Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.javascript > #27949
| From | Ben Bacarisse <ben.usenet@bsb.me.uk> |
|---|---|
| Newsgroups | comp.lang.javascript |
| Subject | Re: permuting a JS vector |
| Date | 2015-05-31 20:27 +0100 |
| Organization | A noiseless patient Spider |
| Message-ID | <87a8wkh7jq.fsf@bsb.me.uk> (permalink) |
| References | <47b347a2-ab29-4722-963c-2c616ca7095c@googlegroups.com> |
dr.mtarver@gmail.com writes:
> 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.
Some pointers: your random_n function should use floor not round. You
can remove an array element using a single call to splice (though you
may need to copy the array at the top level, depending on the
requirements you have). The push function returns the new array length,
not an array. This last one is why you get the error.
--
Ben.
Back to comp.lang.javascript | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
permuting a JS vector dr.mtarver@gmail.com - 2015-05-31 11:45 -0700
Re: permuting a JS vector Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-05-31 20:27 +0100
Re: permuting a JS vector dr.mtarver@gmail.com - 2015-05-31 13:09 -0700
Re: permuting a JS vector Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-05-31 22:42 +0100
Re: permuting a JS vector wolfgang zeidler <invalid@invalid.invalid> - 2015-06-01 20:33 +0200
Re: permuting a JS vector Scott Sauyet <scott.sauyet@gmail.com> - 2015-06-05 13:12 -0700
csiph-web