# Code hanging inside a For loop

I'm pretty new to Mathematica (and functional programming in general). I'm working on some code to find winners (maximal values) in a list. The code I have that is hanging is this line.

For[i = 1, 1 <= Length[WinnerList] + 1, i++,
If[WinnerList[[i]] == winner, AppendTo[WinnerIndexList, i],]]


Basically, my code goes through a list, and adds the index i from that list to a second list, if the i-th entry is a 'winner'. My code hangs, but I get the correct output if I abort my code. Any ideas?

• Then You should try to identify the infinite loop condition which makes Your code to run forever... – mmal Dec 2 '13 at 0:16
• God I'm blind. Thank you much! – Darakian Dec 2 '13 at 0:24

Using Position:

Position[WinnerList, winner] // Flatten

• We both had the same idea, but I think it is better to flatten the results for the OPs purposes. – m_goldberg Dec 2 '13 at 1:06
• @m_goldberg I did flatten. Just in postfix. Aka, the lazy man method. – kale Dec 2 '13 at 3:19
• So you did. I don't know how I missed that. – m_goldberg Dec 2 '13 at 3:25

As you probably realize by now, your code loops indefinitely because 1 <= Length[WinnerList] + 1 is always true. Now, let's look a better, functional way to solve your problem.

Making some data and getting the count of how many items in the list have the maximum value.

SeedRandom[42]; scores = RandomInteger[99, 1000];
Count[scores, Max @ scores]

11


Finding the indices where the maximum value occurs.

indices = Flatten @ Position[scores, Max @ winners]

{52, 101, 161, 180, 428, 432, 437, 526, 546, 653, 779}


Checking the results.

Length @ indices

11

And @@ With[{max = Max[winners]}, scores[[#]] == max & /@ indices]

True


A more functional approach:

Join[ WinnerIndexList, Pick[ Range@Length@WinnerList, WinnerList, winner ] ]