Generating Unique Random Numbers in an Array using Loop

后端 未结 6 2023
臣服心动
臣服心动 2020-12-12 01:36

So the question is to develop a [5][5] table, each containing unique numbers from 1-100 (no duplicates)

so here\'s what I came up with:

#inc         


        
6条回答
  •  轮回少年
    2020-12-12 01:50

    Here is some pseudo code to solve it:

    • Create a "list" of length 100 containing the numbers 1...100 called "numbersAvailable"
    • In your inner loop set index = (int)rand() * numbersAvailable; and the take the number numbersAvailable.get(index); and then do numbersAvailable.remove(index);

    In Java creating a list is easy. If you like to stick to C you have to emulate this via arrays. (I can write down the solution, but this looks like a homework, so I leave something for you).

    Note: In contrast to a trial-and-reject solution, this solution has the advantage of a fixed amount of time needed to construct the result.

提交回复
热议问题