Solving the BossFight Algorithm

Vanessa Martinez
3 min readMar 2, 2021

--

Continuing with the theme of solving algorithms that involve manipulating matrices, I decided to tackle the bossFight algorithm. Here’s the assignment I received:

You are given a list of integers fighters and a two dimensional list bosses. The fighters list contains 1s and 0s with a 1 representing a fighter. Similarly, each bosses list contains 1s and 0s with a 1 representing a boss. Given that fighters can beat a bosses row if it contains more fighters than bosses, return a new bosses matrix with defeated boss rows removed.

Example input:

bossFight([0, 1, 1], [
[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1]
])

Step 1)

It’s clear I will need to compare the amount of 1s inside the fighters array [0, 1, 1] to the amount of 1s inside each subarray of the bosses matrix. Therefore, since I will need to keep score on who’s winning, I should initialize counters. I should also create the new array of winningBosses, which I will ultimately return at the end of my function.

const bossFight = (fighters, bosses) => {  let fightersCount = 0;
let bossCount = 0;
let winningBosses = [];
}

Step 2)

Next, I will need to check how many 1s the fighters array has, so I can update the fightersCount. For that, I use a for…of loop to iterate over each item in the array and update the counter if the element is equal to 1.

const bossFight = (fighters, bosses) => {  let fightersCount = 0;
let bossCount = 0;
let winningBosses = [];
for (let num of fighters) {
num === 1 ? fightersCount+= 1 : null;
}
}

My fightersCount should now be updated to 2.

Step 3)

Now, I need to do the same for the bosses matrix array, but I will need to use a nested for loop, since my data is also nested.

const bossFight = (fighters, bosses) => {  let fightersCount = 0;
let bossCount = 0;
let winningBosses = [];
for (let num of fighters) {
num === 1 ? fightersCount+= 1 : null;
}
for (let subArr of bosses) {
for (let ele of subArr) {
ele === 1 ? bossCount+= 1 : null;
}
}
}

This will definitely update the bossCount, but since we have several subarrays to get through we need to make sure to compare the count of 1s in each subarray to the count of 1s in the fighters array. Recall that we already know the fightersCount.

Step 4)

So, the final step will be to compare the fightersCount to each bossCount in the outer for loop. If the fightersCount is less than or equal to the bossCount, then we’ll push the winning boss subarray into the winningBosses array. Then, we return it at the end.

The solution will be:

[
[0, 1, 1],
[1, 1, 1]
]

--

--

Vanessa Martinez

Freelance Software Engineer. Experience in JavaScript, React.js, and Ruby on Rails.