Sort by

recency

|

2107 Discussions

|

  • + 0 comments

    Simple Python Solution:

    def pageCount(n, p):
        return min( p, n-p +(n%2!=1) )//2
    
  • + 0 comments
    def pageCount(n, p):
        papers=(n//2)+1
        paper=(p//2)+1
        if (papers-paper)<paper:
            return (papers-paper)
        else:
            return paper-1
    
  • + 0 comments

    The problem sounds tough at first but if you think about it, it's a simple division problem. Here's an easy C# solution -

    	public static int pageCount(int n, int p)
        {
            // When iterating from 1 take the celing value
            double pageTurnNeededFromStart = Math.Ceiling((double)(p-1)/2);
            
            // when iterating from end - take the ceiling value if the end page is even, otherwise take floor value
            double pageTurnNeededFromEnd = n%2==0? Math.Ceiling((double)(n-p)/2) : Math.Floor((double)(n-p)/2);
            
            return (int)Math.Min(pageTurnNeededFromStart, pageTurnNeededFromEnd);
        }
    
  • + 1 comment
      int pz = n / 2;
          int p2 = p / 2;
          int high = pz - p2;
          int low  = p2 - 0;
    
          if(low < high)
          {
            return low;
    
          }
          else
          {
            return high;
          }
    
  • + 0 comments

    The AI bros doing L33tCode are heavy now. These 1 liners are ridiculous and help no person. But below hopefully is the logic illustrated by some of the ChatGPT coders.

    public static int pageCount(int n, int p)
        {
            if (p > n)
                return -1; // early exit, can't be done
            
            
            var evenPages = n % 2 == 0;
            
            // p == begin of book, end of book, or left page end of book if odd pages
            if (p == 1 || n == p || (!evenPages && p == n - 1))
                return 0;
            else if (evenPages && p == n - 1)
                return 1;
            
            var fromLeftTurns = (int)Math.Floor((decimal)p / 2);
            var fromRightTurns = (int)Math.Floor((decimal)(n - p) / 2);
            
            return fromLeftTurns <= fromRightTurns ? fromLeftTurns : fromRightTurns;
        }