Skip to content

Instantly share code, notes, and snippets.

@kittsville
Created February 21, 2024 14:28
Show Gist options
  • Save kittsville/7ab7d0c8fbf40b7053e846ed007b255d to your computer and use it in GitHub Desktop.
Save kittsville/7ab7d0c8fbf40b7053e846ed007b255d to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
// A lil class to make the code neater
case class Coordinate(x: Int, y: Int)
@tailrec
def diagonal(matrix: List[List[Int]], coordinate: Coordinate, previousPath: List[Int] = List.empty)
: List[Int] = {
val path = previousPath :+ matrix(coordinate.y)(coordinate.x)
val nextCoordinates = Coordinate(coordinate.x + 1, coordinate.y + 1)
if (nextCoordinates.y >= matrix.length || nextCoordinates.x >= matrix.head.length) {
path
} else {
diagonal(matrix, nextCoordinates, path)
}
}
val input = List(
List(1, 2, 3),
List(4, 5, 6),
List(7, 8, 9),
)
// Assumes the lists are all equal length, mmmm lack of type safety
val height = input.length
val width = input.head.length
// Each range is all the X and Y coordinates respectively, which become the starting points
val topRowStarting = Range(0, input.head.length).map(x => Coordinate(x, 0)).toSet
val leftColumnStarting = Range(0, input.length).map(y => Coordinate(0, y)).toSet
// Using the Set to de-duplicate the (0, 0) coordinate they both generate
val startingPoints = topRowStarting ++ leftColumnStarting
val diagonals = startingPoints.map(coordinate => diagonal(input, coordinate))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment