permuting a vector in JS

30 views
Skip to first unread message

Mark Tarver

unread,
May 31, 2015, 1:25:56 PM5/31/15
to qil...@googlegroups.com
This JS program is supposed to give a random permutation of a vector.  

function random_n (n) {
  var r = Math.round(n * Math.random()); 
  return r;}

function remove_nth (n, vector) {
  var before = vector.slice(0,n);
  var after = vector.slice(n+1,vector.length);
  var result = before.concat(after);
  return result;}  
 
function rperm (vector) {
  if (vector.length == 0)
     {return []}
     else
     {var n = random_n(vector.length);
      var x = vector[n];
      var newvector = remove_nth(n, vector);
      var recurse = rperm(newvector);
      var result = recurse.push(x);
      return  result} }  

var numbers = [1,2,3];
var perm = rperm(numbers);
console.log(perm);

It fails on https://repl.it/ with TypeError: recurse.push is not a function

Solutions welcome.

Mark

Bruno Deferrari

unread,
May 31, 2015, 3:50:21 PM5/31/15
to qil...@googlegroups.com
Don't use an intermediary `result` variable, just return `recurse`
after doing the `push()` call.

The reason is that `push` mutates the array instead of returning a new
one -- what it returns is the new length, so in your code snippet
`result` ends being a number (and numbers don't have a `push` method,
thats why you get that error message).

> Mark
>
> --
> You received this message because you are subscribed to the Google Groups
> "Shen" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to qilang+un...@googlegroups.com.
> To post to this group, send email to qil...@googlegroups.com.
> Visit this group at http://groups.google.com/group/qilang.
> For more options, visit https://groups.google.com/d/optout.



--
BD

Bruno Deferrari

unread,
May 31, 2015, 3:53:44 PM5/31/15
to qil...@googlegroups.com
The documentation for Array's push method is here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push


>> Mark
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Shen" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to qilang+un...@googlegroups.com.
>> To post to this group, send email to qil...@googlegroups.com.
>> Visit this group at http://groups.google.com/group/qilang.
>> For more options, visit https://groups.google.com/d/optout.
>
>
>
> --
> BD



--
BD
Reply all
Reply to author
Forward
0 new messages