Created
October 10, 2015 08:25
-
-
Save squanto/db61fa70a3f8552d1a6e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'rspec' | |
describe 'Inspector' do | |
describe '.uniq?' do | |
it 'works for a unique string' do | |
expect(Inspector.uniq?('abc')).to be true | |
end | |
it 'works for a repeating string' do | |
expect(Inspector.uniq?('abcabc')).to be false | |
end | |
end | |
describe '.reverse' do | |
it 'reverses strings' do | |
expect(Inspector.reverse('foobar')).to eq 'raboof' | |
expect(Inspector.reverse('hugo')).to eq 'oguh' | |
end | |
end | |
describe '.permutations?' do | |
it 'returns true for permutations' do | |
expect(Inspector.permutations?('abc', 'cba')).to be true | |
expect(Inspector.permutations?('foobar', 'barfoo')).to be true | |
end | |
it 'returns false for non-permutations' do | |
expect(Inspector.permutations?('abcd', 'abc')).to be false | |
expect(Inspector.permutations?('fbar', 'foobaz')).to be false | |
expect(Inspector.permutations?('foo', 'foobaz')).to be false | |
end | |
it 'accounts for whitespace' do | |
expect(Inspector.permutations?('abc ', 'abc')).to be false | |
end | |
end | |
describe '.compress' do | |
it 'compresses strings using the counts of repeated characters' do | |
expect(Inspector.compress('aabcccccaaa')).to eq 'a2b1c5a3' | |
end | |
end | |
end | |
class Inspector | |
class << self | |
def uniq?(str) | |
letters = {} | |
str.each_char do |c| | |
if letters[c].nil? | |
letters[c] = true | |
else | |
return false | |
end | |
end | |
true | |
end | |
def reverse(str) | |
new_string = '' | |
str.each_char { |c| new_string.prepend(c) } | |
new_string | |
end | |
def reverse(str) | |
mid_length = str.length / 2 | |
1.upto(mid_length) do |i| | |
left_char = str[i - 1] | |
right_char = str[-i] | |
str[i - 1] = right_char | |
str[-i] = left_char | |
end | |
str | |
end | |
def permutations?(string_a, string_b) | |
string_a.split('').sort.join == string_b.split('').sort.join | |
end | |
def compress(str) | |
output = "" | |
char = str[0] | |
count = 0 | |
str << " " | |
str.each_char do |c| | |
if char != c | |
output << "#{char}#{count}" | |
count = 1 | |
char = c | |
else | |
count += 1 | |
end | |
end | |
output | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment