Sunday, August 6, 2017

Lisa's Workbook - Problem from HackerRank

Problem Statement:

Lisa just got a new math workbook. A workbook contains exercise problems, grouped into chapters.
  • There are  chapters in Lisa's workbook, numbered from  to .
  • The -th chapter has  problems, numbered from  to .
  • Each page can hold up to  problems. There are no empty pages or unnecessary spaces, so only the last page of a chapter may contain fewer than  problems.
  • Each new chapter starts on a new page, so a page will never contain problems from more than one chapter.
  • The page number indexing starts at .
Lisa believes a problem to be special if its index (within a chapter) is the same as the page number where it's located. Given the details for Lisa's workbook, can you count its number of special problems?
Note: See the diagram in the Explanation section for more details.
Input Format
The first line contains two integers  and  — the number of chapters and the maximum number of problems per page respectively. 
The second line contains  integers , where  denotes the number of problems in the -th chapter.
Constraints
Output Format
Print the number of special problems in Lisa's workbook.
Sample Input
5 3  
4 2 6 1 10
Sample Output
4
Explanation
The diagram below depicts Lisa's workbook with  chapters and a maximum of  problems per page. Special problems are outlined in red, and page numbers are in yellow squares.
There are  special problems and thus we print the number  on a new line.

Problem solution using python 2.7.6:

PageIndex = 1
NumberOfSpecialProblem = 0 #If the problem index is same as the page number
n,k = map(int,raw_input().split()) #Input number of chapters and number of problems per page
t = map(int,raw_input().split()[:n]) #Input number of problems per chapter
for i in t:
    GetFullPage,RemainingProblem = divmod(i, k)
    TotalPagesPerChapter = GetFullPage + (1 if RemainingProblem else 0)
    #Get problem index by it's number
    ProblemIndex = iter(range(1,i+1))
    for _ in range(TotalPagesPerChapter):
        Problem_On_EachPage = [next(ProblemIndex,None) for _ in range(k)]
        #print Problem_On_EachPage
        if PageIndex in Problem_On_EachPage:
            NumberOfSpecialProblem +=1
        PageIndex +=1
print NumberOfSpecialProblem

No comments:

Post a Comment