Can any one help me with this challenge from hackerrank 2 days no result?

Hi everyone
Please can someone help me solve that challenge, I came up with many approaches to solve it but I failed in that, this my new approach

function saveThePrisoner(n, m, s) {
    let counter = s-1;
    let arr = [];
    for(let i = 0; i < m; i++){
        counter++;
        arr.push(counter);
        if(counter === n){
            counter = 0;
        }
    }
    return arr[arr.length - 1];
}

this is another approache but no one of these work:

function saveThePrisoner(n, m, s) {
    let counter = s-1;
    for(let i = 0; i < m; i++){
        counter++;
        if(counter === n){
            counter = 0;
        }
    }
    return counter;
}

here is the Link to the challenge if you want to take a look at: save the prisoner challenge

Hey @ansdb, I’m not sure for loop is a right strategy. I suggest you check what % operator does: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder

1 Like

thanks a lot for your help
I know what % operator does, I used it but it doesn’t work here is it

return m%n + (s-1);

what do you think?

Yes, you’ve got it right :slight_smile: The only difference now that it returns 0 instead of n. Try like this:

return n % m + s - 1 || n;
1 Like

Yes, it works thanks a lot for your help but I’m still confused just with that 0 why we need to return n in that case.

Because the last guy’s index equals to number of guys

1 Like

aah okey, yes you’re right it means when we start from the first one and the last candy should be given to the last one the result of m%n + (s-1) = 0 in this case of 0 occurs when there is no remainder and means everyone got 1 candy and we start from distributing 1 not 0 that’s mean 0 is 3

i understand it don’t worry but i can’t explain it well

thanks a lot again for your help i really appreciate it

but it doesn’t pass all the tests just the sample ones

this one:

return m%n + (s-1) || n;

Yeah, my bad :slight_smile: The order is important return (m + s - 1) % n || n;

1 Like

but why we need to reformulate the order even if both are logic and they’re the same I think:
m % n + (s-1) === (s - 1 + m) % n
can you give any case when we need to work with the second one and not the first just to understand more?
for example (7, 19, 2) work just fine with m % n + (s-1)
I’m sorry if I ask a lot of question I just want to understand the problem well :blush:

@ansdb, test saveThePrisoner(20, 10, 15) :wink:

1 Like

yes that’s it, thank you so much again for your help