Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
galfonso99 opened this issue Mar 12, 2024 · 1 comment
Open

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

galfonso99 opened this issue Mar 12, 2024 · 1 comment

Comments

@galfonso99
Copy link

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
Copy link

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants