Last active
August 29, 2015 14:01
-
-
Save ifukazoo/6bce8fbb55c8aa51064b to your computer and use it in GitHub Desktop.
Code IQ チケットゴブル問題
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/ruby -w | |
# encoding: utf-8 | |
require 'date' | |
class Ticket | |
def initialize(string) | |
@nation, term = string.split | |
@departure, @arrival = term.split(/-/).map { |e| Date.parse("2012/" + e) } | |
@trip_num = 1 | |
@next = nil | |
end | |
def to_str | |
@departure.to_s + " - " + @arrival.to_s + "\t" + @nation | |
end | |
def add_trip(ticket) | |
@next = ticket | |
@trip_num += ticket.trip_num | |
end | |
attr_reader:nation, :departure, :arrival, :next, :trip_num | |
end | |
def show_continuous(ticket) | |
print ticket.to_str | |
print "\n" | |
if !ticket.next.nil? | |
print show_continuous(ticket.next) | |
end | |
end | |
def show_answer(max_ticket) | |
tickets = [] | |
tickets << max_ticket.nation | |
next_ticket = max_ticket.next | |
while !next_ticket.nil? | |
tickets << next_ticket.nation | |
next_ticket = next_ticket.next | |
end | |
tickets = tickets.sort | |
print tickets.length() | |
tickets.each do |t| | |
print " " | |
print t | |
end | |
end | |
#チケットをファイルから読んで到着順に並べ替える | |
tickets = [] | |
ARGF.each do |line| | |
obj = Ticket.new(line.chomp) | |
tickets << obj | |
end | |
tickets.sort! { |a, b| a.arrival <=> b.arrival } | |
last_max = tickets.size() -1 | |
ticket_idx = tickets.size() -1 | |
#到着順にチェック | |
while 0 <= ticket_idx | |
ticket = tickets[ticket_idx] | |
chk_idx = ticket_idx | |
max_num = 0 | |
max_ticket = nil | |
max_chk = last_max | |
trip_num = 0 | |
# 到着日に対する最長のチケットまで調べる. | |
# | |
# ------ <----------- check | |
# --------- 1 | |
# -------- 1 | |
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
# -------- 1 | |
# ------ 2 <- ここまで調べればOK | |
# ----------- 1 | |
# -- 1 | |
# | |
while chk_idx <= last_max | |
jticket = tickets[chk_idx] | |
if ticket.arrival < jticket.departure | |
trip_num = jticket.trip_num | |
if max_num < trip_num | |
max_num = trip_num | |
max_ticket = jticket | |
max_jdx = chk_idx | |
end | |
end | |
chk_idx = chk_idx + 1 | |
end | |
if !max_ticket.nil? | |
ticket.add_trip(max_ticket) | |
last_max = max_chk | |
end | |
ticket_idx = ticket_idx - 1 | |
end | |
max_trip = tickets.max_by{|c| c.trip_num} | |
#show_continuous(max_trip) | |
show_answer(max_trip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment