Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!1.eu.feeder.erje.net!newsfeed.fsmpi.rwth-aachen.de!newsfeed.straub-nv.de!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: permuting a JS vector Date: Sun, 31 May 2015 20:27:05 +0100 Organization: A noiseless patient Spider Lines: 39 Message-ID: <87a8wkh7jq.fsf@bsb.me.uk> References: <47b347a2-ab29-4722-963c-2c616ca7095c@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="22223"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+pLam3DTFFvBnghTRpTLljwslxIaHGrq8=" Cancel-Lock: sha1:f+K58s4XuH9MB6WLZkFif6tmqWg= sha1:vtqwV/Cdi7n0dMvRtxmSAp1PuUo= X-BSB-Auth: 1.add6bb3cf2788b9c9a28.20150531202705BST.87a8wkh7jq.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:27949 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.