'For Loop in R to find duplicates in single vector WITHOUT built-in functions
I found this as an interview question and can't seem to work a solution. You can't use any built in R functions.
x <- c(77, 12, 4, 8, 77, 2, 4, 12)
answer <- FALSE #int the answer to FALSE
The way I look at it is the loop takes 77 and compares it to the right. Once it see's the next 77 at x[5], it should return answer <- TRUE and the code should stop completely. But pretend the first number isn't a duplicate, then the next time through it doesn't need to look at x[1] again since its already done x[1] vs x[2] on the first pass through.
This is what I've worked on but can't seem to get it. I have n <- length(x). I've added a variable count <- 0 but within the first loop it increments by 1. Then in the next loop I'm saying 'look from count to the end', but not sure if this is correct either. What seems to happen is it doesn't break away at the first duplicate, then gets to the last index in x and compares it against itself, thus returns TRUE, which is incorrect.
for (i in 1:n){ #wasn't sure if this should be 2:n?
count <- count +1
for (stuff in (count:n)){
if (stuff){
answer <- TRUE
break #I thought this would break the entire code when it see's x[1] vs x[5] which is 77 duplicate
}
}
}
answer
Solution 1:[1]
This will work:
x <- c(77, 12, 4, 8, 77, 2, 4, 12)
answer <- FALSE
n <- length(x)
for(count in 1:n){
for(compare in x[-count]){
if(x[count] == compare){
answer <- TRUE
break()
}
}
if(answer){break()}
}
Solution 2:[2]
The following :
!all(duplicated(x))
Seems to work, and does not use either any(), is.element or %in% functions. If you want your teacher to become smarter and learn the definition of 'builtin' functions, you could answer that :)
Edit : Otherwise, a good algorithm can be found there in O(n) time and O(1) extra space.
Solution 3:[3]
This should work:
for (i in x) {
repeats <- length(x[x == i])
if (repeats < 2) {
} else {
print(paste(i, "has duplicates"))
break
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Santiago I. Hurtado |
| Solution 2 | lrnv |
| Solution 3 |
