Generate random numbers without repeating a value: Difference between revisions
Content added Content deleted
(→{{header|Wren}}: Added alternative implementation which simply shuffles the numbers.) |
(→{{header|Go}}: Added alternative implementation which simply shuffles the numbers.) |
||
Line 69: | Line 69: | ||
4 11 9 17 14 16 2 7 6 1 12 20 8 15 5 13 10 18 19 3 |
4 11 9 17 14 16 2 7 6 1 12 20 8 15 5 13 10 18 19 3 |
||
19 13 9 7 5 12 11 17 1 3 16 4 15 14 20 8 6 18 2 10 |
19 13 9 7 5 12 11 17 1 3 16 4 15 14 20 8 6 18 2 10 |
||
</pre> |
|||
<br> |
|||
Alternatively and far more efficiently, we can simply create a list of the required numbers and randomly shuffle them. Go has a standard library function for this which uses the Fisher-Yates (aka Knuth) shuffle. |
|||
<lang go>package main |
|||
import ( |
|||
"fmt" |
|||
"math/rand" |
|||
"time" |
|||
) |
|||
func main() { |
|||
rand.Seed(time.Now().UnixNano()) |
|||
numbers := make([]int, 20) |
|||
for i := 0; i < 20; i++ { |
|||
numbers[i] = i + 1 |
|||
} |
|||
for i := 1; i <= 5; i++ { |
|||
rand.Shuffle(20, func(i, j int) { |
|||
numbers[i], numbers[j] = numbers[j], numbers[i] |
|||
}) |
|||
s := fmt.Sprintf("%2d ", numbers) |
|||
fmt.Println(s[1 : len(s)-2]) |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
13 10 18 7 3 5 17 4 1 11 16 20 9 12 14 2 15 19 6 8 |
|||
19 12 11 1 3 14 7 20 2 18 4 10 9 5 8 6 15 13 16 17 |
|||
10 6 11 3 5 13 15 4 16 12 1 14 20 7 2 19 8 17 9 18 |
|||
4 14 17 15 1 6 12 11 2 3 19 10 9 18 7 13 8 20 16 5 |
|||
13 12 8 3 9 17 14 10 6 2 11 20 19 18 4 7 16 1 15 5 |
|||
</pre> |
</pre> |
||