I'm making a simple lotto game, but the result is not fixed. Even if I use the set.seed() function, it can't be fixed, how can I fix it?
lotto<-function(game){
z<-matrix(NA, nrow = game, ncol = 6)
colnames(z) <- c('N1', 'N2', 'N3', 'N4', 'N5', 'N6')
for(x in 1:game) {
y <- sample(1:45, 6, replace = FALSE)
print(sort(y))
z[x,] <- sort(y)
}
write.csv(z, 'lotto.csv', row.names = FALSE, fileEncoding = 'UTF-8')
}
lotto(1)
lotto(5)
```
CodePudding user response:
by using set.seed()
every thing is ok see :
set.seed(42)
lotto(1)
#> [1] 1 10 18 25 36 37
lotto(5)
#> [1] 7 20 24 25 36 37
#> [1] 3 25 26 27 36 41
#> [1] 5 20 28 31 34 37
#> [1] 3 24 30 33 40 42
#> [1] 4 8 15 22 36 43
set.seed(42)
lotto(1)
#> [1] 1 10 18 25 36 37
lotto(5)
#> [1] 7 20 24 25 36 37
#> [1] 3 25 26 27 36 41
#> [1] 5 20 28 31 34 37
#> [1] 3 24 30 33 40 42
#> [1] 4 8 15 22 36 43
Created on 2022-05-28 by the reprex package (v2.0.1)
CodePudding user response:
I think that would help :
lotto <- function(game) {
z <- matrix(NA, nrow = game, ncol = 6)
colnames(z) <- c("N1", "N2", "N3", "N4", "N5", "N6")
if (game == 1) {
y <- sample(1:45, 6, replace = FALSE)
print(sort(y))
z[1,] <- sort(y)
} else{
set.seed(NULL)
for (x in 1:game) {
y <- sample(1:45, 6, replace = FALSE)
print(sort(y))
z[x,] <- sort(y)
}
}
write.csv(z,
"lotto.csv",
row.names = FALSE,
fileEncoding = "UTF-8")
}
set.seed(42)
lotto(1)
#> [1] 1 10 18 25 36 37
lotto(5)
#> [1] 6 13 20 23 27 33
#> [1] 7 11 13 19 24 42
#> [1] 10 15 35 38 40 41
#> [1] 15 21 30 31 35 45
#> [1] 15 19 25 35 36 42
set.seed(42)
lotto(1)
#> [1] 1 10 18 25 36 37
lotto(5)
#> [1] 7 11 16 24 27 41
#> [1] 5 10 20 22 25 35
#> [1] 12 13 17 25 27 42
#> [1] 10 25 29 37 39 41
#> [1] 11 20 23 24 26 28
Created on 2022-05-28 by the reprex package (v2.0.1)