Drawing Book

Sort by

recency

|

219 Discussions

|

  • + 0 comments

    My math skill sucks pants, java brute force approach for fun

    public static int pageCount(int n, int p) {
    // Write your code here
    List<List<Integer>> book = new ArrayList();
        System.out.println(String.format("n=%d, p=%d ", n, p));
    int numOfPages = n + 1; // +1 is page zero which will always present
    int l = (int) Math.ceil (numOfPages/2.0);
    
    System.out.println("l=" + l);
    
    //create the books
    for (int i = 0; i < l; i++) {
        List<Integer> pages = new ArrayList<>();
        int number = i * 2;
        pages.add(number);
        pages.add(number+1);
        book.add(new ArrayList<>(pages));
    }
    
    //7 pages
    //should be 4 paper
    //7 / 2
    System.out.println("book: " + book);    
    
    int ftbFlip = 0;
    for (int i = 0; i < book.size(); i++) {
        List<Integer> pages = book.get(i);
        System.out.println(String.format("iftb=%d pages=%s", i, pages.toString()));
    
        if (pages.contains(p)) {
            ftbFlip = i;
            break;
        }
    }
    System.out.println("ftbFlip: " + ftbFlip);
    
    int btfFlip = 0;
    for (int i = book.size() - 1; i > 0; i--) {
        List<Integer> pages = book.get(i);
        System.out.println("pages: " + pages);
        if (pages.contains(p)) {
            break;
        } else {
            btfFlip++;
        }
    }
    System.out.println("btfFlip: " + btfFlip);
    
    int result = Math.min(ftbFlip, btfFlip);
    return result;
    }
    
  • + 0 comments
    def pageCount(n, p):
        front = p // 2
        back = (n // 2) - (p // 2)
        return min(front, back)
    
  • + 0 comments
    def pageCount(n, p):
    
        if p == 1:
            return 0
    
        if n - p == 1 and n % 2 == 0:
            return 1
    
    
        return (n - p) // 2 if p > n // 2 else p // 2
    
  • + 0 comments

    Scala

    def pageCount(n: Int, p: Int): Int = {
         //Sample book: 1 - 2 3 - 4 5 - 6 7 - 8 9 - 10 11
            val lastPage = if(n % 2 == 0) n+1 else n
            val firstPage = 0
            
            val fromFirst: Int = p/2
            val fromLast: Int = (lastPage - p)/2
            
            Array(fromFirst, fromLast).min
        }
    
  • + 0 comments

    short c++ solution. the main idea is that we can calculate how many pages to turn to get number 'x' by turning 'x//2' pages (divide with rounding down e.g. 5//2 = 2). It's because on every display of 2 pages there are 2 consecutive pages e.g. (2,3), (3,4) etc. All we gotta do is just see if we can get from 0->p by turning p//2 pages or from n->p which is n//2-p//2.

    int pageCount(int n, int p) {
        int sza = n/2;
        int pp = p/2;
        return min(pp, sza-pp);
    }