0

Canaries, parrots and cats live in the apartment in such a number that only K paws. Derive all possible combinations of the number of canaries, parrots, cats living in the apartment with this total number of paws.

Here's a bit of code that I came up with:

function calculateAnimals(maxPaws) {
  if (maxPaws % 2 === 1 || maxPaws === 0) {
    console.log("Sorry, not equal amount of paws");
    return;
  } else if (maxPaws === 8) console.log("Total: 1 canary, 1 parrot, 1 cat");

  let maxCanary = maxPaws / 2,
    maxParrot = maxPaws / 2,
    maxCat = Math.floor(maxPaws / 4);

  while (maxCanary !== 0 || maxParrot !== 0 || maxCat !== 0) {
    console.log(`Total: ${maxCanary} canary, ${maxParrot} parrot, ${maxCat} cat`);
    break;
  }
}
console.log(calculateAnimals(20));

As you can see...I'm stuck =) Can't quite figure out how to print all of the possible combinations. I would be incredibly grateful to the person who will help to add/change the code or point me in the right direction for solving this problem

Ivan
  • 11
  • Is there any requirement that at least one of each is present ? Else for 8 your log is wrong : 4 canary, 0 parrot and 0 cat is also valid. – Alois Christen Nov 03 '22 at 06:26
  • Yeah, you are right. Yes, there can be options like: 4 canaries, 0 parrots, 0 cats... 0 canaries, 4 parrots, 0 cats... and so on – Ivan Nov 03 '22 at 06:32
  • Start with as many cats as possible, and one parrot if needed. Then convert 1 parrot at a time into a canary. When there are 0 parrots, reduce the number of cats by 1, and start with as many parrots as needed. Then convert each parrot to a canary, and repeat until there are 0 cats, 0 parrots, and all canaries. – user3386109 Nov 03 '22 at 06:33
  • 1
    Parrots and canaries don't have any paws... – Paul Hankin Nov 03 '22 at 06:33
  • You have to find all A>=0, B>=0, C>=0 such that 4A+2B+2C=K. You can do that with 2 nested loops -- one for A and one for B, and then the value of C is determined. The trickiest bit is getting the loop start/end points right so that you avoid cases where C is negative. – Paul Hankin Nov 03 '22 at 06:35
  • Hint: start with a simpler problem first: derive all possible combinations of cats and *birds*. Then build on top of this solution. – Rafał Dowgird Nov 03 '22 at 20:17

0 Answers0