Home > Software design >  C - How do I fill an array with certain numbers
C - How do I fill an array with certain numbers

Time:12-09

For example if u have an array of size [250] and u want to fill it with 10% of being '1' , 30% of it being '2' and the rest just '3'. How do i approach this? I know how to fill an array with random numbers but i'm clueless here.

CodePudding user response:

Easiest, if not necessarily fastest - set the first 25 elements to 1, the next 75 elements to 2, and the remaining elements to 3, then do a Fisher-Yates shuffle to randomly reorder them.

CodePudding user response:

Write 25x '1', 75x '2' and the rest '3' using plain for loops, nothing random. Then make an algorithm that shuffles the array by repeatedly swapping two items at random indices and repeat it a certain number of times.

  •  Tags:  
  • c
  • Related