Skip to content

Instantly share code, notes, and snippets.

@blabos-zz
Created September 18, 2013 20:55
Show Gist options
  • Save blabos-zz/6615547 to your computer and use it in GitHub Desktop.
Save blabos-zz/6615547 to your computer and use it in GitHub Desktop.
diffs
#!/usr/bin/env perl
use strict;
use warnings;
use 5.018;
use Data::Dumper;
use Const::Fast;
const my $N => 1000;
const my $L => 50;
main();
##############################################################################
sub main {
my $lists = init();
my $diffs;
open my $fh, '>', 'result.txt' or die 'cannot open';
say $fh stringfy($_) foreach @{$lists};
foreach my $i ( 0 .. scalar( @{$lists} ) - 1 ) {
foreach my $j ( 0 .. scalar( @{$lists} ) - 1 ) {
say $fh "$i => $j: "
. sprintf( '%0.3f', compare( $lists->[$i], $lists->[$j] ) );
}
}
close $fh;
}
sub init {
my $lists = [];
foreach my $i ( 0 .. $N - 1 ) {
foreach my $j ( 0 .. $L - 1 ) {
$lists->[$i][$j] = range_rand( 1, 9 );
}
}
return $lists;
}
sub stringfy {
join q{,}, map { sprintf '%03d', $_ } sort { $a <=> $b } @{ shift() };
}
sub compare {
my @one = sort { $a <=> $b } @{ shift() };
my @two = sort { $a <=> $b } @{ shift() };
my ( %one, %two );
$one{$_}++ foreach @one;
foreach (@two) {
if ( $one{$_} ) {
$one{$_}--;
}
else {
$two{$_}++;
}
}
my $diffs = 0;
$diffs += $_ foreach values %one;
$diffs += $_ foreach values %two;
return 1 - $diffs / ( @one + @two );
}
sub range_rand {
my ( $a, $b ) = @_;
return $a + int( rand( $b - $a + 1 ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment