# [SOLVED] Creating a random play function in R

## Issue

I want to create a gambling game that does the following:

It is a lottery, which asks for 5 numbers comprised between 01 and 43 and an additional number comprised between 01 and 16; the idea is that I give my 6 numbers and it tells me if I won or not.

To do so, use this code

``````Lotery = function(a,b,c,d,e,f){
NumeroAleatorio <- matrix(1:6,   ncol = 6)
NumeroAleatorio[1] <- sample (1:43, 1, replace= FALSE)
for (i in 2:6) {
if(i!=6){
NumeroAleatorio[i] <- sample (1:43, 1, replace= FALSE)
if(i == 2){
while(NumeroAleatorio[i] == NumeroAleatorio[1] ){
NumeroAleatorio[i] <- sample (1:43, 1, replace= FALSE)
}
}else{
if(i == 3 ){
while(NumeroAleatorio[i] == NumeroAleatorio[1]  || NumeroAleatorio[i] == NumeroAleatorio[2]){
NumeroAleatorio[i] <- sample (1:43, 1, replace= FALSE)
}
}else{
if(i == 4 ){
while(NumeroAleatorio[i] == NumeroAleatorio[1] || NumeroAleatorio[i] == NumeroAleatorio[2]  || NumeroAleatorio[i] == NumeroAleatorio[3]){
NumeroAleatorio[i] <- sample (1:43, 1, replace= FALSE)
}
}else{
if(i == 5 ){
while(NumeroAleatorio[i] == NumeroAleatorio[1] || NumeroAleatorio[i] == NumeroAleatorio[2] || NumeroAleatorio[i] == NumeroAleatorio[3]  || NumeroAleatorio[i] == NumeroAleatorio[4] ){
NumeroAleatorio[i] <- sample (1:43, 1, replace= FALSE)
}
}
}
}
}
}else{
NumeroAleatorio[6] <- sample (1:16, 1, replace= FALSE)
}
}
ContA<-0
ContB<-0
ContC<-0
ContD<-0
ContE<-0
ContF<-0
for(p in 1:6){
if(NumeroAleatorio[p] == a){
ContA<-ContA+1
}
if(NumeroAleatorio[p] == b){
ContB<-ContB+1
}
if(NumeroAleatorio[p] == c){
ContC<-ContC+1
}
if(NumeroAleatorio[p] == d){
ContD<-ContD+1
}
if(NumeroAleatorio[p] == e){
ContE<-ContE+1
}
if(NumeroAleatorio[p] == f){
ContF<-ContF+1
}
}
if(ContA==0 || ContB==0 || ContC==0 || ContD==0 || ContE==0 || ContF==0){
return(data.frame("Resultado", NumeroAleatorio, "Numero escogido",  a, b, c, d, e, f,  "No Ganaste"))
}else{
return(data.frame("Resultado", NumeroAleatorio, "Numero escogido",  a, b, c, d, e, f, "Ganaste"))
}
}
Lotery(20,15,3,45,9,8)
``````

It seems to work, but I want to know if I can make things simpler because I think the code is too long.

## Solution

I may not be following your code, but it looks like you randomly select 6 numbers and compare them to the numbers submitted. None of the first 5 should match, but the 6th can match one of the first 5. If that is correct then this will generate the random 6 numbers:

``````NumeroAleatorio <- c(sample.int(43, 5, replace=FALSE), sample.int(16, 1))
``````

To compare this to the submitted values, just use

``````NumeroAleatorio == comp
``````

All FALSE indicates no matches. Any TRUE values indicate a match at that position.