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?

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

Using Position:

Position[WinnerList, winner] // Flatten
  • $\begingroup$ We both had the same idea, but I think it is better to flatten the results for the OPs purposes. $\endgroup$ – m_goldberg Dec 2 '13 at 1:06
  • $\begingroup$ @m_goldberg I did flatten. Just in postfix. Aka, the lazy man method. $\endgroup$ – kale Dec 2 '13 at 3:19
  • $\begingroup$ So you did. I don't know how I missed that. $\endgroup$ – 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]

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
And @@ With[{max = Max[winners]}, scores[[#]] == max & /@ indices]

A more functional approach:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.