Skip to content

Instantly share code, notes, and snippets.

@dreamr
Created November 11, 2013 21:49
Show Gist options
  • Save dreamr/e67253f1345f06fd5fea to your computer and use it in GitHub Desktop.
Save dreamr/e67253f1345f06fd5fea to your computer and use it in GitHub Desktop.
functional, lazy, and fast!!! BeQuick Code Challenge
#!/usr/bin/env ruby
# encoding: utf-8
# functional and fast version!
# Not readable unless you know your ruby
dict_lines = ->(file) {
File.readlines(file).lazy
}
sequences = ->(string) {
alpha_only = string.to_s.gsub(/\d|\W/, '')
0.upto(alpha_only.chars.size).map {|i|
alpha_only[i..i+3].upcase
}.select {|word| word if word.chars.size == 4 }
}
dict_hash = ->(dict_lines) {
dict_lines.map {|word|
{ word.gsub(/\d|\W/, '').to_sym => sequences.(word) }
}
}
%w(words.txt sequences.txt).each do |file|
File.delete(file) if File.exists?(file)
end
dict_hash.(dict_lines.("dictionary.txt")).each do |hash|
hash.each do |word, seqs|
next if seqs.none?
File.open("words.txt", "a") {|f| f.puts word.to_s }
File.open("sequences.txt", "a") do |f|
sequences.call(word).each {|seq| f.puts seq }
end
end
end
@dreamr
Copy link
Author

dreamr commented Nov 11, 2013

I have 3 code challenges to do today from different companies. So please let me give this disclaimer: This may not be 100% correct with the amount of info I have on the subject. It should be very close and show what I can do.

solution #1: https://gist.github.com/dreamr/e3a79ae604fda87bfa5e
solution #2: https://gist.github.com/dreamr/e67253f1345f06fd5fea

I heavily used enumerators here to speed this up. The difference is this, in the first example I load the whole dict into a string and then go about doing stuff, operating on that giant string (or array). The second gist reads the dict line by line and operates on that level.

Which one I would deploy would depend on several things:

How jr are the coders I am working with?
How much memory is on production
How big can we expect dictionary to be

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment