marking3/knight2.scala
author Christian Urban <christian.urban@kcl.ac.uk>
Wed, 09 Nov 2022 16:44:16 +0000
changeset 435 fda7c39f3b6a
parent 258 ebe71908b13e
permissions -rw-r--r--
updated wordle testing

// Part 3 about finding a single tour using the Warnsdorf Rule
//=============================================================

//object CW8b { // for preparing the jar

type Pos = (Int, Int)
type Path = List[Pos]


// for measuring time in the JAR
def time_needed[T](code: => T) : T = {
  val start = System.nanoTime()
  val result = code
  val end = System.nanoTime()
  println(f"Time needed: ${(end - start) / 1.0e9}%3.3f secs.")
  result
}


def print_board(dim: Int, path: Path): Unit = {
  println
  for (i <- 0 until dim) {
    for (j <- 0 until dim) {
      print(f"${path.reverse.indexOf((i, j))}%4.0f ")
    }
    println
  } 
}

def add_pair(x: Pos, y: Pos): Pos = 
  (x._1 + y._1, x._2 + y._2)

def is_legal(dim: Int, path: Path, x: Pos): Boolean = 
  0 <= x._1 && 0 <= x._2 && x._1 < dim && x._2 < dim && !path.contains(x)

def moves(x: Pos): List[Pos] = 
  List(( 1,  2),( 2,  1),( 2, -1),( 1, -2),
       (-1, -2),(-2, -1),(-2,  1),(-1,  2)).map(add_pair(x, _))

def legal_moves(dim: Int, path: Path, x: Pos): List[Pos] = 
  moves(x).filter(is_legal(dim, path, _))
 
def ordered_moves(dim: Int, path: Path, x: Pos): List[Pos] = 
  legal_moves(dim, path, x).sortBy((x) => legal_moves(dim, path, x).length)

import scala.annotation.tailrec

@tailrec
def first(xs: List[Pos], f: Pos => Option[Path]): Option[Path] = xs match {
  case Nil => None
  case x::xs => {
    val result = f(x)
    if (result.isDefined) result else first(xs, f)
  }
}


def tfirst_closed_tour_heuristics(dim: Int, path: Path): Option[Path] = {
  if (path.length == dim * dim && moves(path.head).contains(path.last)) Some(path)
  else
    first(ordered_moves(dim, path, path.head), (x: Pos) => tfirst_closed_tour_heuristics(dim, x::path))
}

def first_closed_tour_heuristics(dim: Int, path: Path) =
 time_needed(tfirst_closed_tour_heuristics(dim: Int, path: Path))

def first_closed_tour_heuristic(dim: Int, path: Path) =
 time_needed(tfirst_closed_tour_heuristics(dim: Int, path: Path))


// heuristic cannot be used to search for closed tours on 7 x 7 an beyond
//for (dim <- 1 to 6) {
//  val t = time_needed(0, first_closed_tour_heuristics(dim, List((dim / 2, dim / 2))))
//  println(s"${dim} x ${dim} closed: " + (if (t == None) "" else { print_board(dim, t.get) ; "" }))
//}


def tfirst_tour_heuristics(dim: Int, path: Path): Option[Path] = {
  if (path.length == dim * dim) Some(path)
  else
    first(ordered_moves(dim, path, path.head), (x: Pos) => tfirst_tour_heuristics(dim, x::path))
}


def first_tour_heuristics(dim: Int, path: Path) = 
  time_needed(tfirst_tour_heuristics(dim: Int, path: Path))

def first_tour_heuristic(dim: Int, path: Path) = 
  time_needed(tfirst_tour_heuristics(dim: Int, path: Path))

// will be called with boards up to 30 x 30


//}