Created
November 6, 2015 17:12
-
-
Save durrellchamorro/d037714ce6eb794d783f to your computer and use it in GitHub Desktop.
Three Approaches To Reversing A String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
class String | |
def swap!(a,b) | |
self[a], self[b] = self[b], self[a] | |
self | |
end | |
end | |
string1 = "Pneumonoultramicroscopicsilicovolcanoconiosis" | |
string2 = "Pneumonoultramicroscopicsilicovolcanoconiosis" | |
string3 = "Pneumonoultramicroscopicsilicovolcanoconiosis" | |
def fastest_reverse(string) | |
array = string.chars | |
new_array = [] | |
until array.empty? do | |
new_array << array.pop | |
end | |
new_array.join | |
end | |
def reverse(string) | |
array = string.chars | |
new_array = [] | |
string.size.times do | |
new_array << array.pop | |
end | |
new_array.join | |
end | |
def slowest_reverse!(string) | |
index1 = 0 | |
index2 = -1 | |
(string.size / 2).times do | |
string.swap!(index1, index2) | |
index1 += 1 | |
index2 -=1 | |
end | |
string | |
end | |
Benchmark.bm do |x| | |
x.report { fastest_reverse(string2) } | |
x.report { reverse(string3) } | |
x.report { slowest_reverse!(string1) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment