From: Robert Klemme Date: 2003-11-20T02:42:16+09:00 Subject: Re: Multi-dimensioned sparse array ? "Austin Ziegler" schrieb im Newsbeitrag news:200311192229.932403@PADD... > On Wed, 19 Nov 2003 14:21:19 +0900, Charles Hixson wrote: > > Does anyone have an implementation of a multi-dimensioned sparse > > array? > > What about using hashes? > > msa = Hash.new { |h, k| h[k] = Hash.new } > > If you just use Numeric keys, there's little difference for your > needs. You can subclass Hash to make it act a bit more like an Array > under certain circumstances (e.g., #each would return values in > key-order instead of a key-value pair; you could also do an ordered > hash per [ruby-talk:20551] to potentially save sort times). > > For multi-dimensional auto-vivifying, you could do: > > hash_maker = proc { |h, k| h[k] = Hash.new(&hash_maker) } > msa = Hash.new(&hash_maker) Another option: use a single Hash, *no* hash nesting and arrays as keys: irb(main):012:0> multDim = Hash.new(0) => {} irb(main):013:0> multDim[[1,12]]=4 => 4 irb(main):014:0> multDim[[1,12]]=6 => 6 irb(main):015:0> multDim[[3,12]]=5 => 5 irb(main):016:0> multDim[[1,3]]=34 => 34 irb(main):017:0> multDim[[1,12]] => 6 irb(main):018:0> multDim[[88,66]] => 0 irb(main):019:0> Which of the two has better performance depends on the nature of algorithms you want to do on the matrix. If you subclass Hash and add some methods you can add dimension checks for the keys, some fancy iteration stuff, create vectors on the fly and whatever methods you need for the matrix... Regards robert > http://www.rubygarden.org/ruby?HashOfHashes > > -austin > -- > austin ziegler * austin@halostatue.ca * Toronto, ON, Canada > software designer * pragmatic programmer * 2003.11.19 > * 01.34.12 > >