Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/8c098df9c11ca8fd89c284d5b092845b to your computer and use it in GitHub Desktop.
Save dacr/8c098df9c11ca8fd89c284d5b092845b to your computer and use it in GitHub Desktop.
encode (x,y) coordinates in a single int / published by https://github.com/dacr/code-examples-manager #5b9dcda7-194a-4d1d-8711-355c59a4f8da/a6b6e048e5b68cdb874db91a345249be16dae8fe
// summary : encode (x,y) coordinates in a single int
// keywords : scala, coordinates, conversions, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 5b9dcda7-194a-4d1d-8711-355c59a4f8da
// created-on : 2020-05-27T12:29:46Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.3.0"
//> using dep "org.scalatest::scalatest:3.2.16"
//> using objectWrapper
// ---------------------
import org.scalatest._, flatspec._, matchers._
trait Encoding {
type Coord = (Int, Int)
type Position = Int
val width: Int
val height: Int
final def coord(x: Int, y: Int): Coord = (x, y)
final def coord2pos(x: Int, y: Int): Position = y * width + x
final def coord2pos(coord: Coord): Position = coord match {
case (x, y) => y * width + x
}
final def pos2coord(pos: Position): Coord = (pos % width, pos / width)
}
class TranscodingTest extends AnyFlatSpec with should.Matchers {
override def suiteName: String = "TranscodingTest"
val simple = new Encoding {
override val width = 100
override val height = 10
}
import simple._
"Encoding" should "encode x,y coordinate into single int value" in {
coord2pos(0, 0) shouldBe 0
coord2pos(9, 0) shouldBe 9
coord2pos(0, 1) shouldBe 100
coord2pos(width - 1, height - 1) shouldBe width * height - 1
}
it should "decode int encoded position into (x,y) coordinates" in {
pos2coord(100) shouldBe(0, 1)
pos2coord(width * height - 1) shouldBe(width - 1, height - 1)
}
}
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[TranscodingTest].getName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment