2016-11-16 3 views
0

Ищет способ последовательно найти различные возможности компоновки массива. Я только забочусь о том, чтобы добавлять их последовательно, не нужно пропускать или перетасовывать значения.Перестановка перьев

Пример:

var array = [a, b, c, d, e, f]; 

Желаемый выход:

a 
ab 
abc 
abcd 
abcde 
abcdef 

Он должен быть внутри петли, так что я могу сделать расчет с каждым возможным выходом.

+1

Что такое a, b, c? переменные? строки? кусочки линта? –

+0

в том, что весь желаемый результат? Как насчет персонажей в другом порядке? – derp

ответ

1

Вы можете перебирать каждый символ один раз и должен быть в состоянии заполнить все последовательности.

Вот что вы могли бы сделать.

var inputArray = ['a', 'b', 'c', 'd', 'e', 'f']; 
 

 
var outputStrings = []; 
 

 
inputArray.forEach((item, idx) => { 
 
    let prevString = (idx !== 0) ? outputStrings[idx - 1] : ""; 
 
    outputStrings.push(prevString + item); 
 
}); 
 

 
console.log(outputStrings);

0

Вы можете легко уменьшить массив, нарезая массив на текущий индекс.

var inputArray = ['a', 'b', 'c', 'd', 'e', 'f']; 
 

 
var outputArray = inputArray.reduce(function(result, item, index, arr) { 
 
    return result.concat(arr.slice(0, index + 1).join('')); 
 
}, []); 
 

 

 
document.body.innerHTML = '<pre>' + outputArray.join('\n') + '</pre>';

Примечание: Я до сих пор не уверен, что вы подразумеваете под "найти различные возможности расположения массива".

0

var array = ['a', 'b', 'c', 'd', 'e', 'f']; 
 
results = []; 
 
for (x = 1; x < array.length + 1; ++x) { 
 
    results.push(array.slice(0, x).toString().replace(/,/g, "")) 
 
} 
 
//PRINT ALL RESULTS IN THE RESULTS VARIABLE 
 
for (x = 0; x < results.length; ++x) { 
 
    console.log(results[x]) 
 
}

0

Вы должны рекурсивную функцию, чтобы сделать это.
Поскольку количество возможного расположения вашего массива равно 6! (что равно 720), я сокращу его до 3, чтобы сократить результат выборки, сделать число возможных аранжировок до 3! (Который 6)

var array = ['a', 'b', 'c']; 
 
var counter = 0; //This is to count the number of arrangement possibilities 
 

 
permutation(); 
 
console.log(counter); //Prints the number of possibilities 
 

 
function permutation(startWith){ 
 
    startWith = startWith || ''; 
 
    for (let i = 0; i < array.length; i++){ 
 
     //If the current character is not used in 'startWith' 
 
     if (startWith.search(array[i]) == -1){ 
 
      console.log(startWith + array[i]); //Print the string 
 
       
 
      //If this is one of the arrangement posibilities 
 
      if ((startWith + array[i]).length == array.length){ 
 
       counter++; 
 
      } 
 
       
 
      //If the console gives you "Maximum call stack size exceeded" error 
 
      //use 'asyncPermutation' instead 
 
      //but it might not give you the desire output 
 
      //asyncPermutation(startWith + array[i]); 
 
      permutation(startWith + array[i]); 
 
     } 
 
     else { 
 
      continue; //Skip every line of codes below and continue with the next iteration 
 
     } 
 
    } 
 
    function asyncPermutation(input){ 
 
     setTimeout(function(){permutation(input);},0); 
 
    } 
 
}

Первый выход 3 часть вашего желаемого выхода. Надеюсь, что это ответ на ваш вопрос.

Смежные вопросы