ThePrimeagen / kata-machine

1.28k stars 1.27k forks source link

Off by one error in Two Crystal Ball Solution? #72

Open galfonso99 opened 7 months ago

galfonso99 commented 7 months ago

When I was comparing the solution presented in the Course to the solution I had come up with I noticed the second for loop was possibly excluding a value that needs to be checked (j < jmpAmount instead of j <= jmpAmount). For example, let's say jmpAmount is 3, if the first time you jump by 3 you meet the first floor for which the ball would break, you would then exit the loop go back 3 to index 0 then loop from 0 to 2 (because j < jmpAmount) never encountering the actual answer.

I coded my solution in C to challenge myself a bit and decided to make the problem a bit more fun by making the array have different breaking points (int) for each floor and then also passing the breaking point value of both crystal balls. Here's my code:

int two_crystal_balls(int* stories, int length, int breaking_point) {
  int jump = sqrt(length);
  int floor = -1;
  int i = jump;
  for (; i < length; i+=jump) {
    if (stories[i] >= breaking_point) {break;}
  }
  i -= jump;
  for (int j = 0; j <= jump; j++) {
    if (stories[i + j] >= breaking_point) {
      floor = i + j;
      break;
    }
  }
  return floor;
}
echosonusharma commented 4 months ago

jump will be inclusive that's it.

there was a mistake in the code.

func TwoCrystalBalls(breaks []bool) int {
    l := len(breaks)
    var jmpAmount int = int(math.Sqrt(float64(l)))

    i := jmpAmount

    for ; i < l; i += jmpAmount {
        if breaks[i] {
            break
        }
    }

    i -= jmpAmount

    for j := 0; j <= jmpAmount && i < l; j += 1 {
        if breaks[i] {
            return i
        }

        i += 1
    }

    return -1
}