From 0a0c30a60ae888faeea352c9844d86093594c06f Mon Sep 17 00:00:00 2001 From: Volkov Denis Date: Tue, 21 Apr 2020 18:34:27 +0500 Subject: [PATCH] solve homework 4 --- .../homework_4/src/main/scala/Cell.scala | 26 +++++++++++++++++++ .../homework_4/src/main/scala/Table.scala | 19 ++++++++++++++ .../homework_4/src/test/scala/Test.scala | 2 +- 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/homeworks/homework_4/src/main/scala/Cell.scala b/homeworks/homework_4/src/main/scala/Cell.scala index e69de29..9bb7279 100644 --- a/homeworks/homework_4/src/main/scala/Cell.scala +++ b/homeworks/homework_4/src/main/scala/Cell.scala @@ -0,0 +1,26 @@ +trait Cell + +case class EmptyCell() extends Cell { + override def toString: String = "empty" +} + +case class NumberCell(number: Int) extends Cell +{ + override def toString: String = number.toString +} + +case class StringCell(text: String) extends Cell +{ + override def toString: String = text +} + +case class ReferenceCell(x: Int, y: Int, table: Table) extends Cell { + override def toString: String = { + table.getCell(x, y) match { + case Some(ref: ReferenceCell) => + if (ref.table.getCell(ref.x, ref.y).get == this) "cyclic" else ref.toString + case other => table.getCell(x, y).get.toString + } + } +} + diff --git a/homeworks/homework_4/src/main/scala/Table.scala b/homeworks/homework_4/src/main/scala/Table.scala index e69de29..caec246 100644 --- a/homeworks/homework_4/src/main/scala/Table.scala +++ b/homeworks/homework_4/src/main/scala/Table.scala @@ -0,0 +1,19 @@ +import scala.collection.mutable + +class Table(var width: Int, var height: Int) { + private val table = mutable.HashMap[(Int, Int), Cell]() + + def getCell(x: Int, y: Int): Option[Cell] = { + if(inRange(x, y)) + table get((x, y)) orElse Some(new EmptyCell) + else + Option.empty[Cell] + } + + def setCell(x: Int, y: Int, cell: Cell): Unit = { + table((x, y)) = cell + } + + def inRange(x: Int, y: Int): Boolean = + x >= 0 && y >= 0 && x <= width && y <= height +} \ No newline at end of file diff --git a/homeworks/homework_4/src/test/scala/Test.scala b/homeworks/homework_4/src/test/scala/Test.scala index 08a0ff6..1335775 100644 --- a/homeworks/homework_4/src/test/scala/Test.scala +++ b/homeworks/homework_4/src/test/scala/Test.scala @@ -5,7 +5,7 @@ object Test extends TestSuite { 'test_createTable - { val table = new Table(3, 3) for (i <- 0 until 9) { - assert(table.getCell(i / 3, i % 3).toString == Some("empty")) + assert(table.getCell(i / 3, i % 3).map(_.toString) == Some("empty")) } assert(table.getCell(0, -1).map(_.toString) == None) assert(table.getCell(-1, 0).map(_.toString) == None)