I’m quite new to JavaScript and I’m trying to implement my code in pseudocode in JavaScript, however I’m not getting the result that I’m supposed to. I want the function to permute the elements of the array p places to the left. In pseudocode I’m using a queue data structure, but I thought I can as well us an array. As the result of my function, I get an array with [2, 2, 2, 2]. Can you please help me out?
My code in pseudocode:
JavaScript
x
40
40
1
Function PERMUTEVECTOR(row, p)
2
3
If p=0 then
4
5
Return row
6
7
End if
8
9
New Queue q
10
11
For 0<= i <4 do
12
13
ENQUEUE[row[i], q]
14
15
End for
16
17
18
19
For 1<= i <= p do
20
21
ENQUEUE[HEAD[q],q]
22
23
DEQUEUE[q]
24
25
End for
26
27
28
29
For 0<=i<4 do
30
31
Row[i] <- HEAD[q]
32
33
DEQUEUE[q]
34
35
End for
36
37
Return row
38
39
End function
40
My code in JavaScript:
JavaScript
1
56
56
1
function permute_vector(row, p)
2
3
{
4
5
if (p=0)
6
7
{return row}
8
9
10
11
let q = new Array()
12
13
for (i=0; i<4; i++)
14
15
{
16
17
q.push(row[i])
18
19
}
20
21
22
23
for (i=0; i<p; i++)
24
25
{
26
27
q.push(q[0])
28
29
q.pop()
30
31
}
32
33
34
35
for (i=0; i<4; i++)
36
37
{
38
39
row[i] = q[0]
40
41
q.pop()
42
43
}
44
45
return row
46
47
}
48
49
50
51
px = permute_vector([2,4,1,3], 1)
52
53
console.log("px is:", px)
54
55
}
56
I did the same in Python and it works fine:
JavaScript
1
28
28
1
def permute_vector(row, p):
2
3
if p==0:
4
5
return row
6
7
q = []
8
9
for i in range(4):
10
11
q.append(row[i])
12
13
14
15
for i in range(p):
16
17
q.append(q[0])
18
19
q.pop(0)
20
21
for i in range(4):
22
23
row[i] = q[0]
24
25
q.pop(0)
26
27
return row
28
What am I doing wrong with my JavaScript code?
Many thanks!
Advertisement
Answer
In javascript, Array.pop() removes the last element. You need Array.shift() for removing the first one.
JavaScript
1
57
57
1
function permute_vector(row, p)
2
3
{
4
5
if (p===0) // in js, checks are with == (loose) or === (strict).
6
// = is for assignment and you were assigning p to 0 here.
7
8
{return row}
9
10
11
12
let q = new Array()
13
14
for (i=0; i<4; i++)
15
16
{
17
18
q.push(row[i])
19
20
}
21
22
23
24
for (i=0; i<p; i++)
25
26
{
27
28
q.push(q[0])
29
30
q.shift() // shift instead of pop
31
32
}
33
34
35
36
for (i=0; i<4; i++)
37
38
{
39
40
row[i] = q[0]
41
42
q.shift() // shift instead of pop
43
44
}
45
46
return row
47
48
}
49
50
51
52
px = permute_vector([2,4,1,3], 1)
53
54
console.log("px is:", px)
55
56
}
57