Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Boss Fight in Python
In this problem, we have a fighters list representing fighters (where 1 = fighter) and a bosses matrix where each row represents a boss formation (where 1 = boss). Fighters can defeat a boss row only if they have more fighters than that boss row has bosses. We need to return the remaining undefeated boss rows.
Problem Understanding
Given fighters = [0,1,1] (2 fighters total) and the boss matrix:
Algorithm Steps
- Count total fighters in the
fighterslist - For each boss row, count the number of bosses
- Keep rows where fighters ? bosses (fighters cannot defeat)
- Return the surviving boss rows
Implementation
class Solution:
def solve(self, fighters, bosses):
fighter_cnt = sum(fighters)
result = []
for row in bosses:
if fighter_cnt <= sum(row):
result.append(row)
return result
# Test the solution
ob = Solution()
fighters = [0, 1, 1]
bosses = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
print(ob.solve(fighters, bosses))
[[0, 1, 1], [1, 1, 1]]
Step-by-Step Execution
Let's trace through the algorithm:
def solve_with_details(fighters, bosses):
fighter_cnt = sum(fighters)
print(f"Total fighters: {fighter_cnt}")
result = []
for i, row in enumerate(bosses):
boss_cnt = sum(row)
can_defeat = fighter_cnt > boss_cnt
print(f"Row {i}: {row} ? {boss_cnt} bosses, Can defeat? {can_defeat}")
if not can_defeat: # Keep if cannot defeat
result.append(row)
return result
fighters = [0, 1, 1]
bosses = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
result = solve_with_details(fighters, bosses)
print(f"Surviving boss rows: {result}")
Total fighters: 2 Row 0: [0, 0, 0] ? 0 bosses, Can defeat? True Row 1: [0, 0, 1] ? 1 bosses, Can defeat? True Row 2: [0, 1, 1] ? 2 bosses, Can defeat? False Row 3: [1, 1, 1] ? 3 bosses, Can defeat? False Surviving boss rows: [[0, 1, 1], [1, 1, 1]]
Alternative Approach Using List Comprehension
def boss_fight_compact(fighters, bosses):
fighter_count = sum(fighters)
return [row for row in bosses if sum(row) >= fighter_count]
fighters = [0, 1, 1]
bosses = [[0, 0, 0], [0, 0, 1], [0, 1, 1], [1, 1, 1]]
result = boss_fight_compact(fighters, bosses)
print(result)
[[0, 1, 1], [1, 1, 1]]
Conclusion
The boss fight algorithm compares total fighter count against each boss row's count. Boss rows survive only when they have equal or more bosses than available fighters. The solution uses simple counting and filtering to determine which boss formations remain undefeated.
Advertisements
