Module: Palindromes

Defined in:
lib/cli.rb,
lib/palindromes.rb,
lib/palindromes/base.rb,
lib/palindromes/chart.rb

Defined Under Namespace

Classes: Base, Chart, Cli

Class Method Summary collapse

Class Method Details

.format(content) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/palindromes.rb', line 38

def format(content)
  # group palindrome with the same count together
  grouped = content.group_by { |word, count| count }

  # sort the grouped palindrome by word and print
  output = []
  grouped.sort.reverse.each do |gkey, gvalue|
    gvalue.sort_by { |k,v| k }.each do |word, count|
      output << "#{word} > #{count}"
    end
  end
  output
end

.read_file(file) ⇒ Object

read file and remove unwanted characters



34
35
36
# File 'lib/palindromes.rb', line 34

def read_file(file)
  File.read(file).downcase.split(/[^a-zA-Z0-9]/).delete_if { |word| word == "" }
end

.run(input_file, output_file, chart_file) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/palindromes.rb', line 7

def run(input_file, output_file, chart_file)
  data = read_file(input_file)
  chart_file = chart_file ? chart_file : 'histogram.png'

  p = Palindromes::Base::new
  p.find(data)

  output = String.new
  output << "\n-- palindromes --\n"
  output << format(p.histograms).join("\n")
  output << "\n-- histogram --\n"
  output << p.histograms.to_s

  if output_file
    puts "generating output... #{output_file}"
    File.write(output_file, output)
  else
    puts output
  end

  # generate histogram chart
  puts "\n-- histogram chart --\n"
  puts "generating chart... #{chart_file}"
  Palindromes::Chart.generate(p.histograms, chart_file)
end