Day3.lua 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. local InstructionSets = require(script.InstructionSets)
  2. local WireWorld = require(script.WireWorld)
  3. local Directions = {
  4. ["U"] = Vector2.new( 0, 1),
  5. ["D"] = Vector2.new( 0,-1),
  6. ["L"] = Vector2.new(-1, 0),
  7. ["R"] = Vector2.new( 1, 0),
  8. }
  9. local function dist(p1,p2)
  10. local xDist = math.abs(p2.X - p1.X)
  11. local yDist = math.abs(p2.Y - p1.Y)
  12. return xDist + yDist
  13. end
  14. local function plot(instructionSet)
  15. local newWorld = WireWorld.new()
  16. local currentPosition = Vector2.new(0, 0)
  17. local collisions = {}
  18. local numSteps = 0
  19. for _, instruction in ipairs(instructionSet) do
  20. local direction, steps = instruction.direction, instruction.steps
  21. local displacement = Directions[direction] * steps
  22. local displacedPosition = currentPosition
  23. -- move x axis
  24. local xDist = displacement.X
  25. local xStepDirection = xDist / math.abs(xDist)
  26. for dx = xStepDirection, xDist, xStepDirection do
  27. local displacedPosition = currentPosition + Vector2.new(dx,0)
  28. numSteps = numSteps + 1
  29. local alreadyHere = newWorld:getTraversed(displacedPosition) ~= nil
  30. if not alreadyHere then
  31. newWorld:setTraversed(displacedPosition, numSteps)
  32. end
  33. end
  34. -- move y axis
  35. local yDist = displacement.Y
  36. local yStepDirection = yDist / math.abs(yDist)
  37. for dy = yStepDirection, yDist, yStepDirection do
  38. local displacedPosition = currentPosition + Vector2.new(0,dy)
  39. numSteps = numSteps + 1
  40. local alreadyHere = newWorld:getTraversed(displacedPosition) ~= nil
  41. if not alreadyHere then
  42. newWorld:setTraversed(displacedPosition, numSteps)
  43. end
  44. end
  45. currentPosition = currentPosition + displacement
  46. end
  47. return newWorld
  48. end
  49. local world1 = plot(InstructionSets[1])
  50. local world2 = plot(InstructionSets[2])
  51. local collisions = WireWorld.getCollisions(world1, world2)
  52. local center = Vector2.new(0, 0)
  53. local closestDist = math.huge
  54. for _, contactInfo in ipairs(collisions) do
  55. local pointDist = dist(center, contactInfo.pos)
  56. if pointDist < closestDist then
  57. closestDist = pointDist
  58. end
  59. end
  60. local lowestCombinedSteps = math.huge
  61. for _, contactInfo in ipairs(collisions) do
  62. local combinedSteps = contactInfo.combinedSteps
  63. if combinedSteps < lowestCombinedSteps then
  64. lowestCombinedSteps = combinedSteps
  65. end
  66. end
  67. print("Closest intersection:")
  68. print("\t"..closestDist)
  69. print("Lowest combined steps:")
  70. print("\t"..lowestCombinedSteps)