Quite easy if you closely read the question. My solution is in Python:
Spoiler:Code:import sys def probHeads(n): if n == 0: return 0 d = pow(2,n) sum = 0 for x in range(1, n+1): sum += d * x / pow(2,x) sum += d * x / pow(2,x) return sum def solve(n, m): solution = probHeads(n) - probHeads(m) return solution if solution > 0 else 0 amount = 0 while True: line = raw_input() if amount == 0: limit = line else: (n,m) = line.split(" ") print "%.2f" % solve(n,m) amount += 1 if amount == limit: sys.exit(0)
Results 1 to 5 of 5
- 15 Jan. 2012 03:51am #1
Interviewstreet CS 2 - Coin Tosses
- 23 Feb. 2012 06:37am #2
Grave digging?
Here is my solution in C#. I spent about 20 minutes trying to make the code smaller but I couldn't seem to get it any smaller then what it was without making the variables names smaller of course.
I don't even think this is right. I didn't even follow the rules correctly (disqualified)
PHP Code:static void Main(string[] args)
{
int conHeads = 0, numThrows = 0, landHeads = 0;
while(conHeads < 2)
{
Thread.Sleep(new Random().Next(10, 75));
if (GoThrow() == true)
{
conHeads++; landHeads++;
}
else
{
conHeads = 0;
}
//conHeads = (GoThrow() == true ? conHeads += 1 : conHeads = 0);
//Wouldn't work with conHeads++... ^without times it landed on heads.
numThrows++;
}
Console.WriteLine("Number of throws: " + numThrows);
Console.WriteLine("Times landed on heads: " + landHeads);
Decimal avg = numThrows / landHeads;
Console.WriteLine("Average?: " + Math.Round(avg, 2));
Console.ReadLine();
}
static Boolean GoThrow()
{
// 0 = heads.
return (new Random().Next(0, 2)) == 0 ? true : false;
}
- 23 Feb. 2012 03:35pm #3
- 23 Feb. 2012 09:48pm #4
- 24 Feb. 2012 10:22pm #5
You are correct in that your code is incorrect :p