Skip to content

Instantly share code, notes, and snippets.

@tbbooher
Created April 5, 2023 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbbooher/fefd20828cdc6a6059f976045058e270 to your computer and use it in GitHub Desktop.
Save tbbooher/fefd20828cdc6a6059f976045058e270 to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def first_fit_decreasing(pieces, plywood_width, plywood_length):
pieces = sorted(pieces, key=lambda x: x[0] * x[1], reverse=True)
bins = []
positions = []
for piece in pieces:
piece_placed = False
for i, bin in enumerate(bins):
if piece[0] <= bin[0] and piece[1] <= bin[1]:
positions.append((i, bin[0] - piece[0], plywood_length - bin[1]))
bins[i] = (bin[0] - piece[0], bin[1] - piece[1])
piece_placed = True
break
if not piece_placed:
bins.append((plywood_width - piece[0], plywood_length - piece[1]))
positions.append((len(bins) - 1, 0, plywood_length - piece[1]))
return bins, positions
def visualize_cuts(pieces, plywood_width, plywood_length, positions):
fig, ax = plt.subplots(figsize=(10, 5))
ax.set_xlim(0, plywood_width)
ax.set_ylim(0, plywood_length)
for i, piece in enumerate(pieces):
pos = positions[i]
rect = patches.Rectangle((pos[1], pos[2]), piece[0], piece[1], linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
ax.annotate(f"{piece[0]}x{piece[1]}", (pos[1] + piece[0] / 2, pos[2] + piece[1] / 2), color='b', fontsize=10, ha='center', va='center')
plt.show()
# Example usage:
plywood_width = 96 # 8 feet
plywood_length = 48 # 4 feet
pieces = [(20, 30), (40, 20), (10, 10), (20, 20), (10, 15)]
_, positions = first_fit_decreasing(pieces, plywood_width, plywood_length)
visualize_cuts(pieces, plywood_width, plywood_length, positions)
print(positions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment