Sunday, October 6, 2019

Holes in a Roof, Problem 1 (Greedy)

Holes in a Roof, Problem 1 (Greedy)
In [1]:
### Problem 1: 
### You are given N binary values in a list. This list represents holes in a roof (1 is a hole). 
### You are also given an unlimited number of boards, each with length M. 
### The goal is to determine the minimum number of boards needed to cover all the holes.


# You may want to try coding your own solution without looking at the answer,
# or just implement and understand the following code

def boardsNeeded(binarr, M):
    
    N = len(binarr)
    boards = 0
    last = -1
    for i in range(N):
        if binarr[i] == 1 and last < i:
            boards += 1
            last = i + M - 1
            
    return boards
        
    
testlist = [0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,1,0,1,0,1,0,0,0]
testlength = 10

answer = boardsNeeded(testlist,testlength)
print(answer, "boards with length",testlength,"are required")
2 boards with length 10 are required