Sunday, August 19, 2012

Seven Languages in Seven Weeks - Scala Day 1 Self Study

It's time for the next programming language in Seven Languages in Seven Weeks: Scala!
The self-study assignment consists in writing a program that will take a tic-tac-toe board and determine which player won (if any):
import scala.io.Source;

object TicTacToe extends App {

  val wins = List(
    List(0, 1, 2), List(3, 4, 5), List(6, 7, 8),
    List(0, 3, 6), List(1, 4, 7), List(2, 5, 8),
    List(0, 4, 8), List(2, 4, 6)
  )
  val input = Source.fromFile("tictactoe.txt").mkString
  val board = (for (chars <- "X|O".r findAllIn input) yield chars).toList

  if (isWin("X")) {
    if (isWin("O")) {
      println("Tie")
    } else {
      println("Player X wins")
    }
  } else {
 if (isWin("O")) {
      println("Player O wins")
 } else {
   println("No winner")
 }
  }

  def isWin (char: String): Boolean = {
    for (win <- wins) {
      var result = true
      for (x <- win) {
        result &= board(x) == char
      }
      if (result)
        return true
    }
 return false
  }
}

1 comment:

  1. Here's a more elegant way to implement the isWin method (thanks Robin :-)):

    def isWin (char: String): Boolean = {
     wins.exists { win =>
      win.forall{ i => board(i) == char }
     }
    }

    ReplyDelete