# think you’re good at puzzles? try this one.

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)

1. neil says:

read the first number – that’s it

2. Bruce says:

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

3. Gp says:

I solved it.

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
}
int count=0;
int number;
foreach(key in list)
{
if(list.get(key) > count)
{
count = list.get(key)
number = key
}

}
return number

4. Gp says:

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.