Home > Mobile >  how to create A sequence of M natural numbers from 1 to N without duplication?
how to create A sequence of M natural numbers from 1 to N without duplication?

Time:05-04

Write a function that returns all the Barcode that can be created in an array when M must be an even sequence of natural numbers from 1 to N and the length must be M.*

condition

  • The sequence must be printed in increasing order in dictionary order.
  • Barcode must be returned as a number.
function test (N, M) {
  
  
};

outputs should go like below

const output1 = test(2, 1); console.log(output1); // --> [1, 2]

const output2 = test(3, 2); console.log(output2); // --> [12, 13, 21, 23, 31, 32]

const output3 = test(3, 3); console.log(output3); // --> [123, 132, 213, 231, 312, 321]

I've tried solve this for hours , but I still can't get it. ... It's hard to even start. I would appreciate it if you could help me solve the code.

CodePudding user response:

try this

const test = (n, m) => {
  
  if(m > n){
   return []
  }

  const numbers = Array(n).fill(1).map((n, i) => (n   i).toString())

  const loop = (arr, res, elements) => {
    if (elements === 0) {
      return res.join('')
    }


    return arr.flatMap((a, i) => loop(arr.filter(b => b !== a), [...res, a], elements - 1))


  }
  return loop(numbers, [], m)
}

console.log(test(1, 1))
console.log(test(2, 1))
console.log(test(3, 2))
console.log(test(5, 3))

Explanation

first there is a check to ensure that m is lesser than n because in that case there are no possible combination

Internally this function uses a recursive function loop to calculate all possible combination of length m

the arguments are

  • arr an array of elements
  • res an accumulator of previous selected element
  • elements the number of elements missing

at first the loop function is called with numbers as array , empty array as res and m as number of elements

First it checks if elements is zero (exit condition)

Then there it take the arr and do a flatMap over it

Foreach element it call the loop function recursively with argument

  • arr previous array without current element
  • res previous res this element
  • elements - 1

example (2, 2)

first run loop(['1', '2'], [], 2)

elements > 0

loop(['2'], ['1'], 1)

  • loop([], ['1', '2'], 0) -> return ['1', '2'].join('') = '12'

loop(['1'], ['2'], 1)

  • loop([], ['2', '1'], 0) -> return ['2', '1'].join('') = '21'
  • Related