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

Why not simplify TwoCrystalBalls to this? #64

Open
demakoff opened this issue Nov 9, 2023 · 1 comment
Open

Why not simplify TwoCrystalBalls to this? #64

demakoff opened this issue Nov 9, 2023 · 1 comment

Comments

@demakoff
Copy link

demakoff commented Nov 9, 2023

I think with only one counter (i) it will be more easy to get the logic, and less memory used.
Looks like works in the same way...

export default function two_crystal_balls(breaks: boolean[]): number {
    const jump = Math.floor(Math.sqrt(breaks.length));

    let i = 0;

    for (; i < breaks.length; i += jump) {
        if (breaks[i]) break;
    }

    for (i -= jump + 1; i < breaks.length; i++ ){
        if (breaks[i]) return i;
    }

    return -1;
}
@katayamahide
Copy link

Hi @demakoff,
I really like your simple solution, it looks nice and clear.
I think there are two points to be fixed, though.

  1. unexpected result of i -= jump + 1;
let i = 4,
const jump = 2

i -= jump + 1;  
console.log(i) // might expect 3, but actually got 1. 
  1. In case breaks = [true], the program will return -1;
    If above issue is fixed, the program will return -1 in case the breaks array has only one value, which is true.

So I think.

export default function two_crystal_balls(breaks: boolean[]): number {
    const jump = Math.floor(Math.sqrt(breaks.length));

-   let i = 0;
+   let i = jump;

    for (; i < breaks.length; i += jump) {
        if (breaks[i]) break;
    }

+    i -= jump;
+    for (; i < breaks.length; i++ ){
-    for (i -= jump + 1; i < breaks.length; i++ ){
        if (breaks[i]) return i;
    }

    return -1;
}

Or stick to initializing with zero,

export default function two_crystal_balls(breaks: boolean[]): number {
    const jump = Math.floor(Math.sqrt(breaks.length));

    let i = 0;
    for (; i < breaks.length; i += jump) {
        if (breaks[i]) break;
    }

+     for (i &&= i - jump + 1; i < breaks.length; i++ ){
-     for (i -= jump + 1; i < breaks.length; i++ ){

        if (breaks[i]) return i;
    }

    return -1;
}

Looking forward to seeing your response!

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