Skip to content

Instantly share code, notes, and snippets.

@niclasnilsson
Created February 17, 2011 08:00
Show Gist options
  • Save niclasnilsson/831269 to your computer and use it in GitHub Desktop.
Save niclasnilsson/831269 to your computer and use it in GitHub Desktop.
Second stab at shortening a sting. Is this brute enough?
$cache = {}
def shorten(s, ws)
$cache[s] ||= ws.flat_map { |w|
a = s.split(w, -1)
(0..a.size-1).map { |p|
ns = a[0..p].join(w) + a[p+1..-1].join(w)
ns.size < s.size ? shorten(ns, ws) : s
}
}.min_by { |s| s.size }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment