使所有可能的组合成一串数字,并在javascript中拆分? [英] Make all possible combos in a string of numbers with split in javascript?

查看:47
本文介绍了使所有可能的组合成一串数字,并在javascript中拆分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一串数字"123456",我想以所有可能的方式对它们进行分割.

I have an string of numbers "123456" i want to split them in all possible ways.

所以

1 23456
1 2 3456
1 23 45 6
1234 5 6
and so on 

我尝试过的...

循环遍历len-1,并在每个索引上拆分,但是从逻辑上讲,它错过了许多可能的情况.

looping over len-1, and splitting on every index, but logically it misses a lot of possible scenarios.

推荐答案

您可以尝试如下所示的递归函数...

You could try a recursive function like below...

<script lang="javascript">

  // Split string into all combinations possible
  function splitAllWays(result, left, right){
    // Push current left + right to the result list
    result.push(left.concat(right));
    //document.write(left.concat(right) + '<br />');

    // If we still have chars to work with in the right side then keep splitting
    if (right.length > 1){
      // For each combination left/right split call splitAllWays()
      for(var i = 1; i < right.length; i++){
        splitAllWays(result, left.concat(right.substring(0, i)), right.substring(i));
      }
    }

    // Return result
    return result;
  };

  var str = "123456";
  var ans = splitAllWays([], [], str);

</script>

结果

123456
1,23456
1,2,3456
1,2,3,456
1,2,3,4,56
1,2,3,4,5,6
1,2,3,45,6
1,2,34,56
1,2,34,5,6
1,2,345,6
1,23,456
1,23,4,56
1,23,4,5,6
1,23,45,6
1,234,56
1,234,5,6
1,2345,6
12,3456
12,3,456
12,3,4,56
12,3,4,5,6
12,3,45,6
12,34,56
12,34,5,6
12,345,6
123,456
123,4,56
123,4,5,6
123,45,6
1234,56
1234,5,6
12345,6

我认为这是正确的结果(32个组合).有人可以确认吗?

I think that is the right results (32 combinations). Can someone confirm?

这篇关于使所有可能的组合成一串数字,并在javascript中拆分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