Permutations of an array of arrays of strings

前端 未结 5 943
鱼传尺愫
鱼传尺愫 2021-02-10 02:07

I simply cannot wrap my head around how to solve this problem and after a thorough search on Google with no results, I turn to you with hopes of a solution.

Given the sa

5条回答
  •  轮回少年
    2021-02-10 02:29

    Well I am not clever enough to comprehend ikegami's solution but I was able to convert it to Javascript for my purposes. I don't know how it works but it is brilliant!

    lists = [["a","b"],["x","y"],["1","2","3"]] 
    
    function factorPermutations(lists) {  
    
    permutations = []
    $iter = 0;
    
    while (1) {
    
        $num = $iter++;
        $pick = []; 
    
        for (l in lists) {
            $r = $num % (lists[l].length );
            $num = ($num - $r) / lists[l].length;
            $pick.push( lists[l][$r])
        } 
        if ($num > 0) break;
    
        permutations.push( $pick);
    }
        return permutations
    } 
    
    console.log(factorPermutations(lists))
    

    Yeah, I left some of the $ signs on variables from the PHP version.

提交回复
热议问题