From c69a2e96c7d3075fdb6124831ac6aae25a80b21a Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 13 Jul 2024 14:51:07 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2751.=20Robot=20Collisions?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/robot-collisions.go | 71 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 go/robot-collisions.go diff --git a/go/robot-collisions.go b/go/robot-collisions.go new file mode 100644 index 0000000..7989223 --- /dev/null +++ b/go/robot-collisions.go @@ -0,0 +1,71 @@ +package main + +import ( + "cmp" + "slices" +) + +type Robot struct { + index int + position int + health int + direction byte +} + +func survivedRobotsHealths(positions []int, healths []int, directions string) []int { + // construct a slice of robots instead of separate slices + robots := make([]Robot, len(positions)) + for i := range len(positions) { + robots[i] = Robot{ + index: i, + position: positions[i], + health: healths[i], + direction: directions[i], + } + } + + // sort by positions + slices.SortFunc(robots, func(a, b Robot) int { + return cmp.Compare(a.position, b.position) + }) + + var stack []*Robot + for i := range robots { + robot := &robots[i] + if robot.direction == 'R' { + stack = append(stack, robot) + continue + } + + for len(stack) > 0 && robot.health > 0 { + otherRobot := stack[len(stack)-1] + stack = stack[:len(stack)-1] + + if otherRobot.health > robot.health { + otherRobot.health-- + robot.health = 0 + stack = append(stack, otherRobot) + } else if otherRobot.health < robot.health { + robot.health-- + otherRobot.health = 0 + } else { + robot.health = 0 + otherRobot.health = 0 + } + } + } + + // revert to the original ordering to preserve the order of the robots + // for the output + slices.SortFunc(robots, func(a, b Robot) int { + return cmp.Compare(a.index, b.index) + }) + + var hp []int + for _, robot := range robots { + if robot.health > 0 { + hp = append(hp, robot.health) + } + } + return hp +}