More than 1 year has passed since last update.

What is paiza?

paiza is Japanese recruiting service which uses competitive programming to measure the level of applicants. paiza ranks users by 6 levels based on coding results. Unlike major competitive programming service like Topcoder, it supports a lot of languages including Ruby which is not popular in this world.

Since I usually use Rails, I've chose Ruby as coding language. The items below are the techniques I learned during try.

String#ljust, String#rjust

In paiza, output sometimes needs formatting. Although Ruby has sprintf which can do complex things, in most cases, using String#ljust, String#rjust is enough.

Input

2
apple banana orange
1 2 3

Required output

apple     banana    orange    
1         2         3         

Good

total_rows = gets.to_i
db = []
total_rows.times { db << gets.chomp.split }

db.each do |line|
  # Fill space if str length is less than 10
  formatted = line.map { |str| str.ljust(10) }
  puts formatted.join
end

Array#transpose

Let's consider the problem you have to return the sum of each database column.
You can get labels, number of rows and the data of each row.
Required output is column name and sum.

Input

apple banana orange
5
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6

Required output

apple 17
banana 22
orange 27

One of Ruby's strength is chain of methods. If the requirement was the sum of the values in the same row, you can easily implement it.
Unfortunately, paiza prefers the problem about vertical calculation. Perhaps it may be useful to add a certain difficulty to problems due to the restriction of console which is generally used for output in competitive programming. Implementation using index of array is below

Bad

label = gets.chomp.split
total_rows = gets.to_i
db = []
total_rows.times { db << gets.split.map(&:to_i) }
result = []
# column handling is hard for Ruby
(0...label.size).each do |i|
  sum = 0
  db.each { |line| sum += line[i] }
  result << sum
end

(0...label.size).each do |i|
  puts "#{label[i]} #{result[i]}"
end

Although it works, I sometimes made index counting mistakes for more complicated problems. C-like index isn't natural for Ruby in my humble opinion.

Ruby's array has method transpose which switches row with column. By using it effectively, we can make code nicer to prevent errors.

Good

label = gets.chomp.split
total_rows = gets.to_i
db = []
total_rows.times { db << gets.split.map(&:to_i) }
result = []
# Use tranpose for easy handling
db.transpose.each { |arr| result << arr.reduce(&:+) }

[label, result].transpose.each do |pair|
  puts pair.join(' ')
end