0

Inspired by the leetcode challenge for two sum, I wanted to solve it in R. But while trying to solve it by brute-force I run in to an issue with my for loop.

So the basic idea is that given a vector of integers, which two integers in the vector, sums up to a set target integer.

First I create 10000 integers:

set.seed(1234)
n_numbers <- 10000
nums <- sample(-10^4:10^4, n_numbers, replace = FALSE)

The I do a for loop within a for loop to check every single element against eachother.

# ensure that it is actually solvable
target <- nums[11] + nums[111]


test <- 0
for (i in 1:(length(nums)-1)) {
  for (j in 1:(length(nums)-1)) {
    j <- j + 1
    test <- nums[i] + nums[j]
    if (test == target) {
      print(i)
      print(j)
      break
    }
  }
}

My problem is that it starts wildly printing numbers before ever getting to the right condition of test == target. And I cannot seem to figure out why.

Godrim
  • 449
  • 2
  • 10
  • I don't know what you're really saying here. When I run it, it (correctly) prints out matches. In this random sample, there are 1058 occurrences where one of `nums` plus another of `nums` equals `target`. What are you expecting? – r2evans Jan 04 '22 at 14:48
  • 1
    Sorry, I want it to stop after the first time there is a match, hence the break. – Godrim Jan 04 '22 at 16:54

1 Answers1

1

I think there are several issues with your code:

First, you don't have to increase your j manually, you can do this within the for-statement. So if you really want to increase your j by 1 in every step you can just write:

 for (j in 2:(length(nums))) 

Second, you are breaking only the inner-loop of the for-loop. Look here Breaking out of nested loops in R for further information on that.

Third, there are several entries in nums that gave the "right" result target. Therefore, your if-condition works well and prints all combination of nums[i]+nums[j] that are equal to target.

Dharman
  • 30,962
  • 25
  • 85
  • 135
JKupzig
  • 1,226
  • 3
  • 13