import scala.collection.mutable

class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {

  if (ordering eq null) throw new NullPointerException("ordering must not be null")

  private var _root: AVLNode = _
  private var _size = 0

  override def size: Int = _size

  override def foreach[U](f: A => U): Unit = {
    val stack = mutable.Stack[AVLNode]()
    var current = root
    var done = false

    while (!done) {
      if (current != null) {
        stack.push(current)
        current = current.left
      } else if (stack.nonEmpty) {
        current = stack.pop()
        f.apply(current.key)

        current = current.right
      } else {
        done = true
      }
    }
  }

  def root: AVLNode = _root

  override def isEmpty: Boolean = root == null

  override def min[B >: A](implicit cmp: Ordering[B]): A = minNode().key

  def minNode(): AVLNode = {
    if (root == null) throw new UnsupportedOperationException("empty tree")
    var node = root
    while (node.left != null) node = node.left
    node
  }

  override def max[B >: A](implicit cmp: Ordering[B]): A = maxNode().key

  def maxNode(): AVLNode = {
    if (root == null) throw new UnsupportedOperationException("empty tree")
    var node = root
    while (node.right != null) node = node.right
    node
  }

  def next(node: AVLNode): Option[AVLNode] = {
    var successor = node
    if (successor != null) {
      if (successor.right != null) {
        successor = successor.right
        while (successor != null && successor.left != null) {
          successor = successor.left
        }
      } else {
        successor = node.parent
        var n = node
        while (successor != null && successor.right == n) {
          n = successor
          successor = successor.parent
        }
      }
    }
    Option(successor)
  }

  def prev(node: AVLNode): Option[AVLNode] = {
    var predecessor = node
    if (predecessor != null) {
      if (predecessor.left != null) {
        predecessor = predecessor.left
        while (predecessor != null && predecessor.right != null) {
          predecessor = predecessor.right
        }
      } else {
        predecessor = node.parent
        var n = node
        while (predecessor != null && predecessor.left == n) {
          n = predecessor
          predecessor = predecessor.parent
        }
      }
    }
    Option(predecessor)
  }

  override def rangeImpl(from: Option[A], until: Option[A]): mutable.SortedSet[A] = ???

  override def +=(key: A): AVLTree.this.type = {
    insert(key)
    this
  }

  def insert(key: A): AVLNode = {
    if (root == null) {
      _root = new AVLNode(key)
      _size += 1
      return root
    }

    var node = root
    var parent: AVLNode = null
    var cmp = 0

    while (node != null) {
      parent = node
      cmp = ordering.compare(key, node.key)
      if (cmp == 0) return node // duplicate
      node = node.matchNextChild(cmp)
    }

    val newNode = new AVLNode(key, parent)
    if (cmp <= 0) parent._left = newNode
    else parent._right = newNode

    while (parent != null) {
      cmp = ordering.compare(parent.key, key)
      if (cmp < 0) parent.balanceFactor -= 1
      else parent.balanceFactor += 1

      parent = parent.balanceFactor match {
        case -1 | 1 => parent.parent
        case x if x < -1 =>
          if (parent.right.balanceFactor == 1) rotateRight(parent.right)
          val newRoot = rotateLeft(parent)
          if (parent == root) _root = newRoot
          null
        case x if x > 1 =>
          if (parent.left.balanceFactor == -1) rotateLeft(parent.left)
          val newRoot = rotateRight(parent)
          if (parent == root) _root = newRoot
          null
        case _ => null
      }
    }

    _size += 1
    newNode
  }

  override def -=(key: A): AVLTree.this.type = {
    remove(key)
    this
  }

  override def remove(key: A): Boolean = {
    var node = findNode(key).orNull
    if (node == null) return false

    if (node.left != null) {
      var max = node.left

      while (max.left != null || max.right != null) {
        while (max.right != null) max = max.right

        node._key = max.key
        if (max.left != null) {
          node = max
          max = max.left
        }
      }
      node._key = max.key
      node = max
    }

    if (node.right != null) {
      var min = node.right

      while (min.left != null || min.right != null) {
        while (min.left != null) min = min.left

        node._key = min.key
        if (min.right != null) {
          node = min
          min = min.right
        }
      }
      node._key = min.key
      node = min
    }

    var current = node
    var parent = node.parent
    while (parent != null) {
      parent.balanceFactor += (if (parent.left == current) -1 else 1)

      current = parent.balanceFactor match {
        case x if x < -1 =>
          if (parent.right.balanceFactor == 1) rotateRight(parent.right)
          val newRoot = rotateLeft(parent)
          if (parent == root) _root = newRoot
          newRoot
        case x if x > 1 =>
          if (parent.left.balanceFactor == -1) rotateLeft(parent.left)
          val newRoot = rotateRight(parent)
          if (parent == root) _root = newRoot
          newRoot
        case _ => parent
      }

      parent = current.balanceFactor match {
        case -1 | 1 => null
        case _ => current.parent
      }
    }

    if (node.parent != null) {
      if (node.parent.left == node) {
        node.parent._left = null
      } else {
        node.parent._right = null
      }
    }

    if (node == root) _root = null

    _size -= 1
    true
  }

  def findNode(key: A): Option[AVLNode] = {
    var node = root
    while (node != null) {
      val cmp = ordering.compare(key, node.key)
      if (cmp == 0) return Some(node)
      node = node.matchNextChild(cmp)
    }
    None
  }

  private def rotateLeft(node: AVLNode): AVLNode = {
    val rightNode = node.right
    node._right = rightNode.left
    if (node.right != null) node.right._parent = node

    rightNode._parent = node.parent
    if (rightNode.parent != null) {
      if (rightNode.parent.left == node) {
        rightNode.parent._left = rightNode
      } else {
        rightNode.parent._right = rightNode
      }
    }

    node._parent = rightNode
    rightNode._left = node

    node.balanceFactor += 1
    if (rightNode.balanceFactor < 0) {
      node.balanceFactor -= rightNode.balanceFactor
    }

    rightNode.balanceFactor += 1
    if (node.balanceFactor > 0) {
      rightNode.balanceFactor += node.balanceFactor
    }
    rightNode
  }

  private def rotateRight(node: AVLNode): AVLNode = {
    val leftNode = node.left
    node._left = leftNode.right
    if (node.left != null) node.left._parent = node

    leftNode._parent = node.parent
    if (leftNode.parent != null) {
      if (leftNode.parent.left == node) {
        leftNode.parent._left = leftNode
      } else {
        leftNode.parent._right = leftNode
      }
    }

    node._parent = leftNode
    leftNode._right = node

    node.balanceFactor -= 1
    if (leftNode.balanceFactor > 0) {
      node.balanceFactor -= leftNode.balanceFactor
    }

    leftNode.balanceFactor -= 1
    if (node.balanceFactor < 0) {
      leftNode.balanceFactor += node.balanceFactor
    }
    leftNode
  }

  override def contains(elem: A): Boolean = findNode(elem).isDefined

  override def iterator: Iterator[A] = ???

  override def keysIteratorFrom(start: A): Iterator[A] = ???

  class AVLNode private[AVLTree](k: A, p: AVLNode = null) {

    private[AVLTree] var _key: A = k
    private[AVLTree] var _parent: AVLNode = p
    private[AVLTree] var _left: AVLNode = _
    private[AVLTree] var _right: AVLNode = _
    private[AVLTree] var balanceFactor: Int = 0

    def parent: AVLNode = _parent

    private[AVLTree] def selectNextChild(key: A): AVLNode = matchNextChild(ordering.compare(key, this.key))

    def key: A = _key

    private[AVLTree] def matchNextChild(cmp: Int): AVLNode = cmp match {
      case x if x < 0 => left
      case x if x > 0 => right
      case _ => null
    }

    def left: AVLNode = _left

    def right: AVLNode = _right
  }

}

implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.


import org.scalatest.FunSuite
import math._

case class V2(x: Double, y: Double) {
  val distance = hypot(x, y)
  def /(other: V2) = V2((x+other.x) / 2.0, (y+other.y) / 2.0)
  def -(other: V2) = V2(x-other.x,y-other.y)
  override def equals(other: Any) = other match {
    case p: V2 => abs(x-p.x) <  0.0001 && abs(y-p.y) <  0.0001
    case _ => false
  }
  override def toString = f"($x%.4f, $y%.4f)"
}

case class Circle(center: V2, radius: Double)

class PointTest extends FunSuite {
  println("       p1               p2         r    result")
  Seq(
    (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0, Seq(Circle(V2(1.8631, 1.9742), 2.0), Circle(V2(-0.8632, -0.7521), 2.0))),
    (V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0, Seq(Circle(V2(0.0, 1.0), 1.0))),
    (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0, "coincident points yields infinite circles"),
    (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5, "radius is less then the distance between points"),
    (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0, "radius of zero yields no circles")
  ) foreach { v =>
    print(s"${v._1} ${v._2}  ${v._3}: ")
    circles(v._1, v._2, v._3) match {
      case Right(list) => println(list mkString ",")
        assert(list === v._4)
      case Left(error) => println(error)
        assert(error === v._4)
    }
  }

  def circles(p1: V2, p2: V2, radius: Double) = if (radius == 0.0) {
      Left("radius of zero yields no circles")
    } else if (p1 == p2) {
      Left("coincident points yields infinite circles")
    } else if (radius * 2 < (p1-p2).distance) {
      Left("radius is less then the distance between points")
    } else {
      Right(circlesThruPoints(p1, p2, radius))
    } ensuring { result =>
      result.isLeft || result.right.get.nonEmpty
    }

  def circlesThruPoints(p1: V2, p2: V2, radius: Double): Seq[Circle] = {
    val diff = p2 - p1
    val d = pow(pow(radius, 2) - pow(diff.distance / 2, 2), 0.5)
    val mid = p1 / p2
    Seq(
      Circle(V2(mid.x - d * diff.y / diff.distance, mid.y + d * diff.x / diff.distance), abs(radius)),
      Circle(V2(mid.x + d * diff.y / diff.distance, mid.y - d * diff.x / diff.distance), abs(radius))).distinct
  }
}

"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned."


scala> import util.control.Breaks.{breakable, break}
import util.control.Breaks.{breakable, break}

scala> import util.Random
import util.Random

scala> breakable {
     |   while(true) {
     |     val a = Random.nextInt(20)
     |     println(a)
     |     if(a == 10)
     |       break
     |     val b = Random.nextInt(20)
     |     println(b)
     |   }
     | }
5
4
10

generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.


Library: Scala
Full-blown version[edit]
/** Find factors of a Mersenne number
 *
 * The implementation finds factors for M929 and further.
 *
 * @example M59 = 2^059 - 1 =             576460752303423487  (   2 msec)
 * @example = 179951 × 3203431780337.
 */
object FactorsOfAMersenneNumber extends App {

  val two: BigInt = 2
  // An infinite stream of primes, lazy evaluation and memo-ized
  val oddPrimes = sieve(LazyList.from(3, 2))

  def sieve(nums: LazyList[Int]): LazyList[Int] =
    LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))

  def primes: LazyList[Int] = sieve(2 #:: oddPrimes)

  def factorMersenne(p: Int): Option[Long] = {
    val limit = (mersenne(p) - 1 min Int.MaxValue).toLong

    def factorTest(p: Long, q: Long): Boolean = {
      (List(1, 7) contains (q % 8)) && two.modPow(p, q) == 1 && BigInt(q).isProbablePrime(7)
    }

    // Build a stream of factors from (2*p+1) step-by (2*p)
    def s(a: Long): LazyList[Long] = a #:: s(a + (2 * p)) // Build stream of possible factors

    // Limit and Filter Stream and then take the head element
    val e = s(2 * p + 1).takeWhile(_ < limit).filter(factorTest(p, _))
    e.headOption
  }

  def mersenne(p: Int): BigInt = (two pow p) - 1

  // Test
  (primes takeWhile (_ <= 97)) ++ List(929, 937) foreach { p => { // Needs some intermediate results for nice formatting
    val nMersenne = mersenne(p);
    val lit = s"${nMersenne}"
    val preAmble = f"${s"M${p}"}%4s = 2^$p%03d - 1 = ${lit}%s"

    val datum = System.nanoTime
    val result = factorMersenne(p)
    val mSec = ((System.nanoTime - datum) / 1.0e+6).round

    def decStr = {
      if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else ""
    }

    def sPrime: String = {
      if (result.isEmpty) " is a Mersenne prime number." else " " * 28
    }

    println(f"$preAmble${sPrime} ${f"($mSec%,1d"}%13s msec)")
    if (result.isDefined)
      println(f"${decStr}%-17s = ${result.get} × ${nMersenne / result.get}")
  }
  }
}

implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.


scala> val xml: scala.xml.Elem =
     | <inventory title="OmniCorp Store #45x10^3">
     |

     |     <item upc="123456789" stock="12">
     |       <name>Invisibility Cream</name>
     |       <price>14.50</price>
     |       <description>Makes you invisible</description>
     |     </item>
     |     <item upc="445322344" stock="18">
     |       <name>Levitation Salve</name>
     |       <price>23.99</price>
     |       <description>Levitate yourself for up to 3 hours per application</description>
     |     </item>
     |

     |

     |     <item upc="485672034" stock="653">
     |       <name>Blork and Freen Instameal</name>
     |       <price>4.95</price>
     |       <description>A tasty meal in a tablet; just add water</description>
     |     </item>
     |     <item upc="132957764" stock="44">
     |       <name>Grob winglets</name>
     |       <price>3.56</price>
     |       <description>Tender winglets of Grob. Just add water</description>
     |     </item>
     |

     | </inventory>

scala> val firstItem = xml \\ "item" take 1
firstItem: scala.xml.NodeSeq =
NodeSeq(<item upc="123456789" stock="12">
      <name>Invisibility Cream</name>
      <price>14.50</price>
      <description>Makes you invisible</description>
    </item>)

scala> xml \\ "price" map (_.text) foreach println
14.50
23.99
4.95
3.56

scala> val names = (xml \\ "name").toArray
names: Array[scala.xml.Node] = Array(<name>Invisibility Cream</name>, <name>Levitation Salve</name>, <name>Blork and Freen Instameal</name>, <name>Grob winglets</name>)

The code performs three XPath queries on a given XML document. It retrieves the first "item" element, prints out each "price" element, and generates an array of all the "name" elements. The XML document represents an inventory of an OmniCorp Store. The code is designed to be run in Scala's REPL for better result visualization.


object sets {
  val set1 = Set(1,2,3,4,5)
  val set2 = Set(3,5,7,9)
  println(set1 contains 3)
  println(set1 | set2)
  println(set1 & set2)
  println(set1 diff set2)
  println(set1 subsetOf set2)
  println(set1 == set2)
}

demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.


Library: Scala
JDK (discouraged)[edit]
import java.util.{ Calendar, GregorianCalendar }
import Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY }

object DayOfTheWeek extends App {
  val years = 2008 to 2121

  val yuletide =
    years.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY)

  // If you want a test: (optional)
  assert(yuletide ==
    Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,
      2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))

  println(yuletide.mkString(
    s"${yuletide.length} Years between ${years.head} and ${years.last}" +
      " including where Christmas is observed on Sunday:\n", ", ", "."))
}
JDK >= 8 (recommended)[edit]
Naive programming[edit]
import java.time.{ DayOfWeek, LocalDate }

object DayOfTheWeek1 extends App {
  val years = 2008 to 2121
  val yuletide = for {
    year <- years
    if LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY
  } yield year

  println(yuletide.mkString(
    s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" +
      " including where Christmas is observed on Sunday:\n", ", ", "."))
}
Idiomatic programming[edit]
import java.time.{ DayOfWeek, LocalDate }

object DayOfTheWeek1 extends App {
  val years = 2008 to 2121
  val yuletide =
    years.filter(year => (LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY))

  // If you want a test: (optional)
  assert(yuletide ==
    Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,
      2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))

  println(yuletide.mkString(
    s"${yuletide.length} Years between ${years.head} and ${years.last}" +
      " including where Christmas is observed on Sunday:\n", ", ", "."))
}
Tail recursion[edit]
import java.time.{ DayOfWeek, LocalDate }
import scala.annotation.tailrec

object DayOfTheWeek3 extends App {
  val years = 2008 to 2121
  val yuletide = {
    @tailrec
    def inner(anni: List[Int], accu: List[Int]): List[Int] = {
      if (anni == Nil) accu
      else inner(anni.tail, accu ++
        (if (LocalDate.of(anni.head, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) List(anni.head)
        else Nil))
    }
    inner(years.toList, Nil)
  }

  // If you want a test: (optional)
  assert(yuletide ==
    Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,
      2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))

  println(yuletide.mkString(
    s"${yuletide.length} Years between ${years.head} and ${years.last}" +
      " including where Christmas is observed on Sunday:\n", ", ", "."))
}

Output of all solutions:
Years between 2008 and 2121 including when Christmas is observed on Sunday:
2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118.

The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date/time representation, such as overflow issues similar to y2k problems.


The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.


val list = List(1,2,3,4,2,3,4,99)
val l2 = list.distinct
// l2: scala.List[scala.Int] = List(1,2,3,4,99)

val arr = Array(1,2,3,4,2,3,4,99)
val arr2 = arr.distinct
// arr2: Array[Int] = Array(1, 2, 3, 4, 99)

implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.


  def sort(xs: List[Int]): List[Int] = xs match {
    case Nil => Nil
    case head :: tail =>
      val (less, notLess) = tail.partition(_ < head) // Arbitrarily partition list in two
      sort(less) ++ (head :: sort(notLess))          // Sort each half
  }

  def sort[T](xs: List[T], lessThan: (T, T) => Boolean): List[T] = xs match {
    case Nil => Nil
    case x :: xx =>
      val (lo, hi) = xx.partition(lessThan(_, x))
      sort(lo, lessThan) ++ (x :: sort(hi, lessThan))
  }

  def sort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = xs match {
    case Nil => Nil
    case x :: xx =>
      val (lo, hi) = xx.partition(ord.lt(_, x))
      sort[T](lo) ++ (x :: sort[T](hi))
  }

  def sort[T <: Ordered[T]](xs: List[T]): List[T] = xs match {
    case Nil => Nil
    case x :: xx =>
      val (lo, hi) = xx.partition(_ < x)
      sort(lo) ++ (x :: sort(hi))
  }

  def sort[T, C[T] <: scala.collection.TraversableLike[T, C[T]]]
    (xs: C[T])
    (implicit ord: scala.math.Ordering[T],
      cbf: scala.collection.generic.CanBuildFrom[C[T], T, C[T]]): C[T] = {
    // Some collection types can't pattern match
    if (xs.isEmpty) {
      xs
    } else {
      val (lo, hi) = xs.tail.partition(ord.lt(_, xs.head))
      val b = cbf()
      b.sizeHint(xs.size)
      b ++= sort(lo)
      b += xs.head
      b ++= sort(hi)
      b.result()
    }
  }

The code implements the Quicksort algorithm for sorting an array or list. It provides two versions of the algorithm: a simple one that creates new arrays for partitions, and an optimized one that sorts in place by swapping elements. The pivot element for partitioning can be any element of the array. The algorithm is efficient with a time complexity ranging from O(n log n) to O(n2) depending on the choice of pivot. The code also discusses the comparison of Quicksort with Merge sort, highlighting their differences and use cases.


import java.util.Date

val now=new Date()
println("%tF".format(now))
println("%1$tA, %1$tB %1$td, %1$tY".format(now))

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


import scala.compat.Platform.currentTime

object Powerset extends App {
  def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el)}

  assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4),
    Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4)))
  println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}

def powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet)

def powerset[A](s: Set[A]) = {
  def powerset_rec(acc: List[Set[A]], remaining: List[A]): List[Set[A]] = remaining match {
    case Nil => acc
    case head :: tail => powerset_rec(acc ++ acc.map(_ + head), tail)
  }
  powerset_rec(List(Set.empty[A]), s.toList)
}

The code takes a set S as input and generates its power set, which includes all possible subsets of S. It also handles edge cases like an empty set and a set containing only the empty set. The code supports lazy sequence generation and tail-recursion.


Works with: Scala version 2.8
val romanDigits = Map(
  1 -> "I", 5 -> "V",
  10 -> "X", 50 -> "L",
  100 -> "C", 500 -> "D",
  1000 -> "M",
  4 -> "IV", 9 -> "IX",
  40 -> "XL", 90 -> "XC",
  400 -> "CD", 900 -> "CM")
val romanDigitsKeys = romanDigits.keysIterator.toList sortBy (x => -x)
def toRoman(n: Int): String = romanDigitsKeys find (_ >= n) match {
  case Some(key) => romanDigits(key) + toRoman(n - key)
  case None => ""
}

create a function that converts a positive integer into its equivalent Roman numeral representation.


// Create a new integer array with capacity 10
val a = new Array[Int](10)

// Create a new array containing specified items
val b = Array("foo", "bar", "baz")

// Assign a value to element zero
a(0) = 42

// Retrieve item at element 2
val c = b(2)

val a = new collection.mutable.ArrayBuffer[Int]
a += 5   // Append value 5 to the end of the list
a(0) = 6 // Assign value 6 to element 0

demonstrate the basic syntax of arrays in a specific programming language. It includes creating an array, assigning a value to it, and retrieving an element from it. It covers both fixed-length and dynamic arrays, and also shows how to push a value into the array. The code also discusses the use of ArrayBuffers for creating dynamic arrays in Scala, as an alternative to the less commonly used mutable arrays.


Library: Scala
import java.io.{ FileNotFoundException, PrintWriter }

object FileIO extends App {
  try {
    val MyFileTxtTarget = new PrintWriter("output.txt")

    scala.io.Source.fromFile("input.txt").getLines().foreach(MyFileTxtTarget.println)
    MyFileTxtTarget.close()
  } catch {
    case e: FileNotFoundException => println(e.getLocalizedMessage())
    case e: Throwable => {
      println("Some other exception type:")
      e.printStackTrace()
    }
  }
}

demonstrate reading the contents of "input.txt" file into a variable and then writing this variable's contents into a new file called "output.txt".


val s="alphaBETA"
println(s.toUpperCase)   //-> ALPHABETA
println(s.toLowerCase)   //-> alphabeta
println(s.capitalize)    //-> AlphaBETA
println(s.reverse)       //-> ATEBahpla

demonstrate the conversion of the string "alphaBETA" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.


import scala.collection.mutable.ListBuffer
import scala.util.Random

object ClosestPair {
  case class Point(x: Double, y: Double){
    def distance(p: Point) = math.hypot(x-p.x, y-p.y)

    override def toString = "(" + x + ", " + y + ")"
  }

  case class Pair(point1: Point, point2: Point) {
    val distance: Double = point1 distance point2

    override def toString = {
      point1 + "-" + point2 + " : " + distance
    }
  }

  def sortByX(points: List[Point]) = {
    points.sortBy(point => point.x)
  }

  def sortByY(points: List[Point]) = {
    points.sortBy(point => point.y)
  }

  def divideAndConquer(points: List[Point]): Pair = {
    val pointsSortedByX = sortByX(points)
    val pointsSortedByY = sortByY(points)

    divideAndConquer(pointsSortedByX, pointsSortedByY)
  }

  def bruteForce(points: List[Point]): Pair = {
    val numPoints = points.size
    if (numPoints < 2)
      return null
    var pair = Pair(points(0), points(1))
    if (numPoints > 2) {
      for (i <- 0 until numPoints - 1) {
        val point1 = points(i)
        for (j <- i + 1 until numPoints) {
          val point2 = points(j)
          val distance = point1 distance point2
          if (distance < pair.distance)
            pair = Pair(point1, point2)
        }
      }
    }
    return pair
  }

  private def divideAndConquer(pointsSortedByX: List[Point], pointsSortedByY: List[Point]): Pair = {
    val numPoints = pointsSortedByX.size
    if(numPoints <= 3) {
      return bruteForce(pointsSortedByX)
    }

    val dividingIndex = numPoints >>> 1
    val leftOfCenter = pointsSortedByX.slice(0, dividingIndex)
    val rightOfCenter = pointsSortedByX.slice(dividingIndex, numPoints)

    var tempList = leftOfCenter.map(x => x)
    //println(tempList)
    tempList = sortByY(tempList)
    var closestPair = divideAndConquer(leftOfCenter, tempList)

    tempList = rightOfCenter.map(x => x)
    tempList = sortByY(tempList)

    val closestPairRight = divideAndConquer(rightOfCenter, tempList)

    if (closestPairRight.distance < closestPair.distance)
      closestPair = closestPairRight

    tempList = List[Point]()
    val shortestDistance = closestPair.distance
    val centerX = rightOfCenter(0).x

    for (point <- pointsSortedByY) {
      if (Math.abs(centerX - point.x) < shortestDistance)
        tempList = tempList :+ point
    }

    closestPair = shortestDistanceF(tempList, shortestDistance, closestPair)
    closestPair
  }

  private def shortestDistanceF(tempList: List[Point], shortestDistance: Double, closestPair: Pair ): Pair = {
    var shortest = shortestDistance
    var bestResult = closestPair
    for (i <- 0 until tempList.size) {
      val point1 = tempList(i)
      for (j <- i + 1 until tempList.size) {
        val point2 = tempList(j)
        if ((point2.y - point1.y) >= shortestDistance)
          return closestPair
        val distance = point1 distance point2
        if (distance < closestPair.distance)
        {
          bestResult = Pair(point1, point2)
          shortest = distance
        }
      }
    }

    closestPair
  }

  def main(args: Array[String]) {
    val numPoints = if(args.length == 0) 1000 else args(0).toInt

    val points = ListBuffer[Point]()
    val r = new Random()
    for (i <- 0 until numPoints) {
      points.+=:(new Point(r.nextDouble(), r.nextDouble()))
    }
    println("Generated " + numPoints + " random points")

    var startTime = System.currentTimeMillis()
    val bruteForceClosestPair = bruteForce(points.toList)
    var elapsedTime = System.currentTimeMillis() - startTime
    println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair)

    startTime = System.currentTimeMillis()
    val dqClosestPair = divideAndConquer(points.toList)
    elapsedTime = System.currentTimeMillis() - startTime
    println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair)
    if (bruteForceClosestPair.distance != dqClosestPair.distance)
      println("MISMATCH")
  }
}

provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.


Library: ScalaScala has in his run-time library a rich set set of collections. Due to use of traits is this library easily realized and consistent. Collections provide the same operations on any type where it makes sense to do so. For instance, a string is conceptually a sequence of characters. Consequently, in Scala collections, strings support all sequence operations. The same holds for arrays.

These examples were taken from a Scala REPL session. The second lines are the REPL responces.Windows PowerShell
Copyright (C) 2012 Microsoft Corporation. All rights reserved.

PS C:\Users\FransAdm> scala
Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> // Immutable collections do not and cannot change the instantiated object

scala> // Lets start with Lists

scala> val list = Nil // Empty List
list: scala.collection.immutable.Nil.type = List()

scala> val list2 = List("one", "two") // List with two elements (Strings)
list2: List[String] = List(one, two)

scala> val list3 = 3 :: list2 // prepend 3 to list2, using a special operator
list3: List[Any] = List(3, one, two)

scala> // The result was a mixture with a Int and Strings, so the common superclass Any is used.

scala> // Let test the Set collection

scala> val set = Set.empty[Char] // Empty Set of Char type
set: scala.collection.immutable.Set[Char] = Set()

scala> val set1 = set + 'c' // add an element
set1: scala.collection.immutable.Set[Char] = Set(c)

scala> val set2 = set + 'a' + 'c' + 'c' // try to add another and  the same element twice
set2: scala.collection.immutable.Set[Char] = Set(a, c)

scala> // Let's look at the most universal map: TrieMap (Cache-aware lock-free concurrent hash trie)

scala> val capital = collection.concurrent.TrieMap("US" -> "Washington", "France" -> "Paris") // This map is mutable
capital: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, France -> Paris)

scala> capital - "France" // This is only an expression, does not modify the map itself
res0: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington)

scala> capital += ("Tokio" -> "Japan") // Adding an element, object is changed - not the val capital
res1: capital.type = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)

scala> capital // Check what we have sofar
res2: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)

scala>  val queue = new scala.collection.mutable.Queue[String]
queue: scala.collection.mutable.Queue[String] = Queue()

scala> queue += "first"
res17: queue.type = Queue("first")

scala> queue += "second"
res19: queue.type = Queue("first", "second")

scala>
    import collection.concurrent.TrieMap

    // super concurrent mutable hashmap
    val map = TrieMap("Amsterdam" -> "Netherlands",
      "New York" -> "USA",
      "Heemstede" -> "Netherlands")

    map("Laussanne") = "Switzerland" // 2 Ways of updating
    map += ("Tokio" -> "Japan")

    assert(map("New York") == "USA")
    assert(!map.isDefinedAt("Gent")) // isDefinedAt is false
    assert(map.isDefinedAt("Laussanne")) // true

    val hash = new TrieMap[Int, Int]
    hash(1) = 2
    hash += (1 -> 2) // same as hash(1) = 2
    hash += (3 -> 4, 5 -> 6, 44 -> 99)
    hash(44) // 99
    hash.contains(33) // false
    hash.isDefinedAt(33) // same as contains
    hash.contains(44) // true
    // iterate over key/value
    //    hash.foreach { case (key, val) => println(  "key " + e._1 + " value " + e._2) } // e is a 2 element Tuple
    // same with for syntax
    for ((k, v) <- hash) println("key " + k + " value " + v)
    //    // items in map where the key is greater than 3
        map.filter { k => k._1 > 3 } //  Map(5 -> 6, 44 -> 99)
    //    // same with for syntax
        for ((k, v) <- map; if k > 3) yield (k, v)

create a collection in a statically-typed language, add a few values to it, and demonstrate the difference between immutable and mutable collections. It also shows how to switch between sequential and parallel processing using .seq or .par postfix.


Functional approach (Tail recursive)[edit]
import scala.annotation.tailrec

object UnboundedKnapsack extends App {
  private val (maxWeight, maxVolume) = (BigDecimal(25.0), BigDecimal(0.25))
  private val items = Seq(Item("panacea", 3000, 0.3, 0.025), Item("ichor", 1800, 0.2, 0.015), Item("gold", 2500, 2.0, 0.002))

  @tailrec
  private def packer(notPacked: Seq[Knapsack], packed: Seq[Knapsack]): Seq[Knapsack] = {
    def fill(knapsack: Knapsack): Seq[Knapsack] = items.map(i => Knapsack(i +: knapsack.bagged))

    def stuffer(Seq: Seq[Knapsack]): Seq[Knapsack] = // Cause brute force
      Seq.map(k => Knapsack(k.bagged.sortBy(_.name))).distinct

    if (notPacked.isEmpty) packed.sortBy(-_.totValue).take(4)
    else packer(stuffer(notPacked.flatMap(fill)).filter(_.isNotFull), notPacked ++ packed)
  }

  private case class Item(name: String, value: Int, weight: BigDecimal, volume: BigDecimal)

  private case class Knapsack(bagged: Seq[Item]) {
    def isNotFull: Boolean = totWeight <= maxWeight && totVolume <= maxVolume

    override def toString = s"[${show(bagged)} | value: $totValue, weight: $totWeight, volume: $totVolume]"

    def totValue: Int = bagged.map(_.value).sum

    private def totVolume = bagged.map(_.volume).sum

    private def totWeight = bagged.map(_.weight).sum

    private def show(is: Seq[Item]) =
      (items.map(_.name) zip items.map(i => is.count(_ == i)))
        .map { case (i, c) => f"$i:$c%3d" }
        .mkString(", ")
  }

  packer(items.map(i => Knapsack(Seq(i))), Nil).foreach(println)
}

determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.


Library: Scala
var i = 1
while ({
  print(i)
  i < 10
}) {
  print(", ")
  i += 1
}
println()
println((1 to 10).mkString(", "))

The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.


"abcd".startsWith("ab") //returns true
"abcd".endsWith("zn") //returns false
"abab".contains("bb") //returns false
"abab".contains("ab") //returns true

