6 ms·
Simple Ruby implementation counts = Hash.new(0) STDIN.each_line do |line| words = line.downcase.split words.each do |word| counts[word] += 1
by bestinterest 6y ago
Simple Ruby implementation
counts = Hash.new(0)
STDIN.each_line do |line|
words = line.downcase.split
words.each do |word|
counts[word] += 1
end
end
counts.sort_by { |_k, v| -v }.each do |word, count|
p "#{word} #{count}"
end
- petercooper 6y agoAlternative approach depending on preferred readability: STDIN.each .map(&:downcase) .map(&:split) .flatten .tally .sort_by { _2 } .reverse .each { |word, count| puts "#{word} #{count}" } (It has a slightly different performance profile and is slightly slower than the other implementation. 477ms vs 418ms on the KJV dataset for me.)
- frankenst1 6y agoCould you update it so that you have "word count\n" on each line?
- bestinterest 6y agoLike that?
- frankenst1 6y agoYep, this is probably the most readable implementation of all languages so far. I ran it and got 3.59s (Go 0.82s, Rust 1.55s, Shell 42.6s(?)) For accurate diff results, one would need `puts` instead of `p` to get rid of the additional quotes.
- bestinterest 6y agoCheckout Crystal lang one (Ruby but fast), https://github.com/benhoyt/countwords/pull/21/files https://github.com/benhoyt/countwords/pull/21/files seems to keep readability intact and committer is saying it outperforms Go which is interesting.
- frankenst1 6y agoClocks in at 1.48s for me which is faster than Ruby but slower than JavaScript.
- derjames 6y agowith --no-debug --release ?
- frankenst1 6y agocrystal build --no-debug --release simple.cr -o simple-cr