1.tcl 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 x3 [expr {$x1 - ($x2 - $x1)}]
  51. set y3 [expr {$y1 - ($y2 - $y1)}]
  52. set x4 [expr {$x2 + ($x2 - $x1)}]
  53. set y4 [expr {$y2 + ($y2 - $y1)}]
  54. if {[in_range $x3 $y3]} {
  55. dict set antinodes [list $x3 $y3] {}
  56. }
  57. if {[in_range $x4 $y4]} {
  58. dict set antinodes [list $x4 $y4] {}
  59. }
  60. }
  61. }
  62. }
  63. puts [dict size $antinodes]