Skip to content

Instantly share code, notes, and snippets.

/counting.rb Secret

Created February 12, 2014 13:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/93a975cb7aba6dae5a91 to your computer and use it in GitHub Desktop.
Save anonymous/93a975cb7aba6dae5a91 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
def print_usage
puts "Usage: #{$0} <file> words|lines"
puts " #{$0} <file> find <what-to-find>"
end
class LineCounter
# Initialize instance variables
def initialize
@line_count = 0
end
def process(line)
@line_count += 1
end
def print_result
puts "#{@line_count} lines"
end
end
class WordCounter
# Initialize instance variables
def initialize
@word_count = 0
end
def process(line)
@word_count += line.scan(/\w+/).size
end
def print_result
puts "#{@word_count} words"
end
end
class WordMatcher
# Initialize instance variables, using constructor parameter
def initialize(word_to_find)
@matches = []
@word_to_find = word_to_find
end
def process(line)
if line.scan(/#{@word_to_find}/).size > 0
@matches << line
end
end
def print_result
@matches.each { |line|
puts line
}
end
end
# Main program
if __FILE__ == $PROGRAM_NAME
processor = nil
# Try to find a line-processor
if ARGV.length == 2
if ARGV[1] == "lines"
processor = LineCounter.new
elsif ARGV[1] == "words"
processor = WordCounter.new
end
elsif ARGV.length == 3 && ARGV[1] == "find"
word_to_find = ARGV[2]
processor = WordMatcher.new(word_to_find)
end
if not processor
# Print usage and exit if no processor found
print_usage
exit 1
else
# Process the lines and print result
File.readlines(ARGV[0]).each { |line|
processor.process(line)
}
processor.print_result
end
end
import scala.io.Source
args match {
case Array(fileName, "words") => countWords(linesOf(fileName))
case Array(fileName, "lines") => countLines(linesOf(fileName))
case Array(fileName, "find", wordToFind) =>
findWord(linesOf(fileName), wordToFind)
case _ => printUsage()
}
def linesOf(fileName: String) = Source.fromFile(fileName).getLines()
def wordsIn(line: String) = line.split("\\s+")
def countWords(lines: Iterator[String]) = {
val wordsCount = (lines.map { line => wordsIn(line).size }).sum
println(s"Words: ${wordsCount}")
}
def countLines(lines: Iterator[String]) =
println(s"Lines: ${lines.size}")
def findWord(lines: Iterator[String], wordToFind: String) =
for {
(line, idx) <- lines.zipWithIndex
if wordsIn(line).contains(wordToFind)
} {
println(f"${idx}%02d: " + line)
}
def printUsage() = println(
"""Usage: PROG <file> words|lines
| PROG <file> find <what-to-find>""".stripMargin)
@sebnozzi
Copy link

findWord can be re-writen as:

def findWord(lines: Iterator[String], wordToFind: String) =
  for((line, idx) <- lines.zipWithIndex)
    if (wordsIn(line).contains(wordToFind))
      println(f"${idx}%02d: " + line)

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