Created
February 10, 2014 15:57
-
-
Save jcasimir/8918400 to your computer and use it in GitHub Desktop.
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
# Implement an algorithm | |
# to determine if a string has all unique characters | |
# without using uniq. | |
# What if you can not use additional data structures? | |
# === | |
sample = "abcdę" | |
sample.split('').uniq.count == sample.split('').count | |
sample.split('').uniq.count == sample.length | |
sample.split('').uniq.join == sample | |
# Without uniq: | |
letters = sample.split('') | |
result = true | |
unique_letters = [] | |
letters.each do |letter| | |
if unique_letters.include?(letter) | |
result = false | |
break | |
else | |
unique_letters << letter | |
end | |
end | |
result | |
# In English | |
# 1. Cut the string into a collection of letters | |
# 2. Start with an empty array | |
# 3. Go through the collection of letters and... | |
# A. If the letter is not in the array from (2), add it | |
# B. If the letter is in the array from (2), do nothing | |
# 4. Merge the letters in the array from (2) back into a single string | |
# 5. The letters are all unique if the string from (4) is equal to the original string | |
# 1. From 0 to the length of the string as "i"... | |
# 2. Find the count of the letter at position "i" | |
# 3. Add that count to a total | |
# 4. If total is equal to the length of the string then the letters are unique_letters | |
# 3. If the count is >1 then fail | |
# 4. Otherwise pass | |
sample = "abcd" | |
result = true | |
(0...sample.length).each do |i| | |
if sample.count( sample[i] ) > 1 | |
result = false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment