[QUIZ] Text Munger (#76)

Might as well send it in seperately:

puts gets.gsub(/\B[a-z]+\B/i){|s|l=s.length
;l.times{|i|r=rand(l);s[i],s[r]=s[r],s[i]};s}

88 characters in total.

Alex Barrett wrote:

Might as well send it in seperately:

puts gets.gsub(/\B[a-z]+\B/i){|s|l=s.length
;l.times{|i|r=rand(l);s[i],s[r]=s[r],s[i]};s}

88 characters in total.

Hellfire and damnations. Just read the rules. I didn’t realize about the
spoiler period. Sorry guys.

On Apr 22, 2006, at 18:45, Alex Barrett wrote:

Might as well send it in seperately:

puts gets.gsub(/\B[a-z]+\B/i){|s|l=s.length
;l.times{|i|r=rand(l);s[i],s[r]=s[r],s[i]};s}

There was some golf in ruby-talk when that study was mentioned in
Slashdot back in 2003, it was an intensive day :slight_smile: and I blogged some
solutions:

 http://www.advogato.org/person/fxn/diary.html?start=238

The Perl one-liner is just a start, I am sure a Perl golf tournament
would squeeze that one quite a lot.

– fxn

On Apr 22, 2006, at 18:53, Alex Barrett wrote:

spoiler period. Sorry guys.
Argh, I assumed it was over after reading that email, I am very sorry.

– fxn

Xavier N. wrote:

On Apr 22, 2006, at 18:53, Alex Barrett wrote:

spoiler period. Sorry guys.
Argh, I assumed it was over after reading that email, I am very sorry.

– fxn

Looks I’ve caused trouble :confused:
Nice touch with the rand sort though. And the $&!

Xavier N. wrote:

The Perl one-liner is just a start, I am sure a Perl golf tournament
would squeeze that one quite a lot.
I can take off 3. “sort_by” can simply be “sort” as Array overwrites
Enumberable’s implementation.

Alex Barrett wrote:

rand(9) fixes this.

But not 100% satisfactorily. I’ll stick with my first version :slight_smile:

Alex Barrett wrote:

I can take off 3.

But now, sadly, I have to put them back on :confused:

rand on it’s own doesn’t scramble the letters properly. You get the same
gibberish every time. rand(9) fixes this.

Here is my solution. I didn’t focus on trying to make a one-liner,
as others have, but made a couple of methods (shuffle and swap) for
Array which I might find useful in another context.

-albert

‘scramble.rb’:

class Array
def shuffle
# Fisher Yates shuffling of an array
self.length.step(1,-1) do |i|
j = rand(i)
next if j == i - 1
self.swap!(j,i-1)
end
self
end

def swap!(a,b)
# Swap array elements in place.
self[a], self[b] = self[b], self[a]
self
end
end

if ARGV[0] == nil
abort(“Usage: scramble.rb file”)
else
file = ARGV[0]
end

f = File.open(file)
while line = f.gets

Using a regex, shuffle all alphabetic characters which are

‘internal’ within a word.
line.gsub!(/([A-z])([A-z]{2,})(?=[A-z])/) {$1 + $2.split
(//).shuffle.join}
puts(line)
end