1

I need a simple javascript function which takes 3 inputs

1- Start ASCII value
2- End ASCII value
3- String length

The function will loop from starting value to ending value until length has been made.

For example,

start - 65
end - 67
length- 2

I want all the combination (length 2) of ASCII of [ 65, 66, 67 ] that is ["A", "B", "C"]

I would like the output as
AA
AB
AC
BB
BA
BC
CA
CB
CC

murtuza hussain
  • 458
  • 1
  • 7
  • 18

1 Answers1

3

To generate all possible combinations, you can use a recursive generator:

  function* combine(start, end, depth, previous = []) {
    if(depth <= 0) {
      yield previous;
      return;
    }

    for(let i = start; i <= end; i++)
      yield* combine(start, end, depth - 1, [...previous, i]);
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 2
    Lovely `yield`. It's always cool to see that someone can actually use these :D – briosheje Apr 24 '19 at 06:32
  • 1
    Thanks :) I really like the simplicity: There is no need to worry about passing the results up to the caller ... – Jonas Wilms Apr 24 '19 at 06:37
  • I am syntax error `"SyntaxError: Unexpected token ;` – murtuza hussain Apr 24 '19 at 07:50
  • The problem with yield is that it still really really slow. few days ago i compared solution with yield and trivial for(let i. and on yields it was 3 times slower on chrome – Anatoli Klamer Apr 24 '19 at 08:34
  • 1
    @JonasWilms I didn't test it, but I think this will end up in an infinite loop by closely looking at the code. In fact, every recursive combine call will add `65` to the array, ending up in a RangeError. I think a cartesian product here is enough to solve the issue. – briosheje Apr 24 '19 at 08:38
  • 1
    Something like this: https://jsfiddle.net/xp3owc9t/ . I'm not that good at generators, but I think this should work. – briosheje Apr 24 '19 at 08:40
  • 1
    @briosheje that is actually a simplified cartesian product. And yes, I missed a `return`... – Jonas Wilms Apr 24 '19 at 11:08
  • @zxxc that statement is as useless as "cars are faster than planes if the plane is driving on a road" – Jonas Wilms Apr 24 '19 at 11:11
  • @JonasWilms wooops, didn't notice that the return was missing :P. – briosheje Apr 24 '19 at 11:14