Skip to content

Instantly share code, notes, and snippets.

@sirhc
Created September 26, 2012 19:15
Show Gist options
  • Save sirhc/3789959 to your computer and use it in GitHub Desktop.
Save sirhc/3789959 to your computer and use it in GitHub Desktop.
Bogosorts in Perl
#!/usr/bin/env perl
use strict;
use List::Util qw( shuffle );
print "Unsorted list: @ARGV\n";
@ARGV = shuffle @ARGV while !is_sorted(@ARGV);
print "Sorted list: @ARGV\n";
sub is_sorted {
return 1 if @_ == 0 || @_ == 1;
return '' if $_[0] > $_[1];
return is_sorted( @_[ 1 .. $#_ ] );
}
__END__
=head1 NAME
bogosort.pl - Bogosort implementation in Perl
=head1 SYNOPSIS
=over
perl B<bogosort.pl> I<NUMBER> [...]
=back
=head1 DESCRIPTION
It's a bogosort . . . in Perl. Seriously, what more do you want?
=head1 Chris Grau L<mailto:cgrau@cpan.org>
=head1 COPYRIGHT AND LICENSE
This program is licensed under the Artistic License v2.0.
=cut
#!/usr/bin/env perl
use strict;
print "Unsorted list: @ARGV\n";
@ARGV = shuffle(@ARGV) while !is_sorted(@ARGV);
print "Sorted list: @ARGV\n";
sub is_sorted {
return 1 if @_ == 0 || @_ == 1;
return 0 if $_[0] > $_[1];
return is_sorted( @_[ 1 .. $#_ ] );
}
sub shuffle {
my ( @list ) = @_;
swap( \@list, $_, rand @list ) for 0 .. $#list;
return @list;
}
sub swap {
my ( $list, $a, $b ) = @_;
@{$list}[ $a, $b ] = @{$list}[ $b, $a ];
}
__END__
=head1 NAME
bogosort2.pl - Bogosort implementation in Perl, with custom shuffle
=head1 SYNOPSIS
=over
perl B<bogosort2.pl> I<NUMBER> [...]
=back
=head1 DESCRIPTION
It's a bogosort . . . in Perl. Seriously, what more do you want?
=head1 Chris Grau L<mailto:cgrau@cpan.org>
=head1 COPYRIGHT AND LICENSE
This program is licensed under the Artistic License v2.0.
=cut
#!/usr/bin/env perl
use strict;
use List::Util qw( shuffle );
BEGIN { $|++ }
my @list = map { Value->new( $_, $ARGV[0] ) } @ARGV[ 1 .. $#ARGV ];
print "Unsorted list: @list\n";
@list = shuffle @list while !is_sorted( @list );
print "Sorted list: @list\n";
sub is_sorted {
my ( @list ) = @_;
return 1 if @list == 0 || @list == 1;
return 0 if $list[0] > $list[1];
return is_sorted( @list[ 1 .. $#list ] );
}
package Value;
use overload
'""' => sub { "$_[0][0]($_[0][1])" },
'>' => sub { $_[0][0] > $_[1][0] || $_[0][1] != $_[1][1] };
sub new {
return bless [ $_[1], Schrodinger's_Side->new($_[2]) ];
}
package Schrodinger's_Side;
use overload
'""' => sub { 0 + $_[0] },
'0+' => sub { ${$_[0]}[rand @{$_[0]}] },
fallback => 1;
sub new {
return bless [ 1 .. $_[1] ];
}
__END__
=head1 NAME
bogosort3.pl - Just when you thought bogosort couldn't get any worse
=head1 SYNOPSIS
=over
perl B<bogosort3.pl> I<SIDES> I<VALUE ...>
=back
=head1 DESCRIPTION
It's a I<crazy> bogosort... in Perl. Using overloaded objects. Seriously, what more do you want?
=head1 AUTHOR
Chris Grau L<mailto:cgrau@cpan.org>
=head1 COPYRIGHT AND LICENSE
This program is licensed under the Artistic License v2.0.
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment