Skip to content

Instantly share code, notes, and snippets.

@odaillyjp
Created January 9, 2013 11:45
Show Gist options
  • Save odaillyjp/4492554 to your computer and use it in GitHub Desktop.
Save odaillyjp/4492554 to your computer and use it in GitHub Desktop.
オフラインリアルタイムどう書く#6 参考問題を解いた。 http://nabetani.sakura.ne.jp/hena/ord6lintersection/
#coding: utf-8
class Intersection
def to_square(p, q)
xs = [p[0], q[0]].min.to_i
xe = [p[0], q[0]].max.to_i
ys = [p[1], q[1]].min.to_i
ye = [p[1], q[1]].max.to_i
pos = Array.new(10, 0)
line = (xs..xe).inject(0) {|a, i| a + (2**i)}
(ys..ye).each {|y| pos[y] = line}
pos
end
def union(a, b)
ary = []
10.times {|i| ary[i] = a[i] | b[i]}
ary
end
def to_block(str)
ary = str.split("-")
a = to_square(ary[0], ary[1])
b = to_square(ary[0], ary[2])
union(a, b)
end
def count_area(a, b)
area = 0
10.times do |i|
tmp = a[i] & b[i]
area += tmp.to_s(2).count("1")
end
area
end
def solve(str)
ary = str.split(",")
a = to_block(ary[0])
b = to_block(ary[1])
count_area(a, b)
end
end
$LOAD_PATH << File.dirname(__FILE__)
require 'rspec'
require 'intersection'
describe Intersection do
before do
@intersection = Intersection.new
end
describe "#to_square" do
before :all do
@exp = [0,0,0,1020,1020,0,0,0,0,0]
end
it "四角形の領域を表す配列を返すこと" do
@intersection.to_square("23","94").should eq @exp
end
it "第一引数のが値が大きくても同じ配列を返すこと" do
@intersection.to_square("94","23").should eq @exp
end
it "それぞれの引数のx値を入れ替えても同じ配列を返すこと" do
@intersection.to_square("93","24").should eq @exp
end
it "それぞれの引数のy値を入れ替えても同じ配列を返すこと" do
@intersection.to_square("24","93").should eq @exp
end
end
describe "#union" do
it "2つの領域を重ねた配列を返すこと" do
a = [0,0,0,1020,1020,0,0,0,0,0]
b = [0,0,0,4,4,4,4,4,4,0]
@intersection.union(a,b).should eq [0,0,0,1020,1020,4,4,4,4,0]
end
end
describe "#to_block" do
it "L字領域を表す配列を返すこと" do
@intersection.to_block("23-94-28").should eq [0,0,0,1020,1020,4,4,4,4,0]
end
end
describe "#count_area" do
it "2つの領域の重なり合っているマス数を返すこと" do
a = [0,0,0,1020,1020,4,4,4,4,0]
b = [0,480,480,480,480,480,511,511,511,511]
@intersection.count_area(a, b).should eq 11
end
end
describe "#solve" do
it "サンプルデータ#1の入力に対して正しい値を返すこと" do
input = "23-94-28,89-06-51"
@intersection.solve(input).should eq 11
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment