From: Simon Conrad-Armes (Curne) Date: 2004-11-06T23:23:11+09:00 Subject: Re: Succ distance between two strings On Nov 6, 2004, at 3:07 PM, David A. Black wrote: > Hi -- > > On Sat, 6 Nov 2004, trans. (T. Onoma) wrote: > >> >> Is there an efficient way to calculate the "succ distance" between >> two strings >> (without iterating over each succession)? Examples: >> >> 'a'..'a' 0 >> 'a'..'b' 1 >> 'a'..'z' 25 >> 'a'..'aa' 26 > > 'a'...'aa'.to_a.size # would be one way That still iterates over all elements but it looks sweet :) Only for large strings would be a problem My stab: def diff_succ s1, s2 t1 = t2 = 0 s1.each_byte{|c| t1 = t1*26 + c - 96} s2.each_byte{|c| t2 = t2*26 + c - 96} t2 - t1 end def t s1, s2 puts "#{s1}..#{s2} => #{diff_succ s1, s2}" end t 'a', 'a' #0 t 'a', 'b' #1 t 'a', 'z' #25 t 'a', 'aa' #26 t 'A', 'B' t 'A', 'Z' t 'A', 'AA' output: a..a => 0 a..b => 1 a..z => 25 a..aa => 26 A..B => 1 A..Z => 25 A..AA => -806 Notice how it breaks on multi-letter uppercase strings? that is because of the -96. Maybe one should just lowercase the args... /Curne -- Mailing lists confuse me. Often I don't recognize my own posts and set about writing a flaming reply where I violently disagree. [curne@curnomatic.dk]