Drawing Book

HackerRank 問題: Drawing Book

Question

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:

When they flip page 1 , they see pages 2 and 3 . Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is n pages long, and a student wants to turn to page p, what is the minimum number of pages to turn? They can start at the beginning or the end of the book.

Given n and p , find and print the minimum number of pages that must be turned in order to arrive at page p.

HackerRank 問題: Drawing Book

Answer

<?php

/*
 * Complete the 'pageCount' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER n
 *  2. INTEGER p
 */

function pageCount($total_pages, $turn_to_page) {
    // find front and end of book flip page times
    $begin_page_flip_times = 1;
    $end_page_flip_times = (int) ceil(($total_pages + 1) / 2);
    // find specific page flip times
    $turn_to_page_flip_times = (int) ceil(($turn_to_page + 1) / 2);

    // calculate turn page from front or end of book flip times
    $front_of_book_flip_page_times = $turn_to_page_flip_times - $begin_page_flip_times;
    $end_of_book_flip_page_times = $end_page_flip_times - $turn_to_page_flip_times;

    // get minimum flip page times
    $minimum_flip_page_times = min($front_of_book_flip_page_times, $end_of_book_flip_page_times);

    return $minimum_flip_page_times;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));

$p = intval(trim(fgets(STDIN)));

$result = pageCount($n, $p);

fwrite($fptr, $result . "\n");

fclose($fptr);

Reference