I ran

across this puzzle a little while ago. I’m still working on it –

now you can too:

*You
have a port that you are reading numbers from. You know that there is one number that
is generated in more than half of the cases. You keep reading numbers arbitrarily
long until you are given a command to stop. When you stop you have to return the number
that has occurred in more than half of the cases.*

(Hint: you don’t

have enough memory to store all the numbers)

read the first number – that’s it

neil: that doesn’t work, because you don’t get to decide when to stop. "you are given a command to stop."

I solved it.

int n = readPort()

int nplusone = readPort()

HashMap list = new HashMap()

while(not told to stop)

{

if (nplusone == n)

{

list.put(n, list.get(n) ? list.get(n)+1:1)

}

n = nplusone

nplusone=readPort()

}

int count=0;

int number;

foreach(key in list)

{

if(list.get(key) > count)

{

count = list.get(key)

number = key

}

}

return number

Oops, I think I found a case where that algorithm doesn’t work. I think that the proper algorithm is to mark the longest chain of consecutive numbers, the number with the longest chain is the one you are looking for. Pidgeon hole principle I think.