DEV Community

Cover image for Road to Genius: advanced #47
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: advanced #47

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

function backtrack(list, tempList, nums, remain, start) {
  if (remain < 0)
    return;
  else if (remain === 0)
    return list.push([...tempList]);
  for (let i = start; i < 💎.length; i++) {
    tempList.push(nums[i]);
    backtrack(list, tempList, nums, 😈 - nums[i], i);
    tempList.pop();
  }
}
function combS(arr, T) {
  const list = [];
  backtrack(list, [], arr.sort((a, b) => a - b), T, 0);
  return list;
}
let A = combS([2, 3, 4], 6);
A = A.length;

// 💎 = ? (identifier)
// 😈 = ? (identifier)
// such that A = 3 (number)
Enter fullscreen mode Exit fullscreen mode

I remember this code, we have encountered this on episode 37 (https://dev.to/codr/road-to-genius-advanced-37-104d). So we don't have to reinvent the wheel today.

We've learned from the past that this backtrack algorithm is making an array of all possible combinations from the array to reach some target number. In this particular case there are 3 (A=3) possible ways to produce 6 with numbers 2, 3 and 4:

6 = 2 + 2 + 2
6 = 3 + 3
6 = 4 + 2
Enter fullscreen mode Exit fullscreen mode

The bug 💎 should be nums because that's what we are iterating.
And 😈 should be remain because at each recursive step it is subtracting a number from the remainder.

coding challenge answer

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Get started and become a certified Codr today at https://nevolin.be/codr/

Top comments (0)