Ask coding questions

← Back to all posts
1
C++ help pick randomly from an array

I have an items array called items[6]. I have already assigned variables to the array, but I need a function that randomly selects from the array and adds it to another array called inventory[7]. I also need to make sure it only picks variables that are not already in inventory[7].

Commentshotnewtop
1

Try doing this: -
#incluse<cstdlib> at the top and then
inventory[rand() % inventory.length] to get a random element from the inventory array.

Please let me know if it works.

1

@TheDrone7 Well, I used the library and input the code, but apparently there are "invalid operands to the binary expression 'int'".

1

What if I invited you to multiplayer so you can see?

1

@CPPStudent7308 try inventory[(int)(rand() % inventory.length)] instead. That should cast the result to int.

1

@SPQR Okay, that worked to clear one of the errors, but the compiler doesn't like the percent sign for some weird reason.

1

@CPPStudent7308 maybe (int)rand() instead of just rand()