Last active
November 17, 2024 18:09
-
-
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/9e067961ee5163c9e48e11f643920a2e2265f6c8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.5.2" | |
//> using dep "org.scalatest::scalatest:3.2.19" | |
//> 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