books = gets.to_i.times.map{gets.split(" ")} series = ["iti", "ni", "san", "yon"] num_of_sorted_items = 0 books_last_index = books.length-1 while num_of_sorted_items < books_last_index do (1..books_last_index-num_of_sorted_items).each do |index| if books[index][0] < books[index-1][0] then books[index-1], books[index] = books[index], books[index-1] elsif books[index][0] == books[index-1][0] then if series.index(books[index][1]) < series.index(books[index-1][1]) books[index-1], books[index] = books[index], books[index-1] end end end num_of_sorted_items += 1 end books.each{|item| puts "#{item[0]}\s#{item[1]}"}