[Purdue-pm] fast table lookup of randomly associated items

Joe Kline gizmo at purdue.edu
Wed May 19 12:29:40 PDT 2010


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Say I have a table like the following:

number Item
1-5     A
6       B
7-12    C
13-20   D
21-25   E
26-30   F

Say I then have a random number generator that spits out a number from 1-30.

What is the fastest way to look up the item associated with that random
number?

For more fun, say I want to store that table in a text file what is a
good way to represent that?

I kicked around some ideas and the easiest solution I could come up with
is the following. I settled on JSON since it's a bit more portable than
most and I like its syntax better than YAML.
===================================

#!/usr/local/bin/perl

use 5.010;

use strict;
use warnings;

use File::Slurp;
use JSON;

my $table = q(table.json);
my $json_text = read_file( $table ) ;
my $data = from_json($json_text);

my $number = int(rand(30)+1);
my $item = q(nothing);
foreach my $row ( @$data ) {
  if ( $number > $row->[0] ){
  }
  else {
    $item = $row->[1];
    last;
  }
}

say qq($number associated with $item);

exit(0);

===================================
table.json:

[
 [5,"A"],
 [6,"B"],
 [12,"C"],
 [20,"D"],
 [25,"E"],
 [30,"F"]
]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Red Hat - http://enigmail.mozdev.org

iD8DBQFL9Dwkb0mzA2gRTpkRArivAJ4u0zSffAZp02IUrzplg1G12O51jwCZAZQs
TrHEob9EMRqZFNfZORXhmtg=
=zmeb
-----END PGP SIGNATURE-----


More information about the Purdue-pm mailing list