var loc="abab".indexOf("bb") //returns -1
loc = "abab".indexOf("ab") //returns 0
loc = "abab".indexOf("ab", loc+1) //returns 2

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


Translation of: Java
object FourRings {

  def fourSquare(low: Int, high: Int, unique: Boolean, print: Boolean): Unit = {
    def isValid(needle: Integer, haystack: Integer*) = !unique || !haystack.contains(needle)

    if (print) println("a b c d e f g")

    var count = 0
    for {
      a <- low to high
      b <- low to high if isValid(a, b)
      fp = a + b
      c <- low to high if isValid(c, a, b)
      d <- low to high if isValid(d, a, b, c) && fp == b + c + d
      e <- low to high if isValid(e, a, b, c, d)
      f <- low to high if isValid(f, a, b, c, d, e) && fp == d + e + f
      g <- low to high if isValid(g, a, b, c, d, e, f) && fp == f + g
    } {
      count += 1
      if (print) println(s"$a $b $c $d $e $f $g")
    }

    println(s"There are $count ${if(unique) "unique" else "non-unique"} solutions in [$low, $high]")
  }

  def main(args: Array[String]): Unit = {
    fourSquare(1, 7, unique = true, print = true)
    fourSquare(3, 9, unique = true, print = true)
    fourSquare(0, 9, unique = false, print = false)
  }
}

The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.


Circular ASCII clock[edit]

import java.util.{ Timer, TimerTask }
import java.time.LocalTime
import scala.math._

object Clock extends App {
  private val (width, height) = (80, 35)

  def getGrid(localTime: LocalTime): Array[Array[Char]] = {
    val (minute, second) = (localTime.getMinute, localTime.getSecond())
    val grid = Array.fill[Char](height, width)(' ')

    def toGridCoord(x: Double, y: Double): (Int, Int) =
      (floor((y + 1.0) / 2.0 * height).toInt, floor((x + 1.0) / 2.0 * width).toInt)

    def makeText(grid: Array[Array[Char]], r: Double, theta: Double, str: String) {
      val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
      (0 until str.length).foreach(i =>
        if (row >= 0 && row < height && col + i >= 0 && col + i < width) grid(row)(col + i) = str(i))
    }

    def makeCircle(grid: Array[Array[Char]], r: Double, c: Char) {
      var theta = 0.0
      while (theta < 2 * Pi) {
        val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
        if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c
        theta = theta + 0.01
      }
    }

    def makeHand(grid: Array[Array[Char]], maxR: Double, theta: Double, c: Char) {
      var r = 0.0
      while (r < maxR) {
        val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
        if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c
        r = r + 0.01
      }
    }

    makeCircle(grid, 0.98, '@')
    makeHand(grid, 0.6, (localTime.getHour() + minute / 60.0 + second / 3600.0) * Pi / 6 - Pi / 2, 'O')
    makeHand(grid, 0.85, (minute + second / 60.0) * Pi / 30 - Pi / 2, '*')
    makeHand(grid, 0.90, second * Pi / 30 - Pi / 2, '.')

    (1 to 12).foreach(n => makeText(grid, 0.87, n * Pi / 6 - Pi / 2, n.toString))
    grid
  } // def getGrid(

  private val timerTask = new TimerTask {
    private def printGrid(grid: Array[Array[Char]]) = grid.foreach(row => println(row.mkString))
    def run() = printGrid(getGrid(LocalTime.now()))
  }
  (new Timer).schedule(timerTask, 0, 1000)
}

Berliner Uhr[edit]

import java.time.LocalTime
import java.awt.{ Color, Graphics }

/** The Berlin clock as a Java (8.0) applet
 */
class QDclock extends java.applet.Applet with Runnable {
  val bclockThread: Thread = new Thread(this, "QDclock")

  override def init() = resize(242, 180) // fixed size, at first... doesn't work...

  override def start() = if (!bclockThread.isAlive()) bclockThread.start()

  def run() {
    while (true) {
      repaint()
      try Thread.sleep(1000) catch { case _: Throwable => sys.exit(-1) }
    }
  }

  override def update(g: Graphics) {
    val now = LocalTime.now

    def booleanToColor(cond: Boolean, colorOn: Color = Color.red): Color =
      if (cond) colorOn else Color.black

    g.setColor(booleanToColor(now.getSecond() % 2 == 0, Color.yellow))
    g.fillOval(100, 4, 40, 40)

    val (stu, min) = (now.getHour(), now.getMinute()) match {
      case (0, 0)     => (24, 0)
      case (hrs, min) => (hrs, min)
    }

    def drawRectangle(color: Color, rect: (Int, Int, Int, Int)) {
      g.setColor(color)
      g.fillRoundRect(rect._1, rect._2, rect._3, rect._4, 4, 4)
    }

    for (i <- 0 until 4) {
      drawRectangle(booleanToColor(stu / ((i + 1) * 5) > 0), (i * 60 + 2, 46, 58, 30))
      drawRectangle(booleanToColor(stu % 5 > i), (i * 60 + 2, 78, 58, 30))
      drawRectangle(booleanToColor(min % 5 > i, Color.yellow), (i * 60 + 2, 142, 58, 30))
    }

    for (i <- 0 until 11) {
      drawRectangle(booleanToColor(min / ((i + 1) * 5) > 0,
        if (2 to 8 by 3 contains i) Color.red else Color.yellow), (i * 20 + 10, 110, 18, 30))
    }
  }
}

generate a graphical or text-based representation of a timekeeping device that updates every second in sync with the system clock, without excessively using system resources or CPU. The code is kept simple and clear. An ASCII clock is printed every second as an example.


The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.


Library: sdljava
Library: Scala Java Swing interoperability
import javax.swing.JFrame

object ShowWindow{
  def main(args: Array[String]){
    var jf = new JFrame("Hello!")

    jf.setSize(800, 600)
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    jf.setVisible(true)
  }
}

import scala.swing._
import scala.swing.Swing._

object SimpleWindow extends SimpleSwingApplication {
  def top = new MainFrame {
    title = "Hello!"
    preferredSize = ((800, 600):Dimension)
  }
}

create a GUI window using native Scala libraries, which can respond to close requests.


import io.Source.fromFile

def letterFrequencies(filename: String) =
  fromFile(filename).mkString groupBy (c => c) mapValues (_.length)

Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.


sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]

object List {
  def apply[A](as: A*): List[A] =
    if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*))
}

def main(args: Array[String]): Unit = {
  val words = List("Rosetta", "Code", "Scala", "Example")
}

define a data structure for a singly-linked list element, which includes a data member for storing a numeric value and a mutable link to the next element.


import swing._
import java.awt.{RenderingHints, BasicStroke, Color}

object FractalTree extends SimpleSwingApplication {
  val DEPTH = 9

  def top = new MainFrame {
    contents = new Panel {
      preferredSize = new Dimension(600, 500)

      override def paintComponent(g: Graphics2D) {
        draw(300, 460, -90, DEPTH)

        def draw(x1: Int, y1: Int, angle: Double, depth: Int) {
          if (depth > 0) {
            val x2 = x1 + (math.cos(angle.toRadians) * depth * 10).toInt
            val y2 = y1 + (math.sin(angle.toRadians) * depth * 10).toInt

            g.setColor(Color.getHSBColor(0.25f - depth * 0.125f / DEPTH, 0.9f, 0.6f))
            g.setStroke(new BasicStroke(depth))
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
            g.drawLine(x1, y1, x2, y2)

            draw(x2, y2, angle - 20, depth - 1)
            draw(x2, y2, angle + 20, depth - 1)
          }
        }
      }
    }
  }
}

generates and draws a fractal tree by first drawing the trunk, then splitting the end of the trunk by a certain angle to create two branches, and repeating this process until a desired level of branching is achieved. This is adapted from the Java version.


def factors(num: Int) = {
    (1 to num).filter { divisor =>
      num % divisor == 0
    }
}

def factors(num: Int) = {
    val list = (1 to math.sqrt(num).floor.toInt).filter(num % _ == 0)
    list ++ list.reverse.dropWhile(d => d*d == num).map(num / _)
}

calculate the factors of a positive integer using a brute force approach up to the square root of the number. The program does not handle factors of zero or negative integers. It also notes that every prime number has two factors: 1 and itself.


Works with: scala version 2.8.0.r18997-b20091009021954

object ColumnAligner {
  val eol = System.getProperty("line.separator")
  def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)
  def splitter(line: String) = line split '$'
  def getTable(filename: String) = getLines(filename) map splitter
  def fieldWidths(fields: Array[String]) = fields map (_ length)
  def columnWidths(txt: Iterator[Array[String]]) = (txt map fieldWidths).toList.transpose map (_ max)

  def alignField(alignment: Char)(width: Int)(field: String) = alignment match {
    case 'l' | 'L' => "%-"+width+"s" format field
    case 'r' | 'R' => "%"+width+"s" format field
    case 'c' | 'C' => val padding = (width - field.length) / 2; " "*padding+"%-"+(width-padding)+"s" format field
    case _ => throw new IllegalArgumentException
  }

  def align(aligners: List[String => String])(fields: Array[String]) =
    aligners zip fields map Function.tupled(_ apply _)

  def alignFile(filename: String, alignment: Char) = {
    def table = getTable(filename)
    val aligners = columnWidths(table) map alignField(alignment)
    table map align(aligners) map (_ mkString " ")
  }

  def printAlignedFile(filename: String, alignment: Char) {
    alignFile(filename, alignment) foreach println
  }
}

def pad(s:String, i:Int, d:String) = {
  val padsize = (i-s.length).max(0)
  d match {
    case "left" => s+" "*padsize
    case "right" => " "*padsize+s
    case "center" => " "*(padsize/2) + s + " "*(padsize-padsize/2)
  }
}

val lines = scala.io.Source.fromFile("c:\\text.txt").getLines.map(_.trim())
val words = lines.map(_.split("\\$").toList).toList
val lens = words.map(l => l.map(_.length)).toList

var maxlens = Map[Int,Int]() withDefaultValue 0
lens foreach (l =>
  for(i <- (0 until l.length)){
    maxlens += i -> l(i).max(maxlens(i))
  }
)

val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
padded map (_.reduceLeft(_ + _)) foreach println

The code reads a text file where each line's fields are separated by a dollar sign. It aligns each column by ensuring at least one space between words in each column. It also allows for each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters, consecutive spaces at the end of lines, and separating characters between or around columns are not considered. The output is viewed in a mono-spaced font on a plain text editor or basic terminal.


Java Swing Interoperability[edit]
import java.awt._
import java.awt.event.{MouseAdapter, MouseEvent}

import javax.swing._

import scala.math.{Pi, cos, sin}

object Cuboid extends App {
  SwingUtilities.invokeLater(() => {

    class Cuboid extends JPanel {
      private val nodes: Array[Array[Double]] =
        Array(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1), Array(-1, 1, 1),
          Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1))
      private var mouseX, prevMouseX, mouseY, prevMouseY: Int = _

      private def edges =
        Seq(Seq(0, 1), Seq(1, 3), Seq(3, 2), Seq(2, 0),
          Seq(4, 5), Seq(5, 7), Seq(7, 6), Seq(6, 4),
          Seq(0, 4), Seq(1, 5), Seq(2, 6), Seq(3, 7))

      override def paintComponent(gg: Graphics): Unit = {
        val g = gg.asInstanceOf[Graphics2D]

        def drawCube(g: Graphics2D): Unit = {
          g.translate(getWidth / 2, getHeight / 2)
          for (edge <- edges) {
            g.drawLine(nodes(edge.head)(0).round.toInt, nodes(edge.head)(1).round.toInt,
              nodes(edge(1))(0).round.toInt, nodes(edge(1))(1).round.toInt)
          }
          for (node <- nodes) g.fillOval(node(0).round.toInt - 4, node(1).round.toInt - 4, 8, 8)
        }

        super.paintComponent(gg)
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        drawCube(g)
      }

      private def scale(sx: Double, sy: Double, sz: Double): Unit = {
        for (node <- nodes) {
          node(0) *= sx
          node(1) *= sy
          node(2) *= sz
        }
      }

      private def rotateCube(angleX: Double, angleY: Double): Unit = {
        val (sinX, cosX, sinY, cosY) = (sin(angleX), cos(angleX), sin(angleY), cos(angleY))
        for (node <- nodes) {
          val (x, y, z) = (node.head, node(1), node(2))
          node(0) = x * cosX - z * sinX
          node(2) = z * cosX + x * sinX
          node(1) = y * cosY - node(2) * sinY
          node(2) = node(2) * cosY + y * sinY
        }
      }

      addMouseListener(new MouseAdapter() {
        override def mousePressed(e: MouseEvent): Unit = {
          mouseX = e.getX
          mouseY = e.getY
        }
      })

      addMouseMotionListener(new MouseAdapter() {
        override def mouseDragged(e: MouseEvent): Unit = {
          prevMouseX = mouseX
          prevMouseY = mouseY
          mouseX = e.getX
          mouseY = e.getY
          rotateCube((mouseX - prevMouseX) * 0.01, (mouseY - prevMouseY) * 0.01)
          repaint()
        }
      })

      scale(80, 120, 160)
      rotateCube(Pi / 5, Pi / 9)
      setPreferredSize(new Dimension(640, 640))
      setBackground(Color.white)
    }

    new JFrame("Cuboid") {
      add(new Cuboid, BorderLayout.CENTER)
      pack()
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
      setLocationRelativeTo(null)
      setResizable(false)
      setVisible(true)
    }
  })
}

generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.


import java.io.IOException

import org.apache.directory.api.ldap.model.exception.LdapException
import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}

object LdapConnectionDemo {
  @throws[LdapException]
  @throws[IOException]
  def main(args: Array[String]): Unit = {
    try {
      val connection: LdapConnection = new LdapNetworkConnection("localhost", 10389)
      try {
        connection.bind()
        connection.unBind()
      } finally if (connection != null) connection.close()
    }
  }
}

establish a connection to an Active Directory or Lightweight Directory Access Protocol server.


scala> def rot13(s: String) = s map {
     |   case c if 'a' <= c.toLower && c.toLower <= 'm' => c + 13 toChar
     |   case c if 'n' <= c.toLower && c.toLower <= 'z' => c - 13 toChar
     |   case c => c
     | }
rot13: (s: String)String

scala> rot13("7 Cities of Gold.")
res61: String = 7 Pvgvrf bs Tbyq.

scala> rot13(res61)
res62: String = 7 Cities of Gold.

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


case class Pair(name:String, value:Double)
val input = Array(Pair("Krypton", 83.798), Pair("Beryllium", 9.012182), Pair("Silicon", 28.0855))
input.sortBy(_.name) // Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855))

// alternative versions:
input.sortBy(struct => (struct.name, struct.value)) // additional sort field (name first, then value)
input.sortWith((a,b) => a.name.compareTo(b.name) < 0) // arbitrary comparison function

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.


for (i <- 1 to 5) {
    for (j <- 1 to i)
        print("*")
    println()
}

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


// immutable maps
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
map(3) // 4
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
map.isDefinedAt(33) // false
map.isDefinedAt(44) // true
// mutable maps (HashSets)
import scala.collection.mutable.HashMap
val hash = new HashMap[Int, Int]
hash(1) = 2
hash += (1 -> 2)  // same as hash(1) = 2
hash += (3 -> 4, 5 -> 6, 44 -> 99)
hash(44) // 99
hash.contains(33) // false
hash.isDefinedAt(33) // same as contains
hash.contains(44) // true
// iterate over key/value
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple
// same with for syntax
for((k,v) <- hash) println("key " + k + " value " + v)
// items in map where the key is greater than 3
map.filter {k => k._1 > 3} //  Map(5 -> 6, 44 -> 99)
// same with for syntax
for((k, v) <- map; if k > 3) yield (k,v)

"Create an associative array, also known as a dictionary, map, or hash."


object LinearCongruentialGenerator {
  def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
    var seed=rseed
    override def hasNext:Boolean=true
    override def next:Int={seed=(seed * 1103515245 + 12345) & Int.MaxValue; seed}
  }

  def msRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
    var seed=rseed
    override def hasNext:Boolean=true
    override def next:Int={seed=(seed * 214013 + 2531011) & Int.MaxValue; seed >> 16}
  }

  def toString(it:Iterator[Int], n:Int=20)=it take n mkString ", "

  def main(args:Array[String]){
    println("-- seed 0 --")
    println("BSD: "+ toString(bsdRandom(0)))
    println("MS : "+ toString(msRandom(0)))

    println("-- seed 1 --")
    println("BSD: "+ toString(bsdRandom(1)))
    println("MS : "+ toString( msRandom(1)))
  }
}

The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.


/*
Here is a basic list definition

sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
*/

object List {
  def add[A](as: List[A], a: A): List[A] = Cons(a, as)
}

define a method to insert an element 'C' into a singly-linked list after a specified element 'A'. In the context of functional programming like Scala, a new list is created instead of modifying the existing one.


def ethiopian(i:Int, j:Int):Int=
   pairIterator(i,j).filter(x=> !isEven(x._1)).map(x=>x._2).foldLeft(0){(x,y)=>x+y}

def ethiopian2(i:Int, j:Int):Int=
   pairIterator(i,j).map(x=>if(isEven(x._1)) 0 else x._2).foldLeft(0){(x,y)=>x+y}

def ethiopian3(i:Int, j:Int):Int=
{
   var res=0;
   for((h,d) <- pairIterator(i,j) if !isEven(h)) res+=d;
   res
}

def ethiopian4(i: Int, j: Int): Int = if (i == 1) j else ethiopian(halve(i), double(j)) + (if (isEven(i)) 0 else j)

def isEven(x:Int)=(x&1)==0
def halve(x:Int)=x>>>1
def double(x:Int)=x<<1

// generates pairs of values (halve,double)
def pairIterator(x:Int, y:Int)=new Iterator[(Int, Int)]
{
   var i=(x, y)
   def hasNext=i._1>0
   def next={val r=i; i=(halve(i._1), double(i._2)); r}
}

The code defines three functions: one for halving an integer, one for doubling an integer, and one for checking if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two numbers using only addition, doubling, and halving operations. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.


"Code generates arithmetic expressions from four input digits, following the rules of the 24 game, and displays example solutions."


Imperative[edit]

def factorial(n: Int) = {
  var res = 1
  for (i <- 1 to n)
    res *= i
  res
}
Recursive[edit]

def factorial(n: Int): Int =
  if (n < 1) 1
  else       n * factorial(n - 1)

def factorial(n: Int) = {
  @tailrec def fact(x: Int, acc: Int): Int = {
    if (x < 2) acc else fact(x - 1, acc * x)
  }
  fact(n, 1)
}
Stdlib .product[edit]

def factorial(n: Int) = (2 to n).product
Folding[edit]

def factorial(n: Int) =
  (2 to n).foldLeft(1)(_ * _)
Using implicit functions to extend the Int type[edit]

implicit def IntToFac(i : Int) = new {
  def ! = (2 to i).foldLeft(BigInt(1))(_ * _)
}

Example used in the REPL:
scala> 20!
res0: scala.math.BigInt = 2432902008176640000

scala> 100!
res1: scala.math.BigInt = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

implement a function that calculates the factorial of a given number. The function can be either iterative or recursive. It optionally handles negative input errors. The factorial of a number is the product of all positive integers less than or equal to that number, with the factorial of zero defined as one. The code may include various methods such as naive recursion, tail recursion with a helper function, using standard library builtin, using folding, and enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer.


import scala.util.Random

object BullCow {
   def main(args: Array[String]): Unit = {
      val number=chooseNumber
      var guessed=false
      var guesses=0

      while(!guessed){
         Console.print("Guess a 4-digit number with no duplicate digits: ")
         val input=Console.readInt
         val digits=input.toString.map(_.asDigit).toList
         if(input>=1111 && input<=9999 && !hasDups(digits)){
            guesses+=1
            var bulls, cows=0
            for(i <- 0 to 3)
               if(number(i)==digits(i))
                  bulls+=1
               else if(number.contains(digits(i)))
                  cows+=1

            if(bulls==4)
               guessed=true
            else
               println("%d Cows and %d Bulls.".format(cows, bulls))
         }
      }
      println("You won after "+guesses+" guesses!");
   }

   def chooseNumber={
      var digits=List[Int]()
      while(digits.size<4){
         val d=Random.nextInt(9)+1
         if (!digits.contains(d))
            digits=digits:+d
      }
      digits
   }

   def hasDups(input:List[Int])=input.size!=input.distinct.size
}

generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.


One liner[edit]
List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)

Academic[edit]
object RandomNumbers extends App {

  val distribution: LazyList[Double] = {
    def randomNormal: Double = 1.0 + 0.5 * scala.util.Random.nextGaussian

    def normalDistribution(a: Double): LazyList[Double] = a #:: normalDistribution(randomNormal)

    normalDistribution(randomNormal)
  }

  /*
   * Let's test it
   */
  def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
    val mean: T =
      num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T

    // Root of mean diffs
    val stdDev = Math.sqrt(ts.map { x =>
      val diff = num.toDouble(num.minus(x, mean))
      diff * diff
    }.sum / ts.size)

    (mean, stdDev)
  }

  println(calcAvgAndStddev(distribution.take(1000))) // e.g. (1.0061433267806525,0.5291834867560893)
}

generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.


Library: Scalaclass Dot[T](v1: Seq[T])(implicit n: Numeric[T]) {
  import n._ // import * operator
  def dot(v2: Seq[T]) = {
    require(v1.size == v2.size)
    (v1 zip v2).map{ Function.tupled(_ * _)}.sum
  }
}

object Main extends App {
  implicit def toDot[T: Numeric](v1: Seq[T]) = new Dot(v1)

  val v1 = List(1, 3, -5)
  val v2 = List(4, -2, -1)
  println(v1 dot v2)
}

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


Library: Scala
Works with: Scala version 2.10.3
  scala.io.Source.fromFile("input.txt").getLines().foreach {
    line => ... }

"Continuously read words or lines from a text stream until there is no more data available."


val xml = <root><element>Some text here</element></root>
scala.xml.XML.save(filename="output.xml", node=xml, enc="UTF-8", xmlDecl=true, doctype=null)

Create a simple DOM and serialize it into the specified XML format.


Library: ScalaAd hoc solution as REPL scripts:
JDK < 8[edit]
println(new java.util.Date)

the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.


class SEDOL(s: String) {
  require(s.size == 6 || s.size == 7, "SEDOL length must be 6 or 7 characters")
  require(s.size == 6 || s(6).asDigit == chksum, "Incorrect SEDOL checksum")
  require(s forall (c => !("aeiou" contains c.toLower)), "Vowels not allowed in SEDOL")
  def chksum = 10 - ((s zip List(1, 3, 1, 7, 3, 9) map { case (c, w) => c.asDigit * w } sum) % 10)
  override def toString = s.take(6) + chksum
}

scala> """710889
     | B0YBKJ
     | 406566
     | B0YBLH
     | 228276
     | B0YBKL
     | 557910
     | B0YBKR
     | 585284
     | B0YBKT""".lines.map(_.trim).foreach(s => println(new SEDOL(s)))
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7

scala> new SEDOL("12")
java.lang.IllegalArgumentException: requirement failed: SEDOL length must be 6 or 7 characters

scala> new SEDOL("7108890")
java.lang.IllegalArgumentException: requirement failed: Incorrect SEDOL checksum

scala> new SEDOL("71088A")
java.lang.IllegalArgumentException: requirement failed: Vowels not allowed in SEDOL

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end. It also validates the input to ensure it contains only valid characters for a SEDOL string.


object Sphere extends App {
  private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))

  private def drawSphere(r: Double, k: Double, ambient: Double): Unit = {
    def dot(x: Array[Double], y: Array[Double]) = {
      val d = x.head * y.head + x(1) * y(1) + x.last * y.last
      if (d < 0) -d else 0D
    }

    for (i <- math.floor(-r).toInt to math.ceil(r).toInt; x = i + .5)
      println(
        (for (j <- math.floor(-2 * r).toInt to math.ceil(2 * r).toInt; y = j / 2.0 + .5)
          yield if (x * x + y * y <= r * r) {

            def intensity(vec: Array[Double]) = {
              val b = math.pow(dot(light, vec), k) + ambient
              if (b <= 0) shades.length - 2
              else math.max((1 - b) * (shades.length - 1), 0).toInt
            }

            shades(intensity(normalize(Array(x, y, scala.math.sqrt(r * r - x * x - y * y)))))
          } else ' ').mkString)
  }

  private def normalize(v: Array[Double]): Array[Double] = {
    val len = math.sqrt(v.head * v.head + v(1) * v(1) + v.last * v.last)
    v.map(_ / len)
  }

  normalize(light).copyToArray(light)
  drawSphere(20, 4, .1)
  drawSphere(10, 2, .4)

}

"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection."


Library: Scalaobject Nth extends App {
  def abbrevNumber(i: Int) = print(s"$i${ordinalAbbrev(i)} ")

  def ordinalAbbrev(n: Int) = {
    val ans = "th" //most of the time it should be "th"
    if (n % 100 / 10 == 1) ans //teens are all "th"
    else (n % 10) match {
      case 1 => "st"
      case 2 => "nd"
      case 3 => "rd"
      case _ => ans
    }
  }

  (0 to 25).foreach(abbrevNumber)
  println()
  (250 to 265).foreach(abbrevNumber)
  println();
  (1000 to 1025).foreach(abbrevNumber)
}

The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.


def stripChars(s:String, ch:String)= s filterNot (ch contains _)

stripChars("She was a soul stripper. She took my heart!", "aei")
// => Sh ws  soul strppr. Sh took my hrt!

"Function to remove specific characters from a given string"


Output for all examples:
$ scala GeneralFizzBuzz.scala
20
3 Fizz
5 Buzz
7 Baxx
^D

1
2
Fizz
4
Buzz
Fizz
Baxx
8
Fizz
Buzz
11
Fizz
13
Baxx
FizzBuzz
16
17
Fizz
19
Buzz

Simple[edit]
import scala.io.{Source, StdIn}

object GeneralFizzBuzz extends App {
  val max = StdIn.readInt()
  val factors = Source.stdin.getLines().toSeq
    .map(_.split(" ", 2))
    .map(f => f(0).toInt -> f(1))
    .sorted

  (1 to max).foreach { i =>
    val words = factors.collect { case (k, v) if i % k == 0 => v }
    println(if (words.nonEmpty) words.mkString else i)
  }
}

LazyList (f/k/a Stream)[edit]
import scala.io.{Source, StdIn}

object GeneralFizzBuzz extends App {
  def fizzBuzzTerm(n: Int, factors: Seq[(Int, String)]): String = {
    val words = factors.collect { case (k, v) if n % k == 0 => v }
    if (words.nonEmpty) words.mkString else n.toString
  }

  def fizzBuzz(factors: Seq[(Int, String)]): LazyList[String] =
    LazyList.from(1).map(fizzBuzzTerm(_, factors))

  val max = StdIn.readInt()
  val factors = Source.stdin.getLines().toSeq
    .map(_.split(" ", 2))
    .map { case Array(k, v) => k.toInt -> v }
    .sorted
  fizzBuzz(factors).take(max).foreach(println)
}

Scala 3 (Dotty)[edit]
Translation of: LazyList (f/k/a Stream)
import scala.io.{Source, StdIn}

def fizzBuzzTerm(n: Int, factors: Seq[(Int, String)]): String | Int =
  val words = factors.collect { case (k, v) if n % k == 0 => v }
  if words.nonEmpty then words.mkString else n

def fizzBuzz(factors: Seq[(Int, String)]): LazyList[String | Int] =
  LazyList.from(1).map(i => fizzBuzzTerm(i, factors))

@main def run(): Unit =
  val max = StdIn.readInt()
  val factors: Seq[(Int, String)] = Source.stdin.getLines().toSeq
    .map(_.split(" ", 2))
    .map { case Array(k, v) => k.toInt -> v }
    .sorted
  fizzBuzz(factors).take(max).foreach(println)

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


  val s = "World" // Immutables are recommended   //> s  : String = World
  val f2 = () => ", " //Function assigned to variable
                                                  //> f2  : () => String = <function0>
  val s1 = "Hello" + f2() + s                     //> s1  : String = Hello, World
  println(s1);                                    //> Hello, World

create a string variable, prepend another string to it, and display the result. If possible, the solution should avoid referencing the variable twice in one expression. The functionality is demonstrated using Scala.


import javax.swing.JFrame
import java.awt.Graphics

class DragonCurve(depth: Int) extends JFrame(s"Dragon Curve (depth $depth)") {

  setBounds(100, 100, 800, 600);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  val len = 400 / Math.pow(2, depth / 2.0);
  val startingAngle = -depth * (Math.PI / 4);
  val steps = getSteps(depth).filterNot(c => c == 'X' || c == 'Y')

  def getSteps(depth: Int): Stream[Char] = {
    if (depth == 0) {
      "FX".toStream
    } else {
      getSteps(depth - 1).flatMap{
        case 'X' => "XRYFR"
        case 'Y' => "LFXLY"
        case c => c.toString
      }
    }
  }

  override def paint(g: Graphics): Unit = {
    var (x, y) = (230, 350)
    var (dx, dy) = ((Math.cos(startingAngle) * len).toInt, (Math.sin(startingAngle) * len).toInt)
    for (c <- steps) c match {
      case 'F' => {
        g.drawLine(x, y, x + dx, y + dy)
        x = x + dx
        y = y + dy
      }
      case 'L' => {
        val temp = dx
        dx = dy
        dy = -temp
      }
      case 'R' => {
        val temp = dx
        dx = -dy
        dy = temp
      }
    }
  }

}

object DragonCurve extends App {
  new DragonCurve(14).setVisible(true);
}

generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.


val n = (math.random * 10 + 1).toInt
print("Guess the number: ")
while(readInt != n) print("Wrong! Guess again: ")
println("Well guessed!")

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


Library: Scala
object Abc extends App {
  val lowAlpha = 'a' to 'z' //That's all
  // Now several tests
  assert(lowAlpha.toSeq == Seq('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
    'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'),
    "No complete lowercase alphabet.")
  assert(lowAlpha.size == 26, "No 26 characters in alphabet")
  assert(lowAlpha.start == 'a', "Character 'a' not first char! ???")
  assert(lowAlpha.head == 'a', "Character 'a' not heading! ???")
  assert(lowAlpha.head == lowAlpha(0), "Heading char is not first char.")
  assert(lowAlpha contains 'n', "Character n not present.")
  assert(lowAlpha.indexOf('n') == 13, "Character n not on the 14th position.")
  assert(lowAlpha.last == lowAlpha(25), "Expected character (z)on the last and 26th pos.")

  println(s"Successfully completed without errors. [within ${
    scala.compat.Platform.currentTime - executionStart
  } ms]")
}

generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.


scala> (5 toBinaryString)
res0: String = 101

scala> (50 toBinaryString)
res1: String = 110010

scala> (9000 toBinaryString)
res2: String = 10001100101000

The code takes a non-negative integer as input and outputs its binary representation. It uses either built-in radix functions or a user-defined function to generate the binary sequence. The output consists of binary digits followed by a newline, with no additional whitespace, radix, or sign markers, and no leading zeros. In Scala, this can be achieved using the toBinaryString method.


create a 320x240 window and draw a red pixel at position (100, 100). It is best viewed in a browser with Scastie (remote JVM).


Filters out empty and comment lines
Splits field name and value(s)
Adds "true" to value-less fields
Converts values to (k, List(values)
Converts the entire collection to a Map
val conf = scala.io.Source.fromFile("config.file").
  getLines.
  toList.
  filter(_.trim.size > 0).
  filterNot("#;" contains _(0)).
  map(_ split(" ", 2) toList).
  map(_ :+ "true" take 2).
  map {
    s:List[String] => (s(0).toLowerCase, s(1).split(",").map(_.trim).toList)
  }.toMap

for ((k,v) <- conf) {
  if (v.size == 1)
    println("%s: %s" format (k, v(0)))
  else
    for (i <- 0 until v.size)
      println("%s(%s): %s" format (k, i+1, v(i)))

}

Code summarization: The code reads a configuration file, ignores lines starting with a hash or semicolon, and sets variables based on the configuration parameters. It also handles multiple parameters, storing them in an array. The variables include fullname, favouritefruit, needspeeling, seedsremoved, and otherfamily.


import math._

object Haversine {
   val R = 6372.8  //radius in km

   def haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double)={
      val dLat=(lat2 - lat1).toRadians
      val dLon=(lon2 - lon1).toRadians

      val a = pow(sin(dLat/2),2) + pow(sin(dLon/2),2) * cos(lat1.toRadians) * cos(lat2.toRadians)
      val c = 2 * asin(sqrt(a))
      R * c
   }

   def main(args: Array[String]): Unit = {
      println(haversine(36.12, -86.67, 33.94, -118.40))
  }
}

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


Library: Scala
import scala.io.Source

object HttpTest extends App {
  System.setProperty("http.agent", "*")

  Source.fromURL("http://www.rosettacode.org").getLines.foreach(println)
}

Print the content of a specified URL to the console using HTTP request.


Library: Scala
Functional style[edit]
object Luhn {
  private def parse(s: String): Seq[Int] = s.map{c =>
    assert(c.isDigit)
    c.asDigit
  }
  def checksum(digits: Seq[Int]): Int = {
    digits.reverse.zipWithIndex.foldLeft(0){case (sum,(digit,i))=>
      if (i%2 == 0) sum + digit
      else sum + (digit*2)/10 + (digit*2)%10
    } % 10
  }
  def validate(digits: Seq[Int]): Boolean = checksum(digits) == 0
  def checksum(number: String): Int = checksum(parse(number))
  def validate(number: String): Boolean = validate(parse(number))
}

object LuhnTest extends App {
  Seq(("49927398716", true),
    ("49927398717", false),
    ("1234567812345678", false),
    ("1234567812345670", true)
  ).foreach { case (n, expected) =>
    println(s"$n ${Luhn.validate(n)}")
    assert(Luhn.validate(n) == expected)
  }
}

The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


def executed( prisonerCount:Int, step:Int ) = {

  val prisoners = ((0 until prisonerCount) map (_.toString)).toList

  def behead( dead:Seq[String], alive:Seq[String] )(countOff:Int) : (Seq[String], Seq[String]) = {
    val group = if( alive.size < countOff ) countOff - alive.size else countOff

    (dead ++ alive.take(group).drop(group-1), alive.drop(group) ++ alive.take(group-1))
  }

  def beheadN( dead:Seq[String], alive:Seq[String] ) : (Seq[String], Seq[String]) =
    behead(dead,alive)(step)

  def execute( t:(Seq[String], Seq[String]) ) : (Seq[String], Seq[String]) = t._2 match {
    case x :: Nil => (t._1, Seq(x))
    case x :: xs => execute(beheadN(t._1,t._2))
  }

  execute((List(),prisoners))
}

val (dead,alive) = executed(41,3)

println( "Prisoners executed in order:" )
print( dead.mkString(" ") )

println( "\n\nJosephus is prisoner " + alive(0) )

The code calculates the final survivor in the Josephus problem, given the total number of prisoners (n) and the step count (k). It also provides a method to determine the position of any prisoner in the killing sequence. The prisoners are numbered from 0 to n-1. The code also accounts for scenarios where multiple survivors (m) are allowed. The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is "ha" and 5, the output will be "hahahahaha". Similarly, if the input is "*" and 5, the output will be "*****".


Library: Scala

val Bottles1 = "(\\d+) bottles of beer".r                                            // syntactic sugar
val Bottles2 = """(\d+) bottles of beer""".r                                         // using triple-quotes to preserve backslashes
val Bottles3 = new scala.util.matching.Regex("(\\d+) bottles of beer")               // standard
val Bottles4 = new scala.util.matching.Regex("""(\d+) bottles of beer""", "bottles") // with named groups

"99 bottles of beer" matches "(\\d+) bottles of beer" // the full string must match
"99 bottles of beer" replace ("99", "98") // Single replacement
"99 bottles of beer" replaceAll ("b", "B") // Multiple replacement

"\\d+".r findFirstIn "99 bottles of beer" // returns first partial match, or None
"\\w+".r findAllIn "99 bottles of beer" // returns all partial matches as an iterator
"\\s+".r findPrefixOf "99 bottles of beer" // returns a matching prefix, or None
Bottles4 findFirstMatchIn "99 bottles of beer" // returns a "Match" object, or None
Bottles4 findPrefixMatchOf "99 bottles of beer" // same thing, for prefixes
val bottles = (Bottles4 findFirstMatchIn "99 bottles of beer").get.group("bottles") // Getting a group by name

val Some(bottles) = Bottles4 findPrefixOf "99 bottles of beer" // throws an exception if the matching fails; full string must match
for {
  line <- """|99 bottles of beer on the wall
             |99 bottles of beer
             |Take one down, pass it around
             |98 bottles of beer on the wall""".stripMargin.lines
} line match {
  case Bottles1(bottles) => println("There are still "+bottles+" bottles.") // full string must match, so this will match only once
  case _ =>
}
for {
  matched <- "(\\w+)".r findAllIn "99 bottles of beer" matchData // matchData converts to an Iterator of Match
} println("Matched from "+matched.start+" to "+matched.end)

Bottles2 replaceFirstIn ("99 bottles of beer", "98 bottles of beer")
Bottles3 replaceAllIn ("99 bottles of beer", "98 bottles of beer")

1. Matches a string against a specific regular expression.
2. Substitutes a portion of a string using a defined regular expression.
3. Implements search and replace functionalities using string methods.
4. Executes search operations using regex methods.
5. Utilizes pattern matching with regular expressions.
6. Performs replacements in a string using regular expressions.


val a = Console.readInt
val b = Console.readInt

val sum = a + b //integer addition is discouraged in print statements due to confusion with String concatenation
println("a + b = " + sum)
println("a - b = " + (a - b))
println("a * b = " + (a * b))
println("quotient of a / b = " + (a / b)) // truncates towards 0
println("remainder of a / b = " + (a % b)) // same sign as first operand

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


Using Recursion[edit]
import scala.annotation.tailrec
def countSubstring(str1:String, str2:String):Int={
   @tailrec def count(pos:Int, c:Int):Int={
      val idx=str1 indexOf(str2, pos)
      if(idx == -1) c else count(idx+str2.size, c+1)
   }
   count(0,0)
}

Using Sliding[edit]
def countSubstring(str: String, sub: String): Int =
  str.sliding(sub.length).count(_ == sub)

Using Regular Expressions[edit]
def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length

println(countSubstring("ababababab", "abab"))
println(countSubstring("the three truths", "th"))

The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for, and returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches and does not count overlapping substrings.


def move(n: Int, from: Int, to: Int, via: Int) : Unit = {
    if (n == 1) {
      Console.println("Move disk from pole " + from + " to pole " + to)
    } else {
      move(n - 1, from, via, to)
      move(1, from, to, via)
      move(n - 1, via, to, from)
    }
  }

object TowersOfHanoi {
  import scala.reflect.Manifest

  def simpleName(m:Manifest[_]):String = {
    val name = m.toString
    name.substring(name.lastIndexOf('$')+1)
  }

  trait Nat
  final class _0 extends Nat
  final class Succ[Pre<:Nat] extends Nat

  type _1 = Succ[_0]
  type _2 = Succ[_1]
  type _3 = Succ[_2]
  type _4 = Succ[_3]

  case class Move[N<:Nat,A,B,C]()

  implicit def move0[A,B,C](implicit a:Manifest[A],b:Manifest[B]):Move[_0,A,B,C] = {
        System.out.println("Move from "+simpleName(a)+" to "+simpleName(b));null
  }

  implicit def moveN[P<:Nat,A,B,C](implicit m1:Move[P,A,C,B],m2:Move[_0,A,B,C],m3:Move[P,C,B,A])
   :Move[Succ[P],A,B,C] = null

  def run[N<:Nat,A,B,C](implicit m:Move[N,A,B,C]) = null

  case class Left()
  case class Center()
  case class Right()

  def main(args:Array[String]){
    run[_2,Left,Right,Center]
  }
}

use recursion to solve the Towers of Hanoi problem. The solution is a Scala translation of a Prolog solution from http://gist.github.com/66925, which solves the problem at compile time.


object Binomial {
   def main(args: Array[String]): Unit = {
      val n=5
      val k=3
      val result=binomialCoefficient(n,k)
      println("The Binomial Coefficient of %d and %d equals %d.".format(n, k, result))
   }

   def binomialCoefficient(n:Int, k:Int)=fact(n) / (fact(k) * fact(n-k))
   def fact(n:Int):Int=if (n==0) 1 else n*fact(n-1)
}

The code calculates any binomial coefficient, with a specific focus on outputting the binomial coefficient of 5 choose 3, which is 10. It uses the formula for binomial coefficients and can handle coefficients of arbitrary size due to the use of BigInts. The code also includes functionality for combinations and permutations, with and without replacement.


object ShellSort {
  def incSeq(len:Int)=new Iterator[Int]{
    private[this] var x:Int=len/2
    def hasNext=x>0
    def next()={x=if (x==2) 1 else x*5/11; x}
  }

  def InsertionSort(a:Array[Int], inc:Int)={
    for (i <- inc until a.length; temp=a(i)){
      var j=i;
      while (j>=inc && a(j-inc)>temp){
        a(j)=a(j-inc)
        j=j-inc
      }
      a(j)=temp
    }
  }

  def shellSort(a:Array[Int])=for(inc<-incSeq(a.length)) InsertionSort(a, inc)

  def main(args: Array[String]): Unit = {
    var a=Array(2, 5, 3, 4, 3, 9, 3, 2, 5, 4, 1, 3, 22, 7, 2, -5, 8, 4)
    println(a.mkString(","))
    shellSort(a)
    println(a.mkString(","))
  }
}

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


object BitmapOps {
   def luminosity(c:Color)=(0.2126*c.getRed + 0.7152*c.getGreen + 0.0722*c.getBlue+0.5).toInt

   def grayscale(bm:RgbBitmap)={
      val image=new RgbBitmap(bm.width, bm.height)
      for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y)))
         image.setPixel(x, y, new Color(l,l,l))
      image
   }
}

extend the data storage type to support grayscale images, convert color images to grayscale and vice versa using the CIE recommended formula for luminance. The codes also ensure that rounding errors in floating-point arithmetic do not cause run-time problems or distorted results. The codes utilize the Scala Basic Bitmap Storage class.


Works with: Scala version 2.8
import scala.actors.Actor.{actor, loop, reactWithin, exit}
import scala.actors.TIMEOUT
import scala.swing.{SimpleSwingApplication, MainFrame, Label}
import scala.swing.event.MouseClicked

case object Revert

object BasicAnimation extends SimpleSwingApplication {
  val label = new Label("Hello World! ")
  val rotator = actor {
    var goingRight = true
    loop {
      reactWithin(250 /*ms*/) {
        case Revert => goingRight = !goingRight
        case TIMEOUT =>
          if (goingRight)
            label.text = label.text.last + label.text.init
          else
            label.text = label.text.tail + label.text.head
        case unknown => println("Unknown message "+unknown); exit()
      }
    }
  }
  def top = new MainFrame {
    title = "Basic Animation"
    contents = label
  }
  listenTo(label.mouse.clicks) // use "Mouse" instead of "mouse" on Scala 2.7
  reactions += {
    case _ : MouseClicked => rotator ! Revert
  }
}

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


Library: Scala
Imperative[edit]
  {
    var (x, l) = (0, List[Int]())
    do {
      x += 1
      l :+= x // A new copy of this list with List(x) appended.
    } while (x % 6 != 0)
    l
  }.foreach(println(_))
Tail recursive[edit]
	def loop(iter: Int, cond: (Int) => Boolean, accu: List[Int]): List[Int] = {
	  val succ = iter + 1
	  val temp = accu :+ succ
	  if (cond(succ)) loop(succ, cond, temp) else temp
	}
	println(loop(0, (_ % 6 != 0), Nil))
Stream[edit]
  def loop(i: Int, cond: (Int) => Boolean): Stream[Int] = {
    val succ = i + 1;
    succ #:: (if (cond(succ)) loop(succ, cond) else Stream.empty)
  }
  loop(0, (_ % 6 != 0)).foreach(println(_))

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


Library: Scala
object StringLength extends App {
  val s1 = "møøse"
  val s3 = List("\uD835\uDD18", "\uD835\uDD2B", "\uD835\uDD26",
    "\uD835\uDD20", "\uD835\uDD2C", "\uD835\uDD21", "\uD835\uDD22").mkString
  val s4 = "J\u0332o\u0332s\u0332e\u0301\u0332"

    List(s1, s3, s4).foreach(s => println(
        s"The string: $s, characterlength= ${s.length} UTF8bytes= ${
      s.getBytes("UTF-8").size
    } UTF16bytes= ${s.getBytes("UTF-16LE").size}"))
}

calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.


import java.security.SecureRandom

object RandomExample extends App {
  new SecureRandom {
    val newSeed: Long = this.nextInt().toLong * this.nextInt()
    this.setSeed(newSeed) // reseed using the previous 2 random numbers
    println(this.nextInt()) // get random 32-bit number and print it
  }
}

demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.


Library: Scala
println("knight".tail)               // strip first character
println("socks".init)         // strip last character
println("brooms".tail.init)   // strip both first and last characters

The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.


"Check if an application instance is already running, display a message if so, and terminate the program."


import java.awt.{Dimension, Insets, Toolkit}

import javax.swing.JFrame

class MaxWindowDims() extends JFrame {
  val toolkit: Toolkit = Toolkit.getDefaultToolkit
  val (insets0, screenSize) = (toolkit.getScreenInsets(getGraphicsConfiguration),  toolkit.getScreenSize)

  println("Physical screen size: " + screenSize)
  System.out.println("Insets: " + insets0)
  screenSize.width -= (insets0.left + insets0.right)
  screenSize.height -= (insets0.top + insets0.bottom)
  System.out.println("Max available: " + screenSize)
}

object MaxWindowDims {
  def main(args: Array[String]): Unit = {
    new MaxWindowDims
  }
}

calculate the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations, menubars, multiple monitors, and tiling window managers.


Works with: Scala version 2.9.1
object SudokuSolver extends App {

  class Solver {

    var solution = new Array[Int](81)   //listOfFields toArray

    val fp2m: Int => Tuple2[Int,Int] = pos => Pair(pos/9+1,pos%9+1) //get row, col from array position
    val setAll = (1 to 9) toSet //all possibilities

    val arrayGroups = new Array[List[List[Int]]](81)
    val sv: Int => Int = (row: Int) => (row-1)*9 //start value group row
    val ev: Int => Int = (row: Int) => sv(row)+8 //end value group row
    val fgc: (Int,Int) => Int = (i,col) => i*9+col-1 //get group col
    val fgs: Int => (Int,Int) = p => Pair(p, p/(27)*3+p%9/3) //get group square box
    for (pos <- 0 to 80) {
      val (row,col) = fp2m(pos)
      val gRow = (sv(row) to ev(row)).toList
      val gCol = ((0 to 8) toList) map (fgc(_,col))
      val gSquare = (0 to 80 toList) map fgs filter (_._2==(fgs(pos))._2) map (_._1)
      arrayGroups(pos) = List(gRow,gCol,gSquare)
    }
    val listGroups = arrayGroups toList

    val fpv4s: (Int) => List[Int] = pos => {   //get possible values for solving
      val setRow = (listGroups(pos)(0) map (solution(_))).toSet
      val setCol = listGroups(pos)(1).map(solution(_)).toSet
      val setSquare = listGroups(pos)(2).map(solution(_)).toSet
      val setG = setRow++setCol++setSquare--Set(0)
      val setPossible = setAll--setG
      setPossible.toList.sortWith(_<_)
    }

    //solve the riddle: Nil ==> solution does not exist
    def solve(listOfFields: List[Int]): List[Int] = {
      solution = listOfFields toArray

      def checkSol(uncheckedSol: List[Int]): List[Int] = {
        if (uncheckedSol == Nil) return Nil
        solution = uncheckedSol toArray
        val check = (0 to 80).map(fpv4s(_)).filter(_.size>0)
        if (check == Nil) return uncheckedSol
        return Nil
      }

      val f1: Int => Pair[Int,Int] = p => Pair(p,listOfFields(p))
      val numFields = (0 to 80 toList) map f1 filter (_._2==0)
      val iter = numFields map ((_: (Int,Int))._1)
      var p_iter = 0

      val first: () => Int = () => {
        val ret = numFields match {
          case Nil => -1
          case _   => numFields(0)._1
        }
        ret
      }

      val last: () => Int = () => {
        val ret = numFields match {
          case Nil => -1
          case _   => numFields(numFields.size-1)._1
        }
        ret
      }

      val hasPrev: () => Boolean = () => p_iter > 0
      val prev: () => Int = () => {p_iter -= 1; iter(p_iter)}
      val hasNext: () => Boolean = () => p_iter < iter.size-1
      val next: () => Int = () => {p_iter += 1; iter(p_iter)}
      val fixed: Int => Boolean = pos => listOfFields(pos) != 0
      val possiArray = new Array[List[Int]](numFields.size)
      val firstUF = first() //first unfixed
      if (firstUF < 0) return checkSol(solution.toList) //that is it!
      var pif = iter(p_iter) //pos in fields
      val lastUF = last() //last unfixed
      val (row,col) = fp2m(pif)
      possiArray(p_iter) = fpv4s(pif).toList.sortWith(_<_)

      while(pif <= lastUF) {
        val (row,col) = fp2m(pif)
        if (possiArray(p_iter) == null) possiArray(p_iter) = fpv4s(pif).toList.sortWith(_<_)
        val possis = possiArray(p_iter)
        if (possis.isEmpty) {
          if (hasPrev()) {
            possiArray(p_iter) = null
            solution(pif) = 0
            pif = prev()
          } else {
            return Nil
          }
        } else {
          solution(pif) = possis(0)
          possiArray(p_iter) = (possis.toSet - possis(0)).toList.sortWith(_<_)
          if (hasNext()) {
            pif = next()
          } else {
            return checkSol(solution.toList)
          }
        }
      }
      checkSol(solution.toList)
    }
  }

  val f2Str: List[Int] => String = fields => {
    val sepLine = "+---+---+---+"
    val sepPoints = Set(2,5,8)
    val fs: (Int, Int) => String = (i, v) => v.toString.replace("0"," ")+(if (sepPoints.contains(i%9)) "|" else "")
    sepLine+"\n"+(0 to fields.size-1).map(i => (if (i%9==0) "|" else "")+fs(i,fields(i))+(if (i%9==8) if (sepPoints.contains(i/9)) "\n"+sepLine+"\n" else "\n" else "")).foldRight("")(_+_)
  }

  val solver = new Solver()

  val riddle = List(3,9,4,0,0,2,6,7,0,
                    0,0,0,3,0,0,4,0,0,
                    5,0,0,6,9,0,0,2,0,
                    0,4,5,0,0,0,9,0,0,
                    6,0,0,0,0,0,0,0,7,
                    0,0,7,0,0,0,5,8,0,
                    0,1,0,0,6,7,0,0,8,
                    0,0,9,0,0,8,0,0,0,
                    0,2,6,4,0,0,7,3,5)

  println("riddle:")
  println(f2Str(riddle))
  var solution = solver.solve(riddle)

  println("solution:")
  println(solution match {case Nil => "no solution!!!" case _ => f2Str(solution)})

}

"Implement a Sudoku solver that can solve a partially filled 9x9 Sudoku grid and display the result in a human-readable format. The solver can handle standard and jigsaw type Sudokus, as well as Sudokus with additional constraints such as a diagonal constraint. The code is inspired by the Java section and works effectively, despite not being the most elegant or functional programming solution."


def shuffle[T](a: Array[T]) = {
  for (i <- 1 until a.size reverse) {
    val j = util.Random nextInt (i + 1)
    val t = a(i)
    a(i) = a(j)
    a(j) = t
  }
  a
}

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


import java.util.Calendar
import java.text.SimpleDateFormat

object Fridays {

  def lastFridayOfMonth(year:Int, month:Int)={
    val cal=Calendar.getInstance
    cal.set(Calendar.YEAR, year)
    cal.set(Calendar.MONTH, month)
    cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY)
    cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1)
    cal.getTime
  }

  def fridaysOfYear(year:Int)=for(month <- 0 to 11) yield lastFridayOfMonth(year, month)

  def main(args:Array[String]){
    val year=args(0).toInt
    val formatter=new SimpleDateFormat("yyyy-MMM-dd")
    fridaysOfYear(year).foreach{date=>
      println(formatter.format(date))
    }
  }
}

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


Library: scala
Ad hoc REPL solution[edit]

print("Goodbye, World!")

display the string "Goodbye, World!" without appending a newline at the end.


Library: Scala
import swing.Dialog.{Message, showInput}
import scala.swing.Swing

object UserInput extends App {
  def responce = showInput(null,
    "Complete the sentence:\n\"Green eggs and...\"",
    "Customized Dialog",
    Message.Plain,
    Swing.EmptyIcon,
    Nil, "ham")
  println(responce)
}

"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface."