Я сделал этот простой алгоритм, но Chrome действует странно, почти как функции, которые рекурсивно не возвращаются ... Задача алгоритма состоит в том, чтобы циклически использовать все возможности массива rs
, который имеет три элемента, которые могут быть либо 0, либо 1.Почему этот рекурсивный алгоритм в JS не работает?
//rs is the list of all variables that can be 0 or 1
//cS, or currentStack is the variable that s
rs = [0, 0, 0];
circ = function(cS)
{
for (pos = 0; pos <= 1; pos ++)
{
rs[cS] = pos;
if (cS + 1 < rs.length)
circ(cS + 1);
}
return 0;
}
circ(0); //this should cycle trough all the possibilities of the rs array, it should look like this:
/*
000 - first element of rs, not last, so continue to the next
000 - second element of rs, not last, so continue to the next
000 - third element of rs, last, so continue with the for loop
001 - the for loop ends, return to the second element
011 - second element of rs, not last, so continue to the next
010 - third element of rs, last, so continue with the for loop
011 - the for loop ends, return to the first element
111 - first element of rs, not last, so continue to the next
101 - second element of rs, not last, so continue to the next
100 - third element of rs, last, so continue with the for loop
101 - the for loop ends, return to the second element
111 - second element of rs, not last, so continue to the next
110 - third element of rs, last, so continue with the for loop
111 - the for loop ends, return to the second element
111 - the for loop ends, return to the first element
111 - return
*/
Однако, это просто выглядит следующим образом:
000
000
000
001
return
Может кто-нибудь сказать мне, почему это происходит? Что я сделал не так?
Что вы хотите в итоге? Вы каждый раз переписываете элементы 'rs'. – pimvdb
Возможный дубликат [JavaScript рекурсивного создания элемента не удается] (http://stackoverflow.com/questions/5333572/javascript-recursive-element-creation-fails) – outis
Это кажется странным способом циклического использования возможных комбинаций: wouldn ' t вложенная петля делает трюк гораздо более читабельным способом? Даже желаемый результат в комментарии в конце вашего кода кажется немного странным, потому что у вас много повторяющихся значений. Почему ваша функция возвращает 0, когда вы вообще не используете возврат? – nnnnnn