This implementation takes a different approach, rather than simply relying on probability, this method keeps track of the unique values found until all conditions are satisfied.
To achieve this, an empty vector called foundset
is initialized, and an iteration variable iteration
is set to 0. Inside the while
loop, the iteration
variable is incremented, and a new number is chosen using the sample()
function. This function selects a random value from a specified range (in this case, 1 to 5) and assigns it to the pick
variable.
Next, the code checks if the pick
value is already in the foundset
vector. If it's not, it means a unique value has been selected, so it's added to the foundset
vector. This process continues until the length of the foundset
vector reaches 5, indicating that all unique values have been found.
#initialize values foundset <- vector() iteration <-0 while (length(foundset) < 5) { #increament iteration iteration <- iteration +1 #pick a new number pick <- sample(1:5, 1) #see if pick in the set if not add it if (!(pick %in% foundset)) { foundset <- c(foundset, pick) } #exit if all five values are found } print(iteration) print(foundset)
Finally, the iteration
and foundset
vectors are printed, displaying the number of iterations required to find all unique values and the set of unique values themselves.
This method provides a more deterministic approach to finding unique values within a specified range, ensuring that all conditions are met before exiting the loop.
```