# The nested loop cannot be stopped

Warrior Source

I'm testing a nested loop. The idea is to first loop through i and k, add them up, and loop through j (j has to be not equal to k). The loop runs for so long that I have to manually stop the loop. Since it's a small data, I know it shouldn't take that long, but can't figure out where it goes wrong. Below is the sample data.

``````test = data.frame(ID = c(1,2,3), s= c(0.4,0.3,0.3), j1 = c(0.3,0.22,0.15), j2 = c(0.11,0.58, 0.02))
``````

This is the code:

``````j = 1
k = 1

firstsum = 0
tm1 <- system.time(
while (j <= nrow(test)){
while (k <= nrow(test)){
if (k == j) {
next
} else {
for (i in 3:4){

normindator = normindator + (test[j,i] * test[k, i])
denominator = denominator + test[j, i] * test[j, i]
firstsum = firstsum + norminator/denominator * test[k, 2]
k = k + 1
normindator = 0
denominator = 0
}
}
}
secondsum = 0
secondsum = secondsum + firstsum * test[j,2]
j = j + 1
k = 1
}
)
``````
r

### Answers

answered 4 months ago zack #1

using `next` skipped the increment of `k`. Try this version of your loop

``````test = data.frame(ID = c(1,2,3), s= c(0.4,0.3,0.3), j1 = c(0.3,0.22,0.15), j2 = c(0.11,0.58, 0.02))

j = 1
k = 1

firstsum = 0
tm1 <- system.time(
while (j <= nrow(test)){
while (k <= nrow(test)){
if (k != j) {
for (i in 3:4){
normindator = 0
denominator = 0

normindator = normindator + (test[j,i] * test[k, i])
denominator = denominator + test[j, i] * test[j, i]
firstsum = firstsum + normindator/denominator * test[k, 2]

}
}
k = k + 1
}
secondsum = 0
secondsum = secondsum + firstsum * test[j,2]
j = j + 1
k = 1
}
)
``````

comments powered by Disqus