Skip to content
Advertisement

Implementing pseudocode in JavaScript

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:

Function PERMUTEVECTOR(row, p)

    If p=0 then

        Return row

    End if

    New Queue q

    For 0<= i <4 do

        ENQUEUE[row[i], q]

    End for

 

    For 1<= i <= p do

        ENQUEUE[HEAD[q],q]

        DEQUEUE[q]

    End for

 

    For 0<=i<4 do

        Row[i] <- HEAD[q]

        DEQUEUE[q]

    End for

    Return row

End function

My code in JavaScript:

function permute_vector(row, p)

{

  if (p=0)

  {return row}

   

  let q = new Array()

  for (i=0; i<4; i++)

  {

    q.push(row[i])

  }

 

for (i=0; i<p; i++)

  {

    q.push(q[0])

    q.pop()

  }

 

  for (i=0; i<4; i++)

  {

    row[i] = q[0]

    q.pop()

  }

return row

}

 

px = permute_vector([2,4,1,3], 1)

console.log("px is:", px)

}

I did the same in Python and it works fine:

def permute_vector(row, p):

  if p==0:

    return row

  q = []

  for i in range(4):

    q.append(row[i])

  

  for i in range(p):

    q.append(q[0])

    q.pop(0)

  for i in range(4):

    row[i] = q[0]

    q.pop(0) 

  return row

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.

function permute_vector(row, p)

{

  if (p===0) // in js, checks are with == (loose) or === (strict).
             // = is for assignment and you were assigning p to 0 here.

  {return row}

   

  let q = new Array()

  for (i=0; i<4; i++)

  {

    q.push(row[i])

  }

 

for (i=0; i<p; i++)

  {

    q.push(q[0])

    q.shift() // shift instead of pop

  }

 

  for (i=0; i<4; i++)

  {

    row[i] = q[0]

    q.shift() // shift instead of pop

  }

return row

}

 

px = permute_vector([2,4,1,3], 1)

console.log("px is:", px)

}
Advertisement