Head broke.

First in the for loop: for (var j = 0; j <= 7; j++) I push current_position.push(j); As a result, approximately the following array is generated:

 var current_position = []; var cursor = 0; function queens8() { for (var j = 0; j <= 7; j++) { if (check(cursor, j) == true) { cursor++; current_position.push(j); if (current_position.length == 8) { done_positions.push(current_position); console.log(current_position); //выводит на первой итерации: [0, 4, 7, 5, 2, 6, 1, 3] } queens8(); } } current_position.splice(cursor-1, 1); cursor--; return; } 

But if you collect all the arrays in another like this:

 done_positions.push(current_position); 

I get something like this:

 [Array[0], Array[0], Array[0], Array[0], Array[0], Array[0], ...] 

And so all 120 passes. Why are they empty and how to make them not empty?


UPDATE: I fixed the problem, but I don’t understand why it worked:

 done_positions.push([]+current_position); 
  • Okay, nonsense. I fixed this by adding done_positions.push([]+current_position); What!? Why is that? - Telion
  • And what about variables we don’t need to know, telepaths are the same :) - user207618
  • @Other all variable data is entered in the code above, nothing else happens to the arrays, the variable j generated by the for loop. And already the conditions of selection and bringing j into the array are not necessary here and will only clog the purity of the code. I thought so, and so I cut the code as much as possible. - Telion
  • What is current_position , where is it created, how can it be [0, 4, 7, 5, 2, 6, 1, 3] ? "My bewilderment was shared by all Europe" V.Erofeyev - Igor
  • @Igor has added the entire function to the question, now it contains exactly all actions on arrays. - Telion

1 answer 1

Because done_positions.push([]+current_position); puts a new item in done_positions , which is the union of string representations [] and current_position - at the time of execution of this line. And before that you added a link to the same array to done_positions many times.

Update

Yes, done_positions.push([current_position]); creates a new array from one element, but the element all the time is the same current_position .

You need:

 done_positions.push(current_position.slice()); 

or

 done_positions.push(current_position); current_position = []; 
  • What does the link mean? And what if done_positions.push([current_position]); ? This, too, logically adds an array? - Telion
  • I can not understand. How can the same array be when it changes every cycle cycle? - Telion
  • one
    @Levelleor In your code, the current_position array is created once in the string var current_position = []; . Then it is the same object in which you add and remove elements. - Igor