Question

I'm having trouble making a function that places a number inside a binary grid. For instance, if i'm given 4 3 2 1, and I have a grid that is 5x5, it would look like the following...

4 4 4 4 1
4 4 4 4 0
4 4 4 4 0 
4 4 4 4 0
0 0 0 0 0 

My current code reads a text file and creates a list that is arranged in descending order. For instance if the text file contained 1 2 3, it would create a list of integers 3 2 1. Also my code prompts for a bin # which creates a binxbin square. I don't know how to actually place in a number 4 for the bin. This is the function that should place in the values which i'm stuck with.

def isSpaceFree(bin, row, column, block):
    if row + block > len(bin):
        return False
    if column + block > len(bin):
        return False
    if bin[row][column] == 0 :
        return True
    else:
        return False
    for r in range(row, row+block):
        if bin[row][column] != 0:
Was it helpful?

Solution

It sounds like isSpaceFree should return True if you can create a square with origin origin (row, column) and size block, without going out of bounds or overlapping any non-zero elements. In which case, you're 75% of the way there. You have the bounds checking ready, and half of the overlap check loop.

def isSpaceFree(bin, row, column, block):
    #return False if the block would go out of bounds
    if row + block > len(bin):
        return False
    if column + block > len(bin):
        return False

    #possible todo:
    #return False if row or column is negative

    #return False if the square would overlap an existing element
    for r in range(row, row+block):
        for c in range(column, column+block):
            if bin[r][c] != 0: #oops, overlap will occur
                return False

    #square is in bounds, and doesn't overlap anything. Good to go!
    return True

Then, actually placing the block is the same double-nested loop, but instead performing an assignment.

def place(bin, row, column, block):
    if isSpaceFree(bin, row, column, block):
        for r in range(row, row+block):
            for c in range(column, column+block):
                bin[r][c] = block

x = [
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
]

place(x, 0, 0, 4)

print "\n".join(str(row) for row in x)

Result:

[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[4, 4, 4, 4, 0]
[0, 0, 0, 0, 0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top