Member-only story
JavaScript Interview Prep:
Jul 1, 2024
Prompt
A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page 1 is always on the right side.
Solution
//int n = number of pages in the book
//int p = the page number to flip to
function pageCount(n, p) {
const fromFront = Math.floor(p/2);
let fromBack = 0;
if (n%2 == 0 && p%2 !== 0){
fromBack = Math.floor((n-p)/2)+1;
} else {
fromBack = Math.floor((n-p)/2);
}
if (fromFront < fromBack){
return fromFront;
} else {
return fromBack;
}
}