How to get numbers of variants numerical combinations in javascript?

Viewed 127

I need to implement a function that accepts two parameters - the number of 0 and the number of 1 and determine how many ways to place these 0 and 1 so that there are no two zeros in a row.

For example, I need to find all methods of placing two 0 and two 1.

There are six possible ways to place them: 0011, 0101, 0110, 1001, 1010, 1100.

In three cases there are two zeros in a row: 0011, 1001 and 1100.

I subtract them from the total number and get three possible ways: 0101, 0110 and 1010. So the answer is 3.

First, I'm trying to write script to recognize which cases I need

let arr = ["1100","1010","1001","0011","0101","0110"]
let result = [];
for (let i = 0; i < arr.length; i++){
  let expVal = arr[i];
  for (let p = 0; p < expVal.length; p++){
    if (expVal[p] === expVal[p++] || expVal[p] === "0"){
      result.push(expVal)
    }
  } 
}
console.log(result);

It's does not work. I don't know how to fix it. And I don't understand what I need to do later

2 Answers

The problem you are solving is equivalent to the Fibonacci sequence.

filter for includes '00'

recursive function x generates binary number strings using n0 zeroes, n1 ones. Works by branching to (add a zero, find combos for one less zero)'0'+x(n0-1,n1) and (add a one, find combos for one less 1)'1'+x(n0,n1-1).

let arr = ["1100","1010","1001","0011","0101","0110"]

const x = (n0,n1) =>
  !(n0 === 0 || n1 === 0) ?
    x(n0-1,n1).map(x=>'0'+x).concat(
    x(n0,n1-1).map(x=>'1'+x))
    : ['0'.repeat(n0)||'1'.repeat(n1)]

arr = x(2,2)

console.log(
x(2,2)
)

console.log(arr.filter(x=>x.includes('00')))

There are 2 issues with the code, as far as I can see:

  • You're incrementing p two times: once in the for definition, and once in the execution itself (p++). The second one should be replaced by p+1
  • Also, you're checking if the next character is equal to the current, OR the current character is 0. This should be AND.
    let arr = ["1100","1010","1001","0011","0101","0110"]
    let result = [];
    for (let i = 0; i < arr.length; i++){
      let expVal = arr[i];
      for (let p = 0; p < expVal.length; p++){
        if (expVal[p] === expVal[p+1] && expVal[p] === "0"){
          result.push(expVal)
        }
      } 
    }
    console.log(result);

Changing those two things fixes it.

Related