Message Boards Message Boards

0
|
3825 Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

Format certain numbers inside a RandomSample command?

Posted 6 years ago

Hi! A simple question here. So I want to use RandomSample to get a permutation of a set of integers. Easy enough. But I want a certain range of numbers (say 1-15 out of 50) to appear red so I can pick them out immediately. This second part I'm having some trouble with. Would anyone know how to write this?

Thanks so much!

POSTED BY: Nuliajuk Akesuk
Posted 6 years ago

Hello Nuliajuk,

The easiest way I can think of to do this would use Map to apply Style to the numbers you choose. For example:

list = Map[If[# < 16, Style[#, Red], #] &, RandomSample[Range[50]]]

enter image description here

You should be aware that doing it this way may make further calculations give unexpected answers, like this: enter image description here

As you can see in Out[2], you don't immediately get the answer you might expect. This is because what you've done is to change the internal representation of the items in the list. Instead of simply a list of numbers, the styled numbers now have a new symbolic representation, as seen in Out[3]. This is simple enough to work around if you need to, you just have to add an extra index number to access the number:

enter image description here

This is fine if you only need to do a few quick calculations with those numbers, but could get cumbersome if you're hoping to do a lot more work with this list. If that's the case, then I'd recommend assigning the list to a variable first and then using Map on the variable without making an assignment. This way, your original list stays exactly the same, and you can still inspect the list easily. Here's an example:

enter image description here

I hope that helps!

POSTED BY: Matt Woodbury
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract