We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Save the Prisoner!
Save the Prisoner!
Sort by
recency
|
1658 Discussions
|
Please Login in order to post a comment
C# var warn = (m + s - 1) % n; return warn == 0 ? n : warn;
We calculate the index of the prisoner to warn using the formula (m - 1 + s - 1) % n + 1. (m - 1) calculates the position of the last candy. + s - 1 calculates the starting position of distribution. % n handles the circular nature of the distribution, ensuring the index remains within the range of 1 to n. + 1 adjusts the index to match the numbering of chairs (which starts from 1). If the calculated index is 0, it means it's the last chair, so we set it to n to match the numbering of chairs.
}
Thanks for C_jain and Mikelane's explanation. Since this issue has been a long time in the repo. I was confused at initial attempts to resolve the problem and did some research for this kind of distribution on a cyclic list. I think most of us can figure out mod opertation should be used but still confused why some test cases can pass and others not. The key part is that indexing system are different between mod (0-based indexing) and candy distribution, or any counting in our real life(1-based indexing). So basically, any resoltuion can work as long as it deals with mod on candies and positions twice or turning indexing to 0 and mod once and turning back to 1-indexagain.
My solution in Rust:
c++ solution: int saveThePrisoner(long long n, long long m, long long s) { if((s+m-1)%n==0) return n; else return (s+m-1)%n; }