LoginSignup
1
1

More than 5 years have passed since last update.

perlで配列の順番をばらばらにする

Posted at

意外となかったようでしたので

test.pl
#!/usr/bin/perl
use strict;

my @list=split(/,/,"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20");

srand;
my %temp;
foreach(@list) {
    $temp{$_}=rand;
}

my @newlist;

foreach(keys %temp) {
    push(@newlist, $_);
}

foreach(@newlist) {
    print "$_\n";
}

一度ハッシュのキーに入れてしまうと、ばらばらになるんですよね。

せっかく乱数を使ってるので

test.pl
#!/usr/bin/perl
use strict;

my @list=split(/,/,"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20");

srand;
my %temp;
foreach(@list) {
    $temp{$_}=rand*10000;
}

my @newlist;

foreach(sort { $temp{$a} <=> $temp{$b} }keys %temp) {
    push(@newlist, $_);
}

foreach(@newlist) {
    print "$_\n";
}

こっちのがばらばらの精度が高いでしょう。

1
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1