N Ants

Brain Teasers with Coding Study

Few companies ask the below brain teaser to the candidates during the interview.

Imagine there are 3 ants on three different corners of a triangle, and each ant randomly picks a direction and starts traversing the edge of the triangle. What is the probability that none of the ants collide?

But what if it is a coding challenge:

Imagine there are N ants on N different corners of an equilateral polygon, and each ant randomly picks a direction and starts traversing the edge of the polygon. What is the probability that none of the ants collide? (Provided condition: N>2)

Write a code for the abovementioned problem statement.

The coding solution was originally published in my book “Brain Teasers with Coding For Data Scientist”. Puzzles from that book are published on this link. Also, check my puzzle books “Brain Teasers with Coding For Data Scientist 2: 9 New Computational Puzzles” and “Puzzles with Coding: Puzzles for Everyone” and “Computational Puzzles To Flex Your Brain: 50 original puzzles to sharpen computing mind and mathematical skills at Amazon. For purchasing my books or related queries, feel free to contact me. In these books, you will find interesting brain teasers those are suitable for coders as well as non-coders. Coding solutions are also provided with Python code. So, grab a copy of those books and jump into the world of fascinating and exciting brain teasers.

Solution:

There are only two possibilities in which collision can be occurred.

* All ants move in counterclockwise direction.

* All ants move in anti-counterclockwise direction.

Since every ant has two choices (pick either of two edges going through the corner on which ant is initially sitting). So for N ants there are total 2N possibilities.

Probability that none of the ants collide = (2N – 2)/ 2N = ( 2N-1 – 1)/ 2N-1

Coding Solution

import math
# Non Collide Probability for N ANTS
# N Number of Ants & N > 2
N = int(input("Enter number of ants:"))
if N <= 2:
    print("Number of ants should be greater than 2")
    exit()
    
# P Probability
P = (math.pow(2,N-1)-1)/math.pow(2,N-1)
print('Probability that none of', N, 'ants collide:', P)

Note : (Keeping non-coder readers in mind, code optimization may not be fully utilized.)

Test Output 1:
Enter number of ants:4
Probability that none of 4 ants collide: 0.875

Test Output 2:
Enter number of ants:3
Probability that none of 3 ants collide: 0.75