n00b question. Shuffling a deck (NSMutableArray)

Posts: 3,591
Joined: 2003.06
Post: #16
hypnotx Wrote:I am playing around with the shuffle code from unknown above and I get an error at this line:

[self swapObjectAtIndex:i withObjectAtIndex:random()%([self count]-i)+i];
... error: invalid operands to binary %

Hmm... I'm stumped on that one. It looks like it should work just fine. Did you modify the code that uknown put up? The only reason I can think of off the top of my head at the moment for % to go invalid is trying to supply something other than integers to it (like maybe a float or something).
Quote this message in a reply
Posts: 67
Joined: 2006.06
Post: #17
Maybe you should break that down into more steps so can see stuff better.

int replaceIndex = (random() % ([deck count] - 1));
[self swapObjectAtInex:i withObjectAtIndex:replaceIndex];

But we all know what happens when I try to do things... the sad part is I am going to try and finish my pie graph utility this summer, in a language I hardly remember. Should be fun.

The machine does not run without the coin.
Quote this message in a reply
Posts: 567
Joined: 2004.07
Post: #18
try stuffing parentheses around each operation. Also, print the variables before hand (or use a debugger) to see if anything is wrong. If all else fails, I recommend a rabbits foot and a different approach.

It's not magic, it's Ruby.
Quote this message in a reply
Posts: 834
Joined: 2002.09
Post: #19
Please, write that as:

int randomIndex = random() % ([self count] - i);
int src = i;
int dst = randomIndex + i;
[self swapObjectAtIndex:src withObjectAtIndex: dst];

If nothing else, you'll get the error message on a more granular row number, and you'll be able to inspect the values and see if they make sense.
Quote this message in a reply
Post Reply