2.tcl 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. set fp [open "input"]
  2. set lines {}
  3. while {[gets $fp line] >= 0} {
  4. lappend lines $line
  5. }
  6. close $fp
  7. set height [llength $lines]
  8. set width [string length [lindex $lines 0]]
  9. proc char_at {x y} {
  10. global lines
  11. return [string index [lindex $lines $y] $x]
  12. }
  13. proc in_range {x y} {
  14. global height width
  15. if {$x < 0 || $x >= $width} {
  16. return 0
  17. }
  18. if {$y < 0 || $y >= $height} {
  19. return 0
  20. }
  21. return 1
  22. }
  23. proc build_antenna_map {} {
  24. global height width
  25. set antenna_map {}
  26. for {set x 0} {$x < $width} {incr x} {
  27. for {set y 0} {$y < $height} {incr y} {
  28. set c [char_at $x $y]
  29. if {$c == "."} {
  30. continue
  31. }
  32. dict update antenna_map $c site_list {
  33. lappend site_list [list $x $y]
  34. }
  35. }
  36. }
  37. return $antenna_map
  38. }
  39. set antenna_map [build_antenna_map]
  40. set antinodes {}
  41. foreach k [dict keys $antenna_map] {
  42. set site_list [dict get $antenna_map $k]
  43. set len [llength $site_list]
  44. for {set i 0} {$i < $len} {incr i} {
  45. for {set j [expr {$i + 1}]} {$j < $len} {incr j} {
  46. set x1 [lindex [lindex $site_list $i] 0]
  47. set y1 [lindex [lindex $site_list $i] 1]
  48. set x2 [lindex [lindex $site_list $j] 0]
  49. set y2 [lindex [lindex $site_list $j] 1]
  50. set delta_x [expr {$x2 - $x1}]
  51. set delta_y [expr {$y2 - $y1}]
  52. while {[in_range $x2 $y2]} {
  53. dict set antinodes [list $x2 $y2] {}
  54. set x2 [expr {$x2 + $delta_x}]
  55. set y2 [expr {$y2 + $delta_y}]
  56. }
  57. while {[in_range $x1 $y1]} {
  58. dict set antinodes [list $x1 $y1] {}
  59. set x1 [expr {$x1 - $delta_x}]
  60. set y1 [expr {$y1 - $delta_y}]
  61. }
  62. }
  63. }
  64. }
  65. puts [dict size $antinodes]