U. IMM U. IMM - 1 month ago 5
Javascript Question

Card Stacks Functions is not working

I am new to JavaScript. I don't know why my code does not work. I am creating functions for returning card stacks quantity. The user will input the card stack quantity. Then the card stacks will be remixed with the following rules. But the result does not appear. Can you please help debugging this code..

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p id="demo"></p>

<script>
var reposition = [];
function Reverse(userinput){
var array = new Array(userinput);
var trueform = new Array(userinput);

for(var i=0; i<userinput; i++){
array[i] = i + 1;
trueform[i] = i + 1;
}

while(! (isEqual(trueform,reposition))){
for(var ii=0; ii<userinput; ii++){
reposition[userinput-ii-1] = array[ii];
if((ii+1) != userinput){
swap((ii+1));
}
}
for(var iii=0; iii<reposition.length; iii++){
array[iii] = reposition[iii];
}
count +=1;
}
return count;
}

function swap(n){
var temp = array[n];
for(var iiii=n; iiii<array.length-1; iiii++){
array[iiii] = array[iiii+1];
}
array[array.length-1]= temp;
}

function isEqual(t, r){
for(var iiiii=0; iiiii<t.length; iiiii++){
if(t[iiiii] != r[iiiii]){
return false;
}
}
return true;
}
document.getElementById("demo").innerHTML = Reverse(4);
</script>

</body>
</html>

Answer

The first thing I notice is the variable array is not defined. This is because you are trying to use it in separate functions.

this.array instead of var array

The second thing I notice is that in your while loop you are doing count += 1 which is also not defined anywhere in your code.