patternrubyMinor
Longest lines of file descending
Viewed 0 times
longestfilelinesdescending
Problem
This is a challenge question from codeeval.com:
Write a program which reads a file and prints to stdout the specified
number of the longest lines that are sorted based on their length in
descending order. Input sample:
Your program should accept a path to a file as its first argument. The
file contains multiple lines. The first line indicates the number of
lines you should output, the other lines are of different length and
are presented randomly. You may assume that the input file is
formatted correctly and the number in the first line is a valid
positive integer.
For Example:
Output sample:
Print out the longest lines limited by specified number and sorted by
their length in descending order.
For example:
I think my code is pretty readable.
Write a program which reads a file and prints to stdout the specified
number of the longest lines that are sorted based on their length in
descending order. Input sample:
Your program should accept a path to a file as its first argument. The
file contains multiple lines. The first line indicates the number of
lines you should output, the other lines are of different length and
are presented randomly. You may assume that the input file is
formatted correctly and the number in the first line is a valid
positive integer.
For Example:
2
Hello World
CodeEval
Quick Fox
A
San Francisco
Output sample:
Print out the longest lines limited by specified number and sorted by
their length in descending order.
For example:
San Francisco
Hello World
I think my code is pretty readable.
lines = IO
.readlines(ARGV.first)
puts lines
.drop(1)
.sort_by(&:length)
.last(lines.first.to_i)
.reverse
Solution
Reading a file named on the command line is a common task. I suggest making use of the
Not all lines of the input are to be treated uniformly. Since the first line is to be treated differently, I suggest defining
ARGF to accomplish that.Not all lines of the input are to be treated uniformly. Since the first line is to be treated differently, I suggest defining
lines to exclude it.top_n, *lines = ARGF.to_a
puts lines.sort_by(&:length).last(top_n.to_i).reverseCode Snippets
top_n, *lines = ARGF.to_a
puts lines.sort_by(&:length).last(top_n.to_i).reverseContext
StackExchange Code Review Q#96689, answer score: 3
Revisions (0)
No revisions yet.