[2024][ruby][8.x] refactored

main
Alpha Chen 4 weeks ago
parent 9956d79332
commit 80333f1110
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -6,52 +6,48 @@ input = DATA
}.to_h }.to_h
freqs = input.values.uniq - %w[.] freqs = input.values.uniq - %w[.]
pp freqs.flat_map {|freq| antennae = freqs.to_h {|freq|
antennae = input.select { _2 == freq }.keys [freq, input.select { _2 == freq }.keys]
antennae.combination(2).flat_map {|(ay,ax),(by,bx)| }
pp antennae.values.flat_map {|yxs|
yxs.combination(2).flat_map {|(ay,ax),(by,bx)|
dy = by - ay dy = by - ay
dx = bx - ax dx = bx - ax
[[ay-dy, ax-dx], [by+dy, bx+dx]] [[ay-dy, ax-dx], [by+dy, bx+dx]]
}.select {|yx| input.has_key?(yx) } }.select {|yx|
input.has_key?(yx)
}
}.uniq.length }.uniq.length
def antinodes(input, a, b) def antinodes(input, a, b)
return enum_for(__method__, input, a, b) unless block_given? return enum_for(__method__, input, a, b) unless block_given?
max_y = input.keys.map(&:first).max max_y, max_x = input.keys.transpose.map(&:max)
max_x = input.keys.map(&:last).max
(ay,ax), (by,bx) = a, b r = Rational(*b.zip(a).map { _1 - _2 })
delta = r.numerator, r.denominator
dy = by - ay yx = a
dx = bx - ax
r = Rational(dy, dx)
dy = r.numerator
dx = r.denominator
y, x = a
loop do loop do
break unless input.has_key?([y,x]) break unless input.has_key?(yx)
yield [y,x] yield yx
y -= dy yx = yx.zip(delta).map { _1 - _2 }
x -= dx
end end
y, x = b yx = b
loop do loop do
break unless input.has_key?([y,x]) break unless input.has_key?(yx)
yield [y,x] yield yx
y += dy yx = yx.zip(delta).map { _1 + _2 }
x += dx
end end
end end
pp freqs.flat_map {|freq| pp antennae.values.flat_map {|yxs|
antennae = input.select { _2 == freq }.keys yxs.combination(2).flat_map {|a,b|
antennae.combination(2).flat_map {|a,b|
antinodes(input, a, b).to_a antinodes(input, a, b).to_a
} }
}.sort.uniq.length }.uniq.length
__END__ __END__
............ ............

Loading…
Cancel
Save