Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: shuffle array
- X-seq: zsh-workers 44973
- From: Stephane Chazelas <stephane.chazelas@xxxxxxxxx>
- To: zsh-workers@xxxxxxx
- Subject: Re: shuffle array
- Date: Mon, 2 Dec 2019 15:16:52 +0000
- In-reply-to: <CAN=4vMpt+hQw2zxUC1LH+3bPymBX_5qqexFw-vqkN6ye+dG1ZQ__45487.0572009654$1575297047$gmane$org@mail.gmail.com>
- List-help: <mailto:zsh-workers-help@zsh.org>
- List-id: Zsh Workers List <zsh-workers.zsh.org>
- List-post: <mailto:zsh-workers@zsh.org>
- List-unsubscribe: <mailto:zsh-workers-unsubscribe@zsh.org>
- Mailing-list: contact zsh-workers-help@xxxxxxx; run by ezmlm
- References: <867e3jxtao.fsf@zoho.eu> <20191129064215.GA14095@prometheus.u-strasbg.fr> <8636e7w0w9.fsf__36104.0529723809$1575015640$gmane$org@zoho.eu> <20191201200719.anzbs27c7phgdnmm@chaz.gmail.com> <20191201233848.7selcpkvenlu65px__33142.5388505281$1575243619$gmane$org@tarpaulin.shahaf.local2> <20191202141421.sj7nlhsdrpqxpr42@chaz.gmail.com> <CAN=4vMpt+hQw2zxUC1LH+3bPymBX_5qqexFw-vqkN6ye+dG1ZQ__45487.0572009654$1575297047$gmane$org@mail.gmail.com>
2019-12-02 15:29:17 +0100, Roman Perepelitsa:
> Another alternative is to implement the standard inplace shuffle
> algorithm from scratch:
>
> local -i i
> for ((i = 2; i <= $#l; ++i)); do
> local j=$((RANDOM % i + 1))
shouldn't that be "RANDOM % $#l + 1"?
> # swap l[i] and l[j]
> local tmp=$l[i]
> l[i]=$l[j]
> l[j]=$tmp
> done
>
> Due to RANDOM having a rather narrow range, this will introduce bias
> on large arrays and won't work at all on arrays with more than 32k
> elements. These issues can be mitigated by replacing RANDOM with
> (RANDOM << 15 | RANDOM) or even with (RANDOM << 30 | RANDOM << 15 |
> RANDOM).
[...]
Or use rand48() in zsh/mathfunc
((j = 1 + rand48() * $#l))
--
Stephane
Messages sorted by:
Reverse Date,
Date,
Thread,
Author