Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

homework_4 - Горбунов Матвей #148

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
28 changes: 28 additions & 0 deletions homeworks/homework_4/src/main/scala/Cell.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
trait Cell

class EmptyCell extends Cell {
override def toString: String = "empty"
}

class NumberCell(number: Int) extends Cell {
override def toString: String = number.toString
}

class StringCell(value: String) extends Cell{
override def toString: String = value
}

class ReferenceCell(ix:Int, iy:Int, table: Table) extends Cell {
private def getCell = table.getCell(ix, iy)
private val visited : Set[Cell] = Set(this)
private def getValue(cell: Option[Cell], visited: Set[Cell]): String = cell match {
case None => "outOfRange"
case Some(cell) => cell match {
case c: ReferenceCell if visited.contains(c) => "cyclic"
case c: ReferenceCell => c.getValue(c.getCell, visited + c)
case _ => cell.toString
}
}

override def toString: String = getValue(getCell, visited)
}
21 changes: 21 additions & 0 deletions homeworks/homework_4/src/main/scala/Table.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import scala.collection.mutable

class Table(x: Int, y:Int) {
private val inner = mutable.Map[Int, Cell]().withDefault(_ => new EmptyCell)

def getCell(ix: Int, iy: Int): Option[Cell] = {
val index = ix + iy * x
if (isInBorders(ix, iy))
Option(inner(index))
else None
}

def setCell(ix: Int, iy: Int, cell: Cell): Unit = {
val index = ix + iy * x
inner(index) = cell
}

private def isInBorders(ix:Int, iy:Int) : Boolean = {
ix >= 0 && ix < x && iy >= 0 && iy < y
}
}
2 changes: 1 addition & 1 deletion homeworks/homework_4/src/test/scala/Test.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down