Skip to content

Instantly share code, notes, and snippets.

@ngw
Created July 15, 2019 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngw/54a544b7f9dcd8964d7d27ae84c754ac to your computer and use it in GitHub Desktop.
Save ngw/54a544b7f9dcd8964d7d27ae84c754ac to your computer and use it in GitHub Desktop.
module Anagrams
class Dictionary
extend Forwardable
def_delegators :@data, :[]
def initialize(source:)
@data = Hash.new { |hash, key| hash[key] = [] }
parse(File.open(source, 'r'))
end
private
def parse(source)
source.each_line do |line|
word = line.downcase.strip
@data[normalize(word)] << word
end
end
def normalize(string)
string.chars.sort.join
end
end
end
@havenwood
Copy link

#!/usr/bin/env ruby
# frozen_string_literal: true

require 'async'
require 'async/io/stream'

PATH = '/usr/share/dict/words'
DATA = Hash.new { |k, v| k[v] = [] }

def lines(stream)
  Enumerator.new do |yielder|
    while line = stream.read_until("\n")
      yielder << line
    end
  end
end

def normalize(string)
  string.chars.sort.join
end

def process(line)
  Async do
    word = line.downcase.strip
    DATA[normalize word] << word
  end
end

File.open PATH, 'r' do |io|
  stream = Async::IO::Stream.new io

  Async do
    lines(stream).each do |line|
      process line
    end
  end
end

DATA

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