import java.io.IOException
import java.net.{InetAddress, ServerSocket}

object SingletonApp extends App {
  private val port = 65000

  try {
    val s = new ServerSocket(port, 10, InetAddress.getLocalHost)
  }
  catch {
    case _: IOException =>
      // port taken, so app is already running
      println("Application is already running, so terminating this instance.")
      sys.exit(-1)
  }

  println("OK, only this instance is running but will terminate in 10 seconds.")

  Thread.sleep(10000)

  sys.exit(0)

}

"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

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."


object Caesar {
  private val alphaU='A' to 'Z'
  private val alphaL='a' to 'z'

  def encode(text:String, key:Int)=text.map{
    case c if alphaU.contains(c) => rot(alphaU, c, key)
    case c if alphaL.contains(c) => rot(alphaL, c, key)
    case c => c
  }
  def decode(text:String, key:Int)=encode(text,-key)
  private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)
}
val text="The five boxing wizards jump quickly"
println("Plaintext  => " + text)
val encoded=Caesar.encode(text, 3)
println("Ciphertext => " + encoded)
println("Decrypted  => " + Caesar.decode(encoded, 3))

Implement a Caesar cipher for both encoding and decoding. The cipher uses a key between 1 and 25 to rotate the letters of the alphabet. It replaces each letter with the next 1st to 25th letter in the alphabet, looping from Z back to A. The codes also consider the vulnerabilities of the cipher, such as frequency analysis and brute force attacks. The implementation is similar to Vigenère cipher with a key length of 1 and Rot-13 with key 13. The codes first create non-shifted and shifted character sequences, then perform encoding and decoding by indexing between these sequences.


def gcd(a: Int, b: Int):Int=if (b==0) a.abs else gcd(b, a%b)
def lcm(a: Int, b: Int)=(a*b).abs/gcd(a,b)

lcm(12, 18)   // 36
lcm( 2,  0)   // 0
lcm(-6, 14)   // 42

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


object Cusip extends App {

  val candidates = Seq("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")

  for (candidate <- candidates)
    printf(f"$candidate%s -> ${if (isCusip(candidate)) "correct" else "incorrect"}%s%n")

  private def isCusip(s: String): Boolean = {
    if (s.length != 9) false
    else {
      var sum = 0
      for (i <- 0 until 7) {
        val c = s(i)
        var v = 0
        if (c >= '0' && c <= '9') v = c - 48
        else if (c >= 'A' && c <= 'Z') v = c - 55 // lower case letters apparently invalid
        else if (c == '*') v = 36
        else if (c == '@') v = 37
        else if (c == '#') v = 38
        else return false
        if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing
        sum += v / 10 + v % 10
      }
      s(8) - 48 == (10 - (sum % 10)) % 10
    }
  }

}

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


Library: Scalaimport java.nio.ByteOrder

object ShowByteOrder extends App {
  println(ByteOrder.nativeOrder())
  println(s"Word size: ${System.getProperty("sun.arch.data.model")}")
  println(s"Endianness: ${System.getProperty("sun.cpu.endian")}")
}

"Outputs the word size and endianness of the host machine."


import akka.actor.{Actor, ActorSystem, Props}
import scala.collection.immutable.TreeSet
import scala.xml.XML

// Reports a list with all languages recorded in the Wiki

private object Acquisition {
  val (endPoint, prefix) = ("http://rosettacode.org/mw/api.php", "Category:")
  val (maxPlaces, correction) = (50, 2)

  def convertPathArgsToURL(endPoint: String, pathArgs: Map[String, String]) = {
    pathArgs.map(argPair => argPair._1 + "=" + argPair._2)
      .mkString(endPoint + (if (pathArgs.nonEmpty) "?" else ""), "&", "")
  }

  /* The categories include a page for the language and a count of the pages
   * linked therein, this count is the data we need to scrape.
   * Reports a list with language, count pair recorded in the Wiki
   * All strings starts with the prefixes "Category:"
   */
  def mineCatos = {
    val endPoint = "http://rosettacode.org/mw/index.php"
    Concurrent.logInfo("Acquisition of categories started.")
    val categories =
      (XML.load(convertPathArgsToURL(endPoint,
        Map("title" -> "Special:Categories", "limit" -> "5000"))) \\ "ul" \ "li")
        .withFilter(p => (p \ "a" \ "@title").text.startsWith(prefix))
        .map // Create a tuple pair, eg. ("Category:Erlang", 195)
        { cat =>
          ((cat \ "a" \ "@title").text, // Takes the sibling of "a" and extracts the number
            "[0-9]+".r.findFirstIn(cat.child.drop(1).text).getOrElse("0").toInt)
        }
    Concurrent.logInfo(s"Got ${categories.size} categories..")
    categories
  }

  // The languages
  // All strings starts with the prefixes "Category:"
  def mineLangs = {
    Concurrent.logInfo("Acquisition of languages started...")
    def getLangs(first: Boolean = true, continue: String = ""): TreeSet[String] = (first, continue) match {
      case (false, "") => TreeSet[String]()
      case _ => {
        val xml = XML.load(convertPathArgsToURL(endPoint, Map(
            "action" -> "query",
            "list" -> "categorymembers",
            "cmtitle" -> (prefix + "Programming_Languages"),
            "cmlimit" -> "500",
            "rawcontinue" -> "",
            "format" -> "xml",
            "cmcontinue" -> continue)))
        getLangs(false, (xml \\ "query-continue" \ "categorymembers" \ "@cmcontinue").text) ++ (xml \\ "categorymembers" \ "cm").map(c => (c \ "@title").text)
      }
    }
    val languages = getLangs()
    Concurrent.logInfo(s"Got ${languages.size} languages..")
    languages
  }

  def joinRosettaCodeWithLanguage(catos: Seq[(String, Int)],
                                  langs: TreeSet[String]) =
    for {
      cato <- catos //Clean up the tuple pairs, eg ("Category:Erlang", 195) becomes ("Erlang", 192)
      if langs.contains(cato._1)
    } yield (cato._1.drop(prefix.length), cato._2 - correction max 0) // Correct count

  def printScrape(languages: TreeSet[String], category: Seq[(String, Int)]) {

    val join = joinRosettaCodeWithLanguage(category, languages)
    val total = join.foldLeft(0)(_ + _._2)

    Concurrent.logInfo("Data processed")

    println(f"\nTop$maxPlaces%3d Rosetta Code Languages by Popularity as ${new java.util.Date}%tF:\n")
    (join.groupBy(_._2).toSeq.sortBy(-_._1).take(maxPlaces) :+ (0, Seq(("...", 0))))
      .zipWithIndex // Group the ex aequo
      .foreach {
        case ((score, langs), rank) =>
          println(f"${rank + 1}%2d. $score%3d - ${langs.map(_._1).mkString(", ")}")
      }

    println(s"\nCross section yields ${join.size} languages, total of $total solutions")
    println(s"Resulting average is ${total / join.size} solutions per language")
  }

  def printScrape(): Unit = printScrape(mineLangs, mineCatos)
} // object Acquisition

private object Concurrent extends AppCommons {
  var (category: Option[Seq[(String, Int)]], language: Option[TreeSet[String]]) = (None, None)

  class Worker extends Actor {
    def receive = {
      case 'Catalogue => sender ! Acquisition.mineCatos
      case 'Language => sender ! Acquisition.mineLangs
    }
  }

  class Listener extends Actor {
    // Create and signal the worker actors
    context.actorOf(Props[Worker], "worker0") ! 'Catalogue
    context.actorOf(Props[Worker], "worker1") ! 'Language

    def printCompleteScape() =
      if (category.isDefined && language.isDefined) {
        Acquisition.printScrape(language.get, category.get)
        context.system.shutdown()
        appEnd()
      }

    def receive = {
      case content: TreeSet[String] =>
        language = Some(content)
        printCompleteScape()
      case content: Seq[(String, Int)] =>
        category = Some(content)
        printCompleteScape()
      case whatever => logInfo(whatever.toString)
    } // def receive
  }
} // object Concurrent

trait AppCommons {
  val execStart = System.currentTimeMillis()
  System.setProperty("http.agent", "*")

  def logInfo(info: String) {
    println(f"[Info][${System.currentTimeMillis() - execStart}%5d ms]" + info)
  }

  def appEnd() { logInfo("Run succesfully completed") }
}

// Main entry for sequential version (slower)
object GhettoParserSeq extends App with AppCommons {
  Concurrent.logInfo("Sequential version started")
  Acquisition.printScrape()
  appEnd()
}

// Entry for parallel version (faster)
object GhettoParserPar extends App {
  Concurrent.logInfo("Parallel version started")
  ActorSystem("Main").actorOf(Props[Concurrent.Listener])
}

Output for both solutions: but parallel run chosen. Notice the synchronous start time.
[Info][    0 ms]Sequential version started
[Info][    3 ms]Acquisition of languages started...
[Info][ 1458 ms]Got 642 languages..
[Info][ 1458 ms]Acquisition of categories started.
[Info][19385 ms]Got 2647 categories..
[Info][19389 ms]Data processed

Top 50 Rosetta Code Languages by Popularity as 2016-11-11:

 1. 907 - Racket
 2. 896 - Python, Tcl
 3. 859 - J
 4. 846 - Perl 6
 5. 810 - Ruby
 6. 807 - Zkl
 7. 795 - C
 8. 774 - Java
 9. 773 - Go
10. 754 - Haskell
11. 753 - Perl
12. 751 - REXX
13. 750 - D
14. 729 - PicoLisp
15. 689 - Mathematica
16. 674 - Sidef
17. 634 - C++
18. 631 - Ada
19. 609 - AutoHotkey
20. 592 - Common Lisp
21. 583 - Unicon
22. 569 - Scala
23. 560 - C sharp
24. 546 - BBC BASIC
25. 526 - Icon
26. 522 - Clojure
27. 520 - JavaScript
28. 519 - OCaml
29. 517 - PureBasic
30. 513 - PARI/GP
31. 510 - Lua
32. 509 - Nim
33. 497 - ALGOL 68
34. 491 - Elixir
35. 488 - Fortran
36. 474 - Erlang
37. 430 - PowerShell
38. 428 - Julia
39. 414 - Jq
40. 413 - F Sharp
41. 409 - Phix
42. 407 - Pascal
43. 405 - Forth, Seed7
44. 398 - PL/I
45. 383 - R
46. 382 - PHP
47. 377 - Groovy
48. 370 - AWK
49. 340 - MATLAB
50. 333 - Liberty BASIC
51.   0 - ...

Cross section yields 619 languages, total of 50835 solutions
Resulting average is 82 solutions per language
[Info][19413 ms]Run succesfully completed

The code sorts and ranks computer programming languages based on their popularity, determined by the number of members in their respective Rosetta Code categories. It uses either web scraping or API methods to access the data. The code also provides an option to filter incorrect results. The results are checked against a complete, accurate, and periodically updated list of all programming languages. The code also includes an entry point at object GhettoParserPar and GhettoParserSeq.


val collection = Array(1, 2, 3, 4)
collection.foreach(println)

(element <- 1 to 4).foreach(println)

Iterates through each element in a collection in order using a "for each" loop or another loop if "for each" is not available, and prints each element.


println("Hello,How,Are,You,Today" split "," mkString ".")

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)

@tailrec
def gcd(a: Int, b: Int): Int = {
  b match {
    case 0 => a
    case _ => gcd(b, (a % b))
  }
}

find the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It also relates to the task of finding the least common multiple.


import java.io.PrintWriter
import java.net.{ServerSocket, Socket}

import scala.io.Source

object EchoServer extends App {
  private val serverSocket = new ServerSocket(23)
  private var numConnections = 0

  class ClientHandler(clientSocket: Socket) extends Runnable {
    private val (connectionId, closeCmd) = ({numConnections += 1; numConnections}, ":exit")

    override def run(): Unit =
      new PrintWriter(clientSocket.getOutputStream, true) {
        println(s"Connection opened, close with entering '$closeCmd'.")
        Source.fromInputStream(clientSocket.getInputStream).getLines
          .takeWhile(!_.toLowerCase.startsWith(closeCmd))
          .foreach { line =>
            Console.println(s"Received on #$connectionId: $line")
            println(line)  // Echo
          }
        Console.println(s"Gracefully closing connection, #$connectionId")
        clientSocket.close()
    }

    println(s"Handling connection, $connectionId")
  }

  while (true) new Thread(new ClientHandler(serverSocket.accept())).start()
}

Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.


import scala.util.control.Exception.allCatch

def isNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined
def isNumeric(input: String): Boolean = input.forall(_.isDigit)

def isNumeric2(str: String): Boolean = {
  str.matches(s"""[+-]?((\d+(e\d+)?[lL]?)|(((\d+(\.\d*)?)|(\.\d+))(e\d+)?[fF]?))""")
}

def isNumeric(str: String): Boolean = {
  !throwsNumberFormatException(str.toLong) || !throwsNumberFormatException(str.toDouble)
}

def throwsNumberFormatException(f: => Any): Boolean = {
  try { f; false } catch { case e: NumberFormatException => true }
}

"Implement a boolean function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers. The function uses either a complex regular expression or built-in number parsing with exception handling."


Library: Scala
import scala.io.Source

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

  Source.fromURL("https://sourceforge.net").getLines.foreach(println)
}

Send a GET request to the URL "https://www.w3.org/", validate the host certificate, and print the obtained resource to the console without any authentication.


import javax.swing.{ JFrame, JPanel }

object SutherlandHodgman extends JFrame with App {
    import java.awt.BorderLayout

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    setVisible(true)
    val content = getContentPane()
    content.setLayout(new BorderLayout())
    content.add(SutherlandHodgmanPanel, BorderLayout.CENTER)
    setTitle("SutherlandHodgman")
    pack()
    setLocationRelativeTo(null)
}

object SutherlandHodgmanPanel extends JPanel {
    import java.awt.{ Color, Graphics, Graphics2D }

    setPreferredSize(new java.awt.Dimension(600, 500))

    // subject and clip points are assumed to be valid
    val subject = Seq((50D, 150D), (200D, 50D), (350D, 150D), (350D, 300D), (250D, 300D), (200D, 250D), (150D, 350D), (100D, 250D), (100D, 200D))
    val clipper = Seq((100D, 100D), (300D, 100D), (300D, 300D), (100D, 300D))
    var result = subject

    val len = clipper.size
    for (i <- 0 until len) {
        val len2 = result.size
        val input = result
        result = Seq()

        val A = clipper((i + len - 1) % len)
        val B = clipper(i)

        for (j <- 0 until len2) {
            val P = input((j + len2 - 1) % len2)
            val Q = input(j)

            if (inside(A, B, Q)) {
                if (!inside(A, B, P))
                    result = result :+ intersection(A, B, P, Q)
                result = result :+ Q
            }
            else if (inside(A, B, P))
                result = result :+ intersection(A, B, P, Q)
        }
    }

    override def paintComponent(g: Graphics) {
        import java.awt.RenderingHints._

        super.paintComponent(g)
        val g2 = g.asInstanceOf[Graphics2D]
        g2.translate(80, 60)
        g2.setStroke(new java.awt.BasicStroke(3))
        g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON)
        g2.draw_polygon(subject, Color.blue)
        g2.draw_polygon(clipper, Color.red)
        g2.draw_polygon(result, Color.green)
    }

    private def inside(a: (Double, Double), b: (Double, Double), c: (Double, Double)) =
        (a._1 - c._1) * (b._2 - c._2) > (a._2 - c._2) * (b._1 - c._1)

    private def intersection(a: (Double, Double), b: (Double, Double), p: (Double, Double), q: (Double, Double)) = {
        val A1 = b._2 - a._2
        val B1 = a._1 - b._1
        val C1 = A1 * a._1 + B1 * a._2
        val A2 = q._2 - p._2
        val B2 = p._1 - q._1
        val C2 = A2 * p._1 + B2 * p._2

        val det = A1 * B2 - A2 * B1
        ((B2 * C1 - B1 * C2) / det, (A1 * C2 - A2 * C1) / det)
    }

    private implicit final class Polygon_drawing(g: Graphics2D) {
        def draw_polygon(points: Seq[(Double, Double)], color: Color) {
            g.setColor(color)
            val len = points.length
            val line = new java.awt.geom.Line2D.Double()
            for (i <- 0 until len) {
                val p1 = points(i)
                val p2 = points((i + 1) % len)
                line.setLine(p1._1, p1._2, p2._1, p2._2)
                g.draw(line)
            }
        }
    }
}

Implement the Sutherland-Hodgman clipping algorithm to find the intersection of a given polygon and a rectangle. The polygon and rectangle are defined by a sequence of points. The code also includes an extra feature to visually display all three polygons (the original polygon, the rectangle, and the resulting clipped polygon) on a graphical surface, each in a different color.


object RankingMethods extends App {
    case class Score(score: Int, name: String) // incoming data
    case class Rank[Precision](rank: Precision, names: List[String]) // outgoing results (can be int or double)
    case class State[Precision](n: Int, done: List[Rank[Precision]]) { // internal state, no mutable variables
        def next(n: Int, next: Rank[Precision]) = State(n, next :: done)
    }
    def grouped[Precision](list: List[Score]) = // group names together by score, with highest first
        (scala.collection.immutable.TreeMap[Int, List[Score]]() ++ list.groupBy(-_.score))
        .values.map(_.map(_.name)).foldLeft(State[Precision](1, Nil)) _

    // Ranking methods:

    def rankStandard(list: List[Score]) =
        grouped[Int](list){case (state, names) => state.next(state.n+names.length, Rank(state.n, names))}.done.reverse

    def rankModified(list: List[Score]) =
        rankStandard(list).map(r => Rank(r.rank+r.names.length-1, r.names))

    def rankDense(list: List[Score]) =
        grouped[Int](list){case (state, names) => state.next(state.n+1, Rank(state.n, names))}.done.reverse

    def rankOrdinal(list: List[Score]) =
        list.zipWithIndex.map{case (score, n) => Rank(n+1, List(score.name))}

    def rankFractional(list: List[Score]) =
        rankStandard(list).map(r => Rank((2*r.rank+r.names.length-1.0)/2, r.names))

    // Tests:

    def parseScores(s: String) = s split "\\s+" match {case Array(s,n) => Score(s.toInt, n)}
    val test = List("44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen").map(parseScores)

    println("Standard:")
    println(rankStandard(test) mkString "\n")
    println("\nModified:")
    println(rankModified(test) mkString "\n")
    println("\nDense:")
    println(rankDense(test) mkString "\n")
    println("\nOrdinal:")
    println(rankOrdinal(test) mkString "\n")
    println("\nFractional:")
    println(rankFractional(test) mkString "\n")

}

The code implements various ranking methods for a competition, including Standard, Modified, Dense, Ordinal, and Fractional. It assigns numerical ranks to competitors based on their scores, handling ties differently for each method. The ranking is applied to an ordered list of scores with scorers. The code uses a type-safe singly-linked object model with no mutable state variables, demonstrating an object-oriented functional programming approach.


Library: Scalaimport scala.math._

object Gonio extends App {
  //Pi / 4 rad is 45 degrees. All answers should be the same.
  val radians = Pi / 4
  val degrees = 45.0

  println(s"${sin(radians)} ${sin(toRadians(degrees))}")
  //cosine
  println(s"${cos(radians)} ${cos(toRadians(degrees))}")
  //tangent
  println(s"${tan(radians)} ${tan(toRadians(degrees))}")
  //arcsine
  val bgsin = asin(sin(radians))
  println(s"$bgsin ${toDegrees(bgsin)}")
  val bgcos = acos(cos(radians))
  println(s"$bgcos ${toDegrees(bgcos)}")
  //arctangent
  val bgtan = atan(tan(radians))
  println(s"$bgtan ${toDegrees(bgtan)}")
  val bgtan2 = atan2(1, 1)
  println(s"$bgtan ${toDegrees(bgtan)}")
}

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


Library: Scala
import sun.misc.Signal
import sun.misc.SignalHandler

object SignalHandl extends App {
  val start = System.nanoTime()
  var counter = 0

  Signal.handle(new Signal("INT"), new SignalHandler() {
    def handle(sig: Signal) {
      println(f"\nProgram execution took ${(System.nanoTime() - start) / 1e9f}%f seconds\n")
      exit(0)
    }
  })

  while (true) {
    counter += 1
    println(counter)
    Thread.sleep(500)
  }
}

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.


implicit def toSucc(s: String) = new { def succ = BigDecimal(s) + 1 toString }

scala> "123".succ
res5: String = 124

Code summarization: The following codes define a method to increment a numerical string by converting it to a BigDecimal numeric type.


object FindCommonDirectoryPath extends App {
  def commonPath(paths: List[String]): String = {
    def common(a: List[String], b: List[String]): List[String] = (a, b) match {
      case (a :: as, b :: bs) if a equals b => a :: common(as, bs)
      case _ => Nil
    }
    if (paths.length < 2) paths.headOption.getOrElse("")
    else paths.map(_.split("/").toList).reduceLeft(common).mkString("/")
  }

  val test = List(
    "/home/user1/tmp/coverage/test",
    "/home/user1/tmp/covert/operator",
    "/home/user1/tmp/coven/members"
  )
  println(commonPath(test))
}

/home/user1/tmp

object FindCommonDirectoryPathRelative extends App {
  def commonPath(paths: List[String]): String = {
    val SEP = "/"
    val BOUNDARY_REGEX = s"(?=[$SEP])(?<=[^$SEP])|(?=[^$SEP])(?<=[$SEP])"
    def common(a: List[String], b: List[String]): List[String] = (a, b) match {
      case (a :: as, b :: bs) if a equals b => a :: common(as, bs)
      case _ => Nil
    }
    if (paths.length < 2) paths.headOption.getOrElse("")
    else paths.map(_.split(BOUNDARY_REGEX).toList).reduceLeft(common).mkString
  }

  val test = List(
    "/home/user1/tmp/coverage/test",
    "/home/user1/tmp/covert/operator",
    "/home/user1/tmp/coven/members"
  )
  println(commonPath(test).replaceAll("/$", ""))

  // test cases
  assert(commonPath(test.take(1)) == test.head)
  assert(commonPath(Nil) == "")
  assert(commonPath(List("")) == "")
  assert(commonPath(List("/")) == "/")
  assert(commonPath(List("/", "")) == "")
  assert(commonPath(List("/", "/a")) == "/")
  assert(commonPath(List("/a", "/b")) == "/")
  assert(commonPath(List("/a", "/a")) == "/a")
  assert(commonPath(List("/a/a", "/b")) == "/")
  assert(commonPath(List("/a/a", "/b")) == "/")
  assert(commonPath(List("/a/a", "/a")) == "/a")
  assert(commonPath(List("/a/a", "/a/b")) == "/a/")
  assert(commonPath(List("/a/b", "/a/b")) == "/a/b")
  assert(commonPath(List("a", "/a")) == "")
  assert(commonPath(List("a/a", "/a")) == "")
  assert(commonPath(List("a/a", "/b")) == "")
  assert(commonPath(List("a", "a")) == "a")
  assert(commonPath(List("a/a", "b")) == "")
  assert(commonPath(List("a/a", "b")) == "")
  assert(commonPath(List("a/a", "a")) == "a")
  assert(commonPath(List("a/a", "a/b")) == "a/")
  assert(commonPath(List("a/b", "a/b")) == "a/b")
  assert(commonPath(List("/a/", "/b/")) == "/")
  assert(commonPath(List("/a/", "/a/")) == "/a/")
  assert(commonPath(List("/a/a/", "/b/")) == "/")
  assert(commonPath(List("/a/a/", "/b/")) == "/")
  assert(commonPath(List("/a/a/", "/a/")) == "/a/")
  assert(commonPath(List("/a/a/", "/a/b/")) == "/a/")
  assert(commonPath(List("/a/b/", "/a/b/")) == "/a/b/")
}

The code creates a function that takes a set of directory paths and a directory separator as inputs. It then returns the common directory path among all provided directories. The function is tested using '/' as the directory separator and three specific strings as input paths. The function is designed to handle various edge cases and relative paths, and includes any common trailing '/'. If the language used already has a function that performs this task, it is mentioned as part of the task.


def shuffle[T](a: Array[T]): Array[T] = {
  scala.util.Random.shuffle(a)
  a
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


Works with: Scala version 2.8 (See the Scala discussion on Mean for more information.)
def median[T](s: Seq[T])(implicit n: Fractional[T]) = {
  import n._
  val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2)
  if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head
}

The code calculates the median value of a vector of floating-point numbers. It handles even numbers of elements by returning the average of the two middle values. It uses the selection algorithm for optimal performance. Additionally, the code calculates various statistical measures like arithmetic, geometric, harmonic, quadratic, and circular averages, as well as mode and standard deviation. However, the methods splitAt and last may not be optimal due to their time complexity.


Library: Scala
object FizzBuzz extends App {
  1 to 100 foreach { n =>
    println((n % 3, n % 5) match {
      case (0, 0) => "FizzBuzz"
      case (0, _) => "Fizz"
      case (_, 0) => "Buzz"
      case _ => n
    })
  }
}
def replaceMultiples(x: Int, rs: (Int, String)*): Either[Int, String] =
  rs map { case (n, s) => Either cond(x % n == 0, s, x)} reduceLeft ((a, b) =>
    a fold(_ => b, s => b fold(_ => a, t => Right(s + t))))

def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity)

1 to 100 map fizzbuzz foreach println
def f(n: Int, div: Int, met: String, notMet: String): String = if (n % div == 0) met else notMet
for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))
for (i <- 1 to 100) println(Seq(15 -> "FizzBuzz", 3 -> "Fizz", 5 -> "Buzz").find(i % _._1 == 0).map(_._2).getOrElse(i))
def fizzBuzzTerm(n: Int): String =
  if (n % 15 == 0) "FizzBuzz"
  else if (n % 3 == 0) "Fizz"
  else if (n % 5 == 0) "Buzz"
  else n.toString

def fizzBuzz(): Unit = LazyList.from(1).take(100).map(fizzBuzzTerm).foreach(println)

def fizzBuzzTerm(n: Int): String | Int = // union types
  (n % 3, n % 5) match // optional semantic indentation; no braces
    case (0, 0) => "FizzBuzz"
    case (0, _) => "Fizz"
    case (_, 0) => "Buzz"
    case _      => n // no need for `.toString`, thanks to union type
  end match // optional `end` keyword, with what it's ending
end fizzBuzzTerm // `end` also usable for identifiers

val fizzBuzz = // no namespace object is required; all top level
  LazyList.from(1).map(fizzBuzzTerm)

@main def run(): Unit = // @main for main method; can take custom args
  fizzBuzz.take(100).foreach(println)

The code prints integers from 1 to 100. It replaces multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


Works with: Scala version 2.8

import org.rosettacode.ArithmeticComplex._
import java.awt.Color

object Mandelbrot
{
   def generate(width:Int =600, height:Int =400)={
      val bm=new RgbBitmap(width, height)

      val maxIter=1000
      val xMin = -2.0
      val xMax =  1.0
      val yMin = -1.0
      val yMax =  1.0

      val cx=(xMax-xMin)/width
      val cy=(yMax-yMin)/height

      for(y <- 0 until bm.height; x <- 0 until bm.width){
         val c=Complex(xMin+x*cx, yMin+y*cy)
         val iter=itMandel(c, maxIter, 4)
         bm.setPixel(x, y, getColor(iter, maxIter))
      }
      bm
   }

   def itMandel(c:Complex, imax:Int, bailout:Int):Int={
      var z=Complex()
      for(i <- 0 until imax){
         z=z*z+c;
         if(z.abs > bailout) return i
      }
      imax;
   }

   def getColor(iter:Int, max:Int):Color={
      if (iter==max) return Color.BLACK

      var c=3*math.log(iter)/math.log(max-1.0)
      if(c<1) new Color((255*c).toInt, 0, 0)
      else if(c<2) new Color(255, (255*(c-1)).toInt, 0)
      else new Color(255, 255, (255*(c-2)).toInt)
   }
}

import scala.swing._
import javax.swing.ImageIcon
val imgMandel=Mandelbrot.generate()
val mainframe=new MainFrame(){title="Test"; visible=true
   contents=new Label(){icon=new ImageIcon(imgMandel.image)}
}

generate and draw the Mandelbrot set using various algorithms and functions. It utilizes the RgbBitmap from the Basic Bitmap Storage task and the Complex number class from the given programming task. The code also includes a read-eval-print loop.


val seq = Seq(1, 2, 3, 4, 5)
val sum = seq.foldLeft(0)(_ + _)
val product = seq.foldLeft(1)(_ * _)

val sum = seq.sum
val product = seq.product

Computes the sum and product of an array of integers, compatible with all numeric data types.


//use Java's calendar class
new java.util.GregorianCalendar().isLeapYear(year)

java.time.LocalDate.ofYearDay(year, 1).isLeapYear()

def isLeapYear(year:Int)=if (year%100==0) year%400==0 else year%4==0;

//or use Java's calendar class
def isLeapYear(year:Int):Boolean = {
  val c = new java.util.GregorianCalendar
  c.setGregorianChange(new java.util.Date(Long.MinValue))
  c.isLeapYear(year)
}

determine if a given year is a leap year in the Gregorian calendar, considering the switch from Julian to Gregorian calendar on October 15, 1582, using java.util.GregorianCalendar and JSR-310 java.time for proleptic Gregorian calendar.


This example is incorrect. It does not accomplish the given task. Please fix the code and remove this message.

object MD5 extends App {

  def hash(s: String) = {
    def b = s.getBytes("UTF-8")

    def m = java.security.MessageDigest.getInstance("MD5").digest(b)

    BigInt(1, m).toString(16).reverse.padTo(32, "0").reverse.mkString
  }

  assert("d41d8cd98f00b204e9800998ecf8427e" == hash(""))
  assert("0000045c5e2b3911eb937d9d8c574f09" == hash("iwrupvqb346386"))
  assert("0cc175b9c0f1b6a831c399e269772661" == hash("a"))
  assert("900150983cd24fb0d6963f7d28e17f72" == hash("abc"))
  assert("f96b697d7cb7938d525a2f31aaf161d0" == hash("message digest"))
  assert("c3fcd3d76192e4007dfb496cca67e13b" == hash("abcdefghijklmnopqrstuvwxyz"))
  assert("d174ab98d277d9f5a5611c2c9f419d9f" == hash("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
  assert("57edf4a22be3c955ac49da2e2107b67a" == hash("12345678901234567890123456789012345678901234567890123456789012345678901234567890"))

}

The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.


val depts = {
  (1 to 7).permutations.map{ n => (n(0),n(1),n(2)) }.toList.distinct  // All permutations of possible department numbers
  .filter{ n => n._1 % 2 == 0 }                                       // Keep only even numbers favored by Police Chief
  .filter{ n => n._1 + n._2 + n._3 == 12 }                            // Keep only numbers that add to 12
}

{
println( "(Police, Sanitation, Fire)")
println( depts.mkString("\n") )
}

all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.


  val src = "Hello"
  // Its actually not a copy but a reference
  // That is not a problem because String is immutable
  // In fact its a feature
  val des = src
  assert(src eq des) // Proves the same reference is used.
  // To make a real copy makes no sense.
  // Actually its hard to make a copy, the compiler is too smart.
  // mkString, toString makes also not a real copy
  val cop = src.mkString.toString
  assert((src eq cop))                 // Still no copyed image
  val copy = src.reverse.reverse       // Finally double reverse makes a copy
  assert(src == copy && !(src eq copy))// Prove, but it really makes no sense.

"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable."


def F(n:Int):Int =
  if (n == 0) 1 else n - M(F(n-1))
def M(n:Int):Int =
  if (n == 0) 0 else n - F(M(n-1))

println((0 until 20).map(F).mkString(", "))
println((0 until 20).map(M).mkString(", "))

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.


Library: Scala
val a = (1 to 10).toList

println(scala.util.Random.shuffle(a).head)

demonstrate how to select a random element from a list.


Library: Scalaimport java.net.{URLDecoder, URLEncoder}
import scala.compat.Platform.currentTime

object UrlCoded extends App {
  val original = """http://foo bar/"""
  val encoded: String = URLEncoder.encode(original, "UTF-8")

  assert(encoded == "http%3A%2F%2Ffoo+bar%2F", s"Original: $original not properly encoded: $encoded")

  val percentEncoding = encoded.replace("+", "%20")
  assert(percentEncoding == "http%3A%2F%2Ffoo%20bar%2F", s"Original: $original not properly percent-encoded: $percentEncoding")

  assert(URLDecoder.decode(encoded, "UTF-8") == URLDecoder.decode(percentEncoding, "UTF-8"))

  println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}

provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {
  def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match {
    case _ if high < low => None
    case mid if a(mid) > v => recurse(low, mid - 1)
    case mid if a(mid) < v => recurse(mid + 1, high)
    case mid => Some(mid)
  }
  recurse(0, a.size - 1)
}

def binarySearch[T](xs: Seq[T], x: T)(implicit ordering: Ordering[T]): Option[Int] = {
    var low: Int = 0
    var high: Int = xs.size - 1

    while (low <= high)
      low + high >>> 1 match {
        case guess if ordering.gt(xs(guess), x) => high = guess - 1 //too high
        case guess if ordering.lt(xs(guess), x) => low = guess + 1 // too low
        case guess => return Some(guess) //found it
      }
    None //not found
  }

def testBinarySearch(n: Int) = {
  val odds = 1 to n by 2
  val result = (0 to n).flatMap(binarySearch(odds, _))
  assert(result == (0 until odds.size))
  println(s"$odds are odd natural numbers")
  for (it <- result)
    println(s"$it is ordinal of ${odds(it)}")
}

def main() = testBinarySearch(12)

Range(1, 3, 5, 7, 9, 11) are odd natural numbers
0 is ordinal of 1
1 is ordinal of 3
2 is ordinal of 5
3 is ordinal of 7
4 is ordinal of 9
5 is ordinal of 11

The code implements a binary search algorithm to find a specific number in a sorted integer array. It divides the range of values into halves until the target number is found. The code includes both recursive and iterative versions of the binary search. It also handles scenarios where multiple values in the array are equal to the target value. The code provides the index of the target number if it is found, or the index where it would be inserted while maintaining the sorted order of the array if it is not found. The code also ensures there are no overflow bugs during the calculation of the midpoint.


Library: Scala

object CommandLineArguments extends App {
    println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}")
}

println(s"Received the following arguments: + ${argv.mkString("", ", ", ".")}")

The code retrieves the list of command-line arguments provided to the program. It specifically prints these arguments when the program is run directly. It uses a main method defined on an object, which receives an array of strings (command line arguments) and returns unit. In the case of a Scala script, the arguments are stored in an array of strings called argv. The example command line used is: myprogram -c "alpha beta" -h "gamma".


Library: Scala
import java.awt.Color
import java.util.concurrent.{Executors, TimeUnit}

import scala.swing.{Graphics2D, MainFrame, Panel, SimpleSwingApplication}
import scala.swing.Swing.pair2Dimension

object Pendulum extends SimpleSwingApplication {
  val length = 100

  lazy val ui = new Panel {
    import scala.math.{cos, Pi, sin}

    background = Color.white
    preferredSize = (2 * length + 50, length / 2 * 3)
    peer.setDoubleBuffered(true)

    var angle: Double = Pi / 2

    override def paintComponent(g: Graphics2D): Unit = {
      super.paintComponent(g)

      val (anchorX, anchorY) = (size.width / 2, size.height / 4)
      val (ballX, ballY) =
        (anchorX + (sin(angle) * length).toInt, anchorY + (cos(angle) * length).toInt)
      g.setColor(Color.lightGray)
      g.drawLine(anchorX - 2 * length, anchorY, anchorX + 2 * length, anchorY)
      g.setColor(Color.black)
      g.drawLine(anchorX, anchorY, ballX, ballY)
      g.fillOval(anchorX - 3, anchorY - 4, 7, 7)
      g.drawOval(ballX - 7, ballY - 7, 14, 14)
      g.setColor(Color.yellow)
      g.fillOval(ballX - 7, ballY - 7, 14, 14)
    }

    val animate: Runnable = new Runnable {
      var angleVelocity = 0.0
      var dt = 0.1

      override def run(): Unit = {
        angleVelocity += -9.81 / length * Math.sin(angle) * dt
        angle += angleVelocity * dt
        repaint()
      }
    }
  }

  override def top = new MainFrame {
    title = "Rosetta Code >>> Task: Animate a pendulum | Language: Scala"
    contents = ui
    centerOnScreen()
    Executors.
      newSingleThreadScheduledExecutor().
      scheduleAtFixedRate(ui.animate, 0, 15, TimeUnit.MILLISECONDS)
  }
}

create and animate a simple physical model of a gravity pendulum.


scala> import scala.util.parsing.json.{JSON, JSONObject}
import scala.util.parsing.json.{JSON, JSONObject}

scala> JSON.parseFull("""{"foo": "bar"}""")
res0: Option[Any] = Some(Map(foo -> bar))

scala> JSONObject(Map("foo" -> "bar")).toString()
res1: String = {"foo" : "bar"}

"Code loads a JSON string into a data structure, creates a new data structure and serializes it into JSON using built-in parsing library. It ensures the JSON is valid and uses objects and arrays as per the language's suitability."


def nroot(n: Int, a: Double): Double = {
  @tailrec
  def rec(x0: Double) : Double = {
    val x1 = ((n - 1) * x0 + a/math.pow(x0, n-1))/n
    if (x0 <= x1) x0 else rec(x1)
  }

  rec(a)
}

def fallPrefix(itr: Iterator[Double]): Iterator[Double] = itr.sliding(2).dropWhile(p => p(0) > p(1)).map(_.head)
def nrootLazy(n: Int)(a: Double): Double = fallPrefix(Iterator.iterate(a){r => (((n - 1)*r) + (a/math.pow(r, n - 1)))/n}).next

implement the principal nth root computation algorithm for a positive real number A, using tail recursion or an iterator.


"Determines and outputs the hostname of the current system where the routine is running."


def leo( n:Int, n1:Int=1, n2:Int=1, addnum:Int=1 ) : BigInt = n match {
  case 0 => n1
  case 1 => n2
  case n => leo(n - 1, n1, n2, addnum) + leo(n - 2, n1, n2, addnum) + addnum
}

{
println( "The first 25 Leonardo Numbers:")
(0 until 25) foreach { n => print( leo(n) + " " ) }

println( "\n\nThe first 25 Fibonacci Numbers:")
(0 until 25) foreach { n => print( leo(n, n1=0, n2=1, addnum=0) + " " ) }
}

generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.


object TwentyFourGame {
  def main(args: Array[String]) {
    import Parser.TwentyFourParser

    println(welcome)

    var parser = new TwentyFourParser(problemsIterator.next)
    println("Your four digits: "+parser+".")

    var finished = false
    var expressionCount = 1
    do {
      val line = Console.readLine("Expression "+expressionCount+": ")
      line match {
        case "!" =>
          parser = new TwentyFourParser(problemsIterator.next)
          println("New digits: "+parser+".")

        case "q" =>
          finished = true

        case _ =>
          parser readExpression line match {
            case Some(24) => println("That's right!"); finished = true
            case Some(n) => println("Sorry, that's "+n+".")
            case None =>
          }
      }
      expressionCount += 1
    } while (!finished)

    println("Thank you and goodbye!")
  }

  val welcome = """|The 24 Game
                   |
                   |Given any four digits in the range 1 to 9, which may have repetitions,
                   |Using just the +, -, *, and / operators; and the possible use of
                   |brackets, (), show how to make an answer of 24.
                   |
                   |An answer of "q" will quit the game.
                   |An answer of "!" will generate a new set of four digits.
                   |Otherwise you are repeatedly asked for an expression until it evaluates to 24
                   |
                   |Note: you cannot form multiple digit numbers from the supplied digits,
                   |so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.
                   |""".stripMargin

  val problemsIterator = (
    Iterator
    continually List.fill(4)(scala.util.Random.nextInt(9) + 1 toDouble)
    filter hasSolution
  )

  def hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations exists (_ == 24)

  def computeAllOperations(l: List[Double]): List[Double] = l match {
    case Nil => Nil
    case x :: Nil => l
    case x :: xs =>
      for {
        y <- computeAllOperations(xs)
        z <- if (y == 0) List(x*y, x+y, x-y) else List(x*y, x/y, x+y, x-y)
      } yield z
  }

  def permute(l: List[Double]): List[List[Double]] = l match {
    case Nil => List(Nil)
    case x :: xs =>
      for {
        ys <- permute(xs)
        position <- 0 to ys.length
        (left, right) = ys splitAt position
      } yield left ::: (x :: right)
  }

  object Parser {
    /*  Arithmetic expression grammar production rules in EBNF form:
     *
     * <expr> --> <term> ( '+' <term> | '-' <term> )*
     * <term> --> <factor> ( '*'  <factor> | '/'  <factor> )*
     * <factor> --> '(' <expr> ')' | <digit>
     * <digit> --> 0 | 1  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
     *
     * Semantically, <digit> can only be a digit from the list of remaining digits.
     */

    class TwentyFourParser(digits: List[Double]) extends scala.util.parsing.combinator.RegexParsers {
      require(digits.length == 4 && digits.forall(d => 0 <= d && d <= 9))
      override val toString = digits.map(_.toInt).mkString(", ")

      // Grammar
      def exprConsumingAllDigits = expr ^? (remainingDigits.allDigitsConsumed, digitsRemainingError) // Guarantees all digits consumed
      def expr : Parser[Double] = term ~ rep( "+" ~ term | "-" ~ term) ^^ solveOperationChain
      def term = factor ~ rep( "*" ~ factor | "/" ~ factor) ^^ solveOperationChain
      def factor = "(" ~> expr <~ ")" | digit
      def digit = digitRegex ^? (remainingDigits.consumeDigit, digitNotAllowedError)
      def digitRegex = "\\d".r | digitExpected
      def digitExpected: Parser[String] = ".".r <~ failure(expectedDigitError) // Produces clear error messages

      // Evaluate expressions
      def readExpression(input: String): Option[Double] = {
        remainingDigits = new DigitList(digits) // Initialize list of digits to be consumed
        parseAll(exprConsumingAllDigits, input) match {
          case Success(result, _) => Some(result)
          case NoSuccess(msg, next) =>
            println(ParsingErrorFormatter(msg, next))
            None
        }
      }

      // List of digits to be consumed
      private var remainingDigits: DigitList = _

      // Solve partial results from parsing
      private def solveOperationChain(partialResult: ~[Double,List[~[String,Double]]]): Double = partialResult match {
        case first ~ chain => chain.foldLeft(first)(doOperation)
      }
      private def doOperation(acc: Double, op: ~[String, Double]): Double = op match {
        case "+" ~ operand => acc + operand
        case "-" ~ operand => acc - operand
        case "*" ~ operand => acc * operand
        case "/" ~ operand => acc / operand
        case x => error("Unknown operation "+x+".")
      }

      // Error messages
      private def digitNotAllowedError(d: String) = "Digit "+d+" is not allowed here. Available digits: "+remainingDigits+"."
      private def digitsRemainingError(x: Any) = "Not all digits were consumed. Digits remaining: "+remainingDigits+"."
      private def expectedDigitError = "Unexpected input. Expected a digit from the list: "+remainingDigits+"."
    }

    private object ParsingErrorFormatter {
      def apply[T](msg: String, next: scala.util.parsing.input.Reader[T]) =
        "%s\n%s\n%s\n" format (msg, next.source.toString.trim, " "*(next.offset - 1)+"^")
    }

    private class DigitList(digits: List[Double]) {
      private var remainingDigits = digits
      override def toString = remainingDigits.map(_.toInt).mkString(", ")

      def consumeDigit: PartialFunction[String, Double] = {
        case d if remainingDigits contains d.toDouble =>
          val n = d.toDouble
          remainingDigits = remainingDigits diff List(n)
          n
      }

      def allDigitsConsumed: PartialFunction[Double, Double] = {
        case n if remainingDigits.isEmpty => n
      }
    }
  }
}

The code randomly selects and displays four digits from 1 to 9, allows the player to input an arithmetic expression using these digits exactly once each, and checks if the expression evaluates to 24. The code supports operations of addition, subtraction, multiplication, and division with floating point or rational arithmetic. The code also allows the use of brackets in the expression but does not permit forming multiple digit numbers from the given digits. The order of the digits does not need to be preserved in the expression. The code does not generate or test the expression. It uses Scala's Parser library to construct parsers from EBNF grammars and displays only the problems with the solution to the user.


def encode(s: String) = (1 until s.size).foldLeft((1, s(0), new StringBuilder)) {
  case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb)
  case ((len, c, sb), _) => (len + 1, c, sb)
} match {
  case (len, c, sb) => sb.append(len); sb.append(c); sb.toString
}

def decode(s: String) = {
  val sb = new StringBuilder
  val Code = """(\d+)([A-Z])""".r
  for (Code(len, c) <- Code findAllIn s) sb.append(c * len.toInt)
  sb.toString
}

def encode(s:String) = {
  s.foldLeft((0,s(0),""))( (t,c) => t match {case (i,p,s) => if (p==c) (i+1,p,s) else (1,c,s+i+p)})
    match {case (i,p,s) => s+i+p}
}

def decode(s: String, Code: scala.util.matching.Regex = """(\d+)?([a-zA-Z])""".r) =
  Code.findAllIn(s).foldLeft("") { case (acc, Code(len, c)) =>
    acc + c * Option(len).map(_.toInt).getOrElse(1)
  }

The code implements run-length encoding and decoding for a string of uppercase characters. It compresses repeated characters by storing the length of the run. It also provides a function to reverse the compression. The code uses StringBuilder for better performance. It can handle strings like "2AB", producing "AAB".


  val s = "hello"                                 //> s  : String = hello
  val s2 = s + " world"                           //> s2  : String = hello world
  val f2 = () =>  " !"                            //> f2  : () => String = <function0>

  println(s2 + f2())                              //> hello world !

The code creates two string variables, one with a text value and another that concatenates the first variable with a string literal. The content of these variables is then displayed. Additionally, an anonymous function is assigned to the variable 'f2' in a Scala worksheet.


import scala.annotation.tailrec

object ContinousKnapsackForRobber extends App {
  val MaxWeight = 15.0
  val items = Seq(
    Item("Beef",    3.8, 3600),
    Item("Pork",    5.4, 4300),
    Item("Ham",     3.6, 9000),
    Item("Greaves", 2.4, 4500),
    Item("Flitch",  4.0, 3000),
    Item("Brawn",   2.5, 5600),
    Item("Welt",    3.7, 6700),
    Item("Salami",  3.0, 9500),
    Item("Sausage", 5.9, 9800))

  // sort items by value per unit weight in descending order
  def sortedItems = items.sortBy(it => -it.value / it.weight)

  @tailrec
  def packer(notPacked: Seq[Item], packed: Lootsack): Lootsack = {

    if (!packed.isNotFull || notPacked.isEmpty) packed
    else {
      val try2fit = packed.copy(bagged = notPacked.head +: packed.bagged)
      if (try2fit.isNotFull) packer(notPacked.tail, try2fit)
      else {
        try2fit.copy(lastPiece = packed.weightLeft / notPacked.head.weight)
      }
    }
  }

  case class Item(name: String, weight: Double, value: Int)

  case class Lootsack(bagged: Seq[Item], lastPiece: Double = 1.0) {
    private val totWeight = if (bagged.isEmpty) 0.0
    else bagged.tail.map(_.weight).sum + bagged.head.weight * lastPiece

    def isNotFull: Boolean = weightLeft > 0

    def weightLeft: Double = MaxWeight - totWeight

    override def toString = f"${show(bagged, lastPiece)}Totals: weight: $totWeight%4.1f, value: $totValue%6.2f"

    private def totValue: BigDecimal = if (bagged.isEmpty) 0.0
    else (bagged.tail.map(_.value).sum + bagged.head.value * lastPiece) / 100

    private def show(is: Seq[Item], percentage: Double) = {
      def toStr(is: Seq[Item], percentage: Double = 1): String =
        is.map(it => f"${percentage * 100}%6.2f%% ${it.name}%-7s ${
          it.weight * percentage}%4.1f ${it.value * percentage / 100}%6.2f\n").mkString

      toStr(is.tail.reverse) + toStr(Seq(is.head), percentage)
    }
  }

  println(packer(sortedItems, Lootsack(Nil)))
}

determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.


val src = io.Source fromURL "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"
val vls = src.getLines.toList.groupBy(_.sorted).values
val max = vls.map(_.size).max
vls filter (_.size == max) map (_ mkString " ") mkString "\n"

"Find the largest sets of anagrams from the word list provided at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt."


def nextCarpet(carpet: List[String]): List[String] = (
  carpet.map(x => x + x + x) :::
  carpet.map(x => x + x.replace('#', ' ') + x) :::
  carpet.map(x => x + x + x))

def sierpinskiCarpets(n: Int) = (Iterator.iterate(List("#"))(nextCarpet) drop n next) foreach println

generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.


Works with: scala version 2.8
object Huffman {
  import scala.collection.mutable.{Map, PriorityQueue}

  sealed abstract class Tree
  case class Node(left: Tree, right: Tree) extends Tree
  case class Leaf(c: Char) extends Tree

  def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] {
     def compare(x: Tree, y: Tree) = m(y).compare(m(x))
  }

  def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length)

  def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) {
    val right = queue.dequeue
    val left = queue.dequeue
    val node = Node(left, right)
    map(node) = map(left) + map(right)
    queue.enqueue(node)
  }

  def codify(tree: Tree, map: Map[Tree, Int]) = {
    def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match {
      case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1")
      case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil
    }
    recurse(tree, "")
  }

  def encode(text: String) = {
    val map = Map.empty[Tree,Int] ++= stringMap(text)
    val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator

    while(queue.size > 1) {
      buildNode(queue, map)
    }
    codify(queue.dequeue, map)
  }

  def main(args: Array[String]) {
    val text = "this is an example for huffman encoding"
    val code = encode(text)
    println("Char\tWeight\t\tEncoding")
    code sortBy (_._2._1) foreach {
      case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding))
    }
  }
}

The code generates a Huffman encoding for each character in the given string "this is an example for huffman encoding". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.


Library: Scala
import scala.swing.{ BorderPanel, Button, Label, MainFrame, SimpleSwingApplication }
import scala.swing.event.ButtonClicked

object SimpleApp extends SimpleSwingApplication {
  def top = new MainFrame {
    contents = new BorderPanel {
      var nClicks = 0

      val (button, label) = (new Button { text = "click me" },
        new Label { text = "There have been no clicks yet" })

      layout(button) = BorderPanel.Position.South
      layout(label) = BorderPanel.Position.Center
      listenTo(button)
      reactions += {
        case ButtonClicked(_) =>
          nClicks += 1
          label.text = s"There have been ${nClicks} clicks"
      }
    }
  }
}

"Creates a windowed application with a label and a button. The label initially displays 'There have been no clicks yet'. The button is labeled 'click me'. On each button click, the label updates to show the total number of button clicks."


for(i <- 10 to 0 by -1) println(i)
//or
10 to 0 by -1 foreach println

The code performs a countdown from 10 to 0 using a downward for loop.


object Vigenere {
  def encrypt(msg: String, key: String) : String = {
    var result: String = ""
    var j = 0

    for (i <- 0 to msg.length - 1) {
      val c = msg.charAt(i)
      if (c >= 'A' && c <= 'Z') {
        result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar
        j = (j + 1) % key.length
      }
    }

    return result
  }

  def decrypt(msg: String, key: String) : String = {
    var result: String = ""
    var j = 0

    for (i <- 0 to msg.length - 1) {
      val c = msg.charAt(i)
      if (c >= 'A' && c <= 'Z') {
        result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar
        j = (j + 1) % key.length
      }
    }

    return result
  }
}

println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY"))
println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY"))

Implement the Vigenère cipher for both encryption and decryption. It handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. It accepts valid characters from A to Z, 0 to 9, and a full-stop (.).


for (i <- 2 to 8 by 2) println(i)

(2 to 8 by 2) foreach println

demonstrate a for-loop with a step-value greater than one.


class MyInt { var i: Int = _ }
val i = new MyInt
def sum(i: MyInt, lo: Int, hi: Int, term: => Double) = {
  var temp = 0.0
  i.i = lo
  while(i.i <= hi) {
    temp = temp + term
    i.i += 1
  }
  temp
}
sum(i, 1, 100, 1.0 / i.i)

res2: Double = 5.187377517639621

The code is an implementation of Jensen's Device, a programming technique that uses call by name. It calculates the 100th harmonic number using a sum procedure. The sum procedure takes four parameters: an integer, two range values, and a term. The term and integer are passed by name, allowing their values to be re-evaluated in the caller's context each time they are required. The code also demonstrates the importance of passing the first parameter by name or reference, to ensure changes made within the sum procedure are visible in the caller's context. A mutable integer class is used to simulate passing by reference in Scala.


Library: org.scala-lang.modules scala-swing
import scala.swing.Swing.pair2Dimension
import scala.swing.{Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication}

object XorPattern extends SimpleSwingApplication {

  def top = new MainFrame {
    preferredSize = (300, 300)
    title = "Rosetta Code >>> Task: Munching squares | Language: Scala"
    contents = new Panel {

      protected override def paintComponent(g: Graphics2D) = {
        super.paintComponent(g)
        for {
          y <- 0 until size.getHeight.toInt
          x <- 0 until size.getWidth.toInt
        } {
          g.setColor(new Color(0, (x ^ y) % 256, 0))
          g.drawLine(x, y, x, y)
        }
      }
    }

    centerOnScreen()
  }
}

generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.


import scala.util.Random

object MazeTypes {
  case class Direction(val dx: Int, val dy: Int)

  case class Loc(val x: Int, val y: Int) {
    def +(that: Direction): Loc = Loc(x + that.dx, y + that.dy)
  }

  case class Door(val from: Loc, to: Loc)

  val North = Direction(0,-1)
  val South = Direction(0,1)
  val West = Direction(-1,0)
  val East = Direction(1,0)
  val directions = Set(North, South, West, East)
}

object MazeBuilder {
  import MazeTypes._

  def shuffle[T](set: Set[T]): List[T] = Random.shuffle(set.toList)

  def buildImpl(current: Loc, grid: Grid): Grid = {
    var newgrid = grid.markVisited(current)
    val nbors = shuffle(grid.neighbors(current))
    nbors.foreach { n =>
      if (!newgrid.isVisited(n)) {
        newgrid = buildImpl(n, newgrid.markVisited(current).addDoor(Door(current, n)))
      }
    }
    newgrid
  }

  def build(width: Int, height: Int): Grid = {
    val exit = Loc(width-1, height-1)
    buildImpl(exit, new Grid(width, height, Set(), Set()))
  }
}

class Grid(val width: Int, val height: Int, val doors: Set[Door], val visited: Set[Loc]) {

  def addDoor(door: Door): Grid =
    new Grid(width, height, doors + door, visited)

  def markVisited(loc: Loc): Grid =
    new Grid(width, height, doors, visited + loc)

  def isVisited(loc: Loc): Boolean =
    visited.contains(loc)

  def neighbors(current: Loc): Set[Loc] =
    directions.map(current + _).filter(inBounds(_)) -- visited

  def printGrid(): List[String] = {
    (0 to height).toList.flatMap(y => printRow(y))
  }

  private def inBounds(loc: Loc): Boolean =
    loc.x >= 0 && loc.x < width && loc.y >= 0 && loc.y < height

  private def printRow(y: Int): List[String] = {
    val row = (0 until width).toList.map(x => printCell(Loc(x, y)))
    val rightSide = if (y == height-1) " " else "|"
    val newRow = row :+ List("+", rightSide)
    List.transpose(newRow).map(_.mkString)
  }

  private val entrance = Loc(0,0)

  private def printCell(loc: Loc): List[String] = {
    if (loc.y == height)
      List("+--")
    else List(
      if (openNorth(loc)) "+  " else "+--",
      if (openWest(loc) || loc == entrance) "   " else "|  "
    )
  }

  def openNorth(loc: Loc): Boolean = openInDirection(loc, North)

  def openWest(loc: Loc): Boolean = openInDirection(loc, West)

  private def openInDirection(loc: Loc, dir: Direction): Boolean =
    doors.contains(Door(loc, loc + dir)) || doors.contains(Door(loc + dir, loc))
}

generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.


continuously calculate and display the next decimal digit of Pi until the program is manually terminated by the user. The sequence begins with 3.14159265.


def lessThan1(a: List[Int], b: List[Int]): Boolean =
  if (b.isEmpty) false
  else if (a.isEmpty) true
  else if (a.head != b.head) a.head < b.head
  else lessThan1(a.tail, b.tail)
def lessThan2(a: List[Int], b: List[Int]): Boolean = (a, b) match {
  case (_, Nil) => false
  case (Nil, _) => true
  case (a :: _, b :: _) if a != b => a < b
  case _ => lessThan2(a.tail, b.tail)
}
def lessThan3(a: List[Int], b: List[Int]): Boolean =
  a.zipAll(b, Integer.MIN_VALUE, Integer.MIN_VALUE)
   .find{case (a, b) => a != b}
   .map{case (a, b) => a < b}
   .getOrElse(false)
val tests = List(
  (List(1, 2, 3), List(1, 2, 3)) -> false,
  (List(3, 2, 1), List(3, 2, 1)) -> false,
  (List(1, 2, 3), List(3, 2, 1)) -> true,
  (List(3, 2, 1), List(1, 2, 3)) -> false,
  (List(1, 2), List(1, 2, 3)) -> true,
  (List(1, 2, 3), List(1, 2)) -> false
)

tests.foreach{case test @ ((a, b), c) =>
  assert(lessThan1(a, b) == c, test)
  assert(lessThan2(a, b) == c, test)
  assert(lessThan3(a, b) == c, test)
}

"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise."


def ack(m: BigInt, n: BigInt): BigInt = {
  if (m==0) n+1
  else if (n==0) ack(m-1, 1)
  else ack(m-1, ack(m, n-1))
}

Example:
scala> for ( m <- 0 to 3; n <- 0 to 6 ) yield ack(m,n)
res0: Seq.Projection[BigInt] = RangeG(1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 7, 8, 3, 5, 7, 9, 11, 13, 15, 5, 13, 29, 61, 125, 253, 509)

val ackMap = new mutable.HashMap[(BigInt,BigInt),BigInt]
def ackMemo(m: BigInt, n: BigInt): BigInt = {
  ackMap.getOrElseUpdate((m,n), ack(m,n))
}

Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the conditions defined. The function is expected to terminate always. It is preferred to have arbitrary precision due to the rapid growth of the function. A memoized version using a mutable hash map is also provided.


implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in/library function if available. The Gamma function is computed through numerical integration.


object NQueens {

  private implicit class RichPair[T](
    pair: (T,T))(
    implicit num: Numeric[T]
  ) {
    import num._

    def safe(x: T, y: T): Boolean =
      pair._1 - pair._2 != abs(x - y)
  }

  def solve(n: Int): Iterator[Seq[Int]] = {
    (0 to n-1)
      .permutations
      .filter { v =>
        (0 to n-1).forall { y =>
          (y+1 to n-1).forall { x =>
            (x,y).safe(v(x),v(y))
          }
        }
      }
  }

  def main(args: Array[String]): Unit = {
    val n = args.headOption.getOrElse("8").toInt
    val (solns1, solns2) = solve(n).duplicate
    solns1
      .zipWithIndex
      .foreach { case (soln, i) =>
        Console.out.println(s"Solution #${i+1}")
        output(n)(soln)
      }
    val n_solns = solns2.size
    if (n_solns == 1) {
      Console.out.println("Found 1 solution")
    } else {
      Console.out.println(s"Found $n_solns solutions")
    }
  }

  def output(n: Int)(board: Seq[Int]): Unit = {
    board.foreach { queen =>
      val row =
        "_|" * queen + "Q" + "|_" * (n-queen-1)
      Console.out.println(row)
    }
  }
}
scala> NQueens.main(Array("8"))
Solution #1
Q|_|_|_|_|_|_|_
_|_|_|_|Q|_|_|_
_|_|_|_|_|_|_|Q
_|_|_|_|_|Q|_|_
_|_|Q|_|_|_|_|_
_|_|_|_|_|_|Q|_
_|Q|_|_|_|_|_|_
_|_|_|Q|_|_|_|_

Solution #2
Q|_|_|_|_|_|_|_
_|_|_|_|_|Q|_|_
_|_|_|_|_|_|_|Q
_|_|Q|_|_|_|_|_
_|_|_|_|_|_|Q|_
_|_|_|Q|_|_|_|_
_|Q|_|_|_|_|_|_
_|_|_|_|Q|_|_|_
...
Found 92 solutions

The code solves the N-queens puzzle for a board of size NxN, extending the eight queens puzzle. It uses an enriched implicit class to extend a Tuple2[T,T] to check if positions are safe or threatened. It also lazily generates permutations with an Iterator. The code also provides the number of solutions for small values of N, referencing OEIS: A000170.


val arr1 = Array( 1, 2, 3 )
val arr2 = Array( 4, 5, 6 )
val arr3 = Array( 7, 8, 9 )

arr1 ++ arr2 ++ arr3
//or:
Array concat ( arr1, arr2, arr3 )
// res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)

demonstrate how to concatenate two arrays.


Works with: Scala version 2.9.2
object Knapsack extends App {

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

  val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)/1000}

  //===== brute force (caution: increase the heap!) ====================================
  val ks01b: List[Item] => Unit = loi => {
    val tw:Set[Item]=>Int=ps=>(ps:\0)((a,b)=>a.weight+b) //total weight
    val tv:Set[Item]=>Int=ps=>(ps:\0)((a,b)=>a.value+b) //total value
    val pis = (loi.toSet.subsets).toList.filterNot(_==Set())

   #[test]
fn test_dp_results() {
    let dp_results = knap_01_dp(items, 400);
    let dp_weights= dp_results.iter().fold(0, |a, &b| a + b.weight);
    let dp_values = dp_results.iter().fold(0, |a, &b| a + b.value);
    assert_eq!(dp_weights, 396);
    assert_eq!(dp_values, 1030);
} val res = pis.map(ss=>Pair(ss,tw(ss)))
      .filter(p=>p._2>350 && p._2<401).map(p=>Pair(p,tv(p._1)))
      .sortWith((s,t)=>s._2.compareTo(t._2) < 0)
      .last
    println{val h = "packing list of items (brute force):"; h+"\n"+"="*h.size}
    res._1._1.foreach{p=>print("  "+p.name+": weight="+p.weight+" value="+p.value+"\n")}
    println("\n"+"  resulting items: "+res._1._1.size+" of "+loi.size)
    println("  total weight: "+res._1._2+", total value: "+res._2)
  }

  //===== dynamic programming ==========================================================
  val ks01d: List[Item] => Unit = loi => {
    val W = 400
    val N = loi.size

    val m = Array.ofDim[Int](N+1,W+1)
    val plm = (List((for {w <- 0 to W} yield Set[Item]()).toArray)++(
                for {
                  n <- 0 to N-1
                  colN = (for {w <- 0 to W} yield Set[Item](loi(n))).toArray
                } yield colN)).toArray

    1 to N foreach {n =>
      0 to W foreach {w =>
        def in = loi(n-1)
        def wn = loi(n-1).weight
        def vn = loi(n-1).value
        if (w<wn) {
          m(n)(w) = m(n-1)(w)
          plm(n)(w) = plm(n-1)(w)
        }
        else {
          if (m(n-1)(w)>=m(n-1)(w-wn)+vn) {
            m(n)(w) = m(n-1)(w)
            plm(n)(w) = plm(n-1)(w)
          }
          else {
            m(n)(w) = m(n-1)(w-wn)+vn
	    plm(n)(w) = plm(n-1)(w-wn)+in
	  }
	}
      }
    }

    println{val h = "packing list of items (dynamic programming):"; h+"\n"+"="*h.size}
    plm(N)(W).foreach{p=>print("  "+p.name+": weight="+p.weight+" value="+p.value+"\n")}
    println("\n"+"  resulting items: "+plm(N)(W).size+" of "+loi.size)
    println("  total weight: "+(0/:plm(N)(W).toVector.map{item=>item.weight})(_+_)+", total value: "+m(N)(W))
  }

  val items = List(
     Item("map", 9, 150)
    ,Item("compass", 13, 35)
    ,Item("water", 153, 200)
    ,Item("sandwich", 50, 160)
    ,Item("glucose", 15, 60)
    ,Item("tin", 68, 45)
    ,Item("banana", 27, 60)
    ,Item("apple", 39, 40)
    ,Item("cheese", 23, 30)
    ,Item("beer", 52, 10)
    ,Item("suntan cream", 11, 70)
    ,Item("camera", 32, 30)
    ,Item("t-shirt", 24, 15)
    ,Item("trousers", 48, 10)
    ,Item("umbrella", 73, 40)
    ,Item("waterproof trousers", 42, 70)
    ,Item("waterproof overclothes", 43, 75)
    ,Item("note-case", 22, 80)
    ,Item("sunglasses", 7, 20)
    ,Item("towel", 18, 12)
    ,Item("socks", 4, 50)
    ,Item("book", 30, 10)
  )

  List(ks01b, ks01d).foreach{f=>
    val t = elapsed{f(items)}
    println("  elapsed time: "+t+" sec"+"\n")
  }
}

The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.


object SMP extends App {
    private def checkMarriages(): Unit =
        if (check)
            println("Marriages are stable")
        else
            println("Marriages are unstable")

    private def swap() {
        val girl1 = girls.head
        val girl2 = girls(1)
        val tmp = girl2 -> matches(girl1)
        matches += girl1 -> matches(girl2)
        matches += tmp
        println(girl1 + " and " + girl2 + " have switched partners")
    }

    private type TM = scala.collection.mutable.TreeMap[String, String]

    private def check: Boolean = {
        if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet))
            return false

        val invertedMatches = new TM
        matches foreach { invertedMatches += _.swap }

        for ((k, v) <- matches) {
            val shePrefers = girlPrefers(k)
            val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v))
            val hePrefers = guyPrefers(v)
            val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k))

            for (guy <- sheLikesBetter) {
                val fiance = invertedMatches(guy)
                val guy_p = guyPrefers(guy)
                if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) {
                    println(s"$k likes $guy better than $v and $guy likes $k better than their current partner")
                    return false
                }
            }

            for (girl <- heLikesBetter) {
                val fiance = matches(girl)
                val girl_p = girlPrefers(girl)
                if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) {
                    println(s"$v likes $girl better than $k and $girl likes $v better than their current partner")
                    return false
                }
            }
        }
        true
    }

    private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil
    private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil
    private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"),
        "bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"),
        "col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"),
        "dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"),
        "ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"),
        "fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"),
        "gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"),
        "hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"),
        "ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"),
        "jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"))
    private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"),
        "bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"),
        "cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"),
        "dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"),
        "eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"),
        "fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"),
        "gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"),
        "hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"),
        "ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"),
        "jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"))

    private lazy val matches = {
        val engagements = new TM
        val freeGuys = scala.collection.mutable.Queue.empty ++ guys
        while (freeGuys.nonEmpty) {
            val guy = freeGuys.dequeue()
            val guy_p = guyPrefers(guy)
            var break = false
            for (girl <- guy_p)
                if (!break)
                    if (!engagements.contains(girl)) {
                        engagements(girl) = guy
                        break = true
                    }
                    else {
                        val other_guy = engagements(girl)
                        val girl_p = girlPrefers(girl)
                        if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) {
                            engagements(girl) = guy
                            freeGuys += other_guy
                            break = true
                        }
                    }
        }

        engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") }
        engagements
    }

    checkMarriages()
    swap()
    checkMarriages()
}

The code implements the Gale/Shapley algorithm to solve the Stable Marriage problem. It takes as input a list of ten males and ten females, each with a ranked list of preferences. The code then generates a stable set of engagements based on these preferences. It also perturbs this set to create an unstable set of engagements and checks the stability of this new set.


object ShortCircuit {
   def a(b:Boolean)={print("Called A=%5b".format(b));b}
   def b(b:Boolean)={print(" -> B=%5b".format(b));b}

   def main(args: Array[String]): Unit = {
      val boolVals=List(false,true)
      for(aa<-boolVals; bb<-boolVals){
         print("\nTesting A=%5b AND B=%5b   -> ".format(aa, bb))
         a(aa) && b(bb)
      }
      for(aa<-boolVals; bb<-boolVals){
         print("\nTesting A=%5b  OR B=%5b   -> ".format(aa, bb))
         a(aa) || b(bb)
      }
      println
   }
}

create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.


<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. </output>


Library: Scalaobject AbcBlocks extends App {

  protected class Block(face1: Char, face2: Char) {

    def isFacedWith(that: Char) = { that == face1 || that == face2 }
    override def toString() = face1.toString + face2
  }
  protected object Block {
    def apply(faces: String) = new Block(faces.head, faces.last)
  }

  type word = Seq[Block]

  private val blocks = List(Block("BO"), Block("XK"), Block("DQ"), Block("CP"), Block("NA"),
    Block("GT"), Block("RE"), Block("TG"), Block("QD"), Block("FS"),
    Block("JW"), Block("HU"), Block("VI"), Block("AN"), Block("OB"),
    Block("ER"), Block("FS"), Block("LY"), Block("PC"), Block("ZM"))

  private def isMakeable(word: String, blocks: word) = {

    def getTheBlocks(word: String, blocks: word) = {

      def inner(word: String, toCompare: word, rest: word, accu: word): word = {
        if (word.isEmpty || rest.isEmpty || toCompare.isEmpty) accu
        else if (toCompare.head.isFacedWith(word.head)) {
          val restant = rest diff List(toCompare.head)
          inner(word.tail, restant, restant, accu :+ toCompare.head)
        } else inner(word, toCompare.tail, rest, accu)
      }
      inner(word, blocks, blocks, Nil)
    }

    word.lengthCompare(getTheBlocks(word, blocks).size) == 0
  }

  val words = List("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSED", "ANBOCPDQERSFTGUVWXLZ")
  // Automatic tests
  assert(isMakeable(words(0), blocks))
  assert(isMakeable(words(1), blocks))
  assert(!isMakeable(words(2), blocks)) // BOOK not
  assert(isMakeable(words(3), blocks))
  assert(!isMakeable(words(4), blocks)) // COMMON not
  assert(isMakeable(words(5), blocks))
  assert(isMakeable(words(6), blocks))
  assert(isMakeable(words(7), blocks))

  //words(7).mkString.permutations.foreach(s => assert(isMakeable(s, blocks)))

  words.foreach(w => println(s"$w can${if (isMakeable(w, blocks)) " " else "not "}be made."))
}

"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed."


object RosettaMD5 extends App {

  def MD5(s: String): String = {
    // Besides "MD5", "SHA-256", and other hashes are available
    val m = java.security.MessageDigest.getInstance("MD5").digest(s.getBytes("UTF-8"))
    m.map("%02x".format(_)).mkString
  }

  assert("d41d8cd98f00b204e9800998ecf8427e" == MD5(""))
  assert("0cc175b9c0f1b6a831c399e269772661" == MD5("a"))
  assert("900150983cd24fb0d6963f7d28e17f72" == MD5("abc"))
  assert("f96b697d7cb7938d525a2f31aaf161d0" == MD5("message digest"))
  assert("c3fcd3d76192e4007dfb496cca67e13b" == MD5("abcdefghijklmnopqrstuvwxyz"))
  assert("e38ca1d920c4b8b8d3946b2c72f01680" == MD5("The quick brown fox jumped over the lazy dog's back"))
  assert("d174ab98d277d9f5a5611c2c9f419d9f" ==
    MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
  assert("57edf4a22be3c955ac49da2e2107b67a" ==
    MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890"))
  import scala.compat.Platform.currentTime
  println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]")
}

implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5/Implementation for a scratch implementation.


Library: Scala
import java.net.Socket

object sendSocketData {

  def sendData(host: String, msg: String) {
    val sock = new Socket(host, 256)
    sock.getOutputStream().write(msg.getBytes())
    sock.getOutputStream().flush()
    sock.close()
  }

  sendData("localhost", "hello socket world")
}

opens a socket to localhost on port 256, sends the message "hello socket world", and then closes the socket.


Library: Scala
import java.util.Properties

import javax.mail.internet.{ InternetAddress, MimeMessage }
import javax.mail.Message.RecipientType
import javax.mail.{ Session, Transport }

/** Mail constructor.
 *  @constructor Mail
 *  @param host Host
 */
class Mail(host: String) {
  val session = Session.getDefaultInstance(new Properties() { put("mail.smtp.host", host) })

  /** Send email message.
   *
   *  @param from From
   *  @param tos Recipients
   *  @param ccs CC Recipients
   *  @param subject Subject
   *  @param text Text
   *  @throws MessagingException
   */
  def send(from: String, tos: List[String], ccs: List[String], subject: String, text: String) {
    val message = new MimeMessage(session)
    message.setFrom(new InternetAddress(from))
    for (to <- tos)
      message.addRecipient(RecipientType.TO, new InternetAddress(to))
    for (cc <- ccs)
      message.addRecipient(RecipientType.TO, new InternetAddress(cc))
    message.setSubject(subject)
    message.setText(text)
    Transport.send(message)
  }
}

Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.


Stream from 0 foreach (i => println(i.toOctalString))

generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.


def swap[A,B](a: A, b: B): (B, A) = (b, a)

implement a generic swap function or operator that can exchange the values of two variables or storage places, regardless of their types. In statically typed languages, the function should be described in a way that provides genericity. The function should be able to handle mutually compatible types and does not necessarily need to swap different types like strings and integers. The function uses type parameters and abstract types in Scala, and returns a tuple with inverted values as it cannot swap values in-place.


Library: Scala
  def isPalindrome(s: String): Boolean = (s.size >= 2) && s == s.reverse
  def isPalindromeSentence(s: String): Boolean =
    (s.size >= 2) && {
      val p = s.replaceAll("[^\\p{L}]", "").toLowerCase
      p == p.reverse
    }
import scala.annotation.tailrec

  def isPalindromeRec(s: String) = {
    @tailrec
    def inner(s: String): Boolean =
      (s.length <= 1) || (s.head == s.last) && inner(s.tail.init)

    (s.size >= 2) && inner(s)
  }

  // Testing
  assert(!isPalindrome(""))
  assert(!isPalindrome("z"))
  assert(isPalindrome("amanaplanacanalpanama"))
  assert(!isPalindrome("Test 1,2,3"))
  assert(isPalindrome("1 2 1"))
  assert(!isPalindrome("A man a plan a canal Panama."))

  assert(!isPalindromeSentence(""))
  assert(!isPalindromeSentence("z"))
  assert(isPalindromeSentence("amanaplanacanalpanama"))
  assert(!isPalindromeSentence("Test 1,2,3"))
  assert(isPalindromeSentence("1 2 1"))
  assert(isPalindromeSentence("A man a plan a canal Panama."))

  assert(!isPalindromeRec(""))
  assert(!isPalindromeRec("z"))
  assert(isPalindromeRec("amanaplanacanalpanama"))
  assert(!isPalindromeRec("Test 1,2,3"))
  assert(isPalindromeRec("1 2 1"))
  assert(!isPalindromeRec("A man a plan a canal Panama."))

  println("Successfully completed without errors.")

The code provides a function to check if a given sequence of characters or bytes is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case sensitivity. The code also includes a method to reverse a string.


"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system."


function deque(arr) {
    arr["start"] = 0
    arr["end"] = 0
}

function dequelen(arr) {
    return arr["end"] - arr["start"]
}

function empty(arr) {
    return dequelen(arr) == 0
}

function push(arr, elem) {
    arr[++arr["end"]] = elem
}

function pop(arr) {
    if (empty(arr)) {
        return
    }
    return arr[arr["end"]--]
}

function unshift(arr, elem) {
    arr[arr["start"]--] = elem
}

function shift(arr) {
    if (empty(arr)) {
        return
    }
    return arr[++arr["start"]]
}

function peek(arr) {
    if (empty(arr)) {
        return
    }
    return arr[arr["end"]]
}

function printdeque(arr,    i, sep) {
    printf("[")
    for (i = arr["start"] + 1; i <= arr["end"]; i++) {
        printf("%s%s", sep, arr[i])
        sep = ", "
    }
    printf("]\n")
}

BEGIN {
    deque(q)
    for (i = 1; i <= 10; i++) {
        push(q, i)
    }
    printdeque(q)
    for (i = 1; i <= 10; i++) {
        print pop(q)
    }
    printdeque(q)
}

implement a stack data structure with basic operations such as push (to add elements), pop (to remove and return the last added element), and empty (to check if the stack is empty). This stack follows a Last-In-First-Out (LIFO) access policy.


generate the nth Fibonacci number, supporting both positive and negative indices. The function can be implemented either iteratively or recursively.


select specific elements from an array, in this case, all even numbers, and place them into a new array. Optionally, it can also modify the original array instead of creating a new one. The sequence of elements may not be maintained.


BEGIN {
	str = "abcdefghijklmnopqrstuvwxyz"
	n = 12
	m = 5

	print substr(str, n, m)
	print substr(str, n)
	print substr(str, 1, length(str) - 1)
	print substr(str, index(str, "q"), m)
	print substr(str, index(str, "pq"), m)
}

- Extracts a substring starting from the nth character of a specific length m.
- Extracts a substring starting from the nth character up to the end of the string.
- Returns the entire string excluding the last character.
- Extracts a substring starting from a known character within the string of length m.
- Extracts a substring starting from a known substring within the string of length m.
- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.
- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.
- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.


function reverse(s)
{
  p = ""
  for(i=length(s); i > 0; i--) { p = p substr(s, i, 1) }
  return p
}

BEGIN {
  print reverse("edoCattesoR")
}

Recursive
function reverse(s   ,l)
{
  l = length(s)
  return l < 2 ? s:( substr(s,l,1) reverse(substr(s,1,l-1)) )
}

BEGIN {
  print reverse("edoCattesoR")
}

using split, then joining in front

# Usage: awk -f reverse.awk -v s=Rosetta

function rev(s,   i,len,a,r) {
   len = split(s, a, "")
  #for (i in a) r = a[i] r	# may not work - order is not guaranteed !
   for (i=1; i<=len; i++) r = a[i] r
   return r
}
BEGIN {
   if(!s) s = "Hello, world!"
   print s, "<-->", rev(s)
}

Reverses a given string while preserving Unicode combining characters. For instance, it transforms "asdf" to "fdsa" and "as⃝df̅" to "f̅ds⃝a".


NF == 3 { graph[$1,$2] = $3 }
NF == 2 {
    weight = shortest($1, $2)
    n = length(path)
    p = $1
    for (i = 2; i < n; i++)
        p = p "-" path[i]
    print p "-" $2 " (" weight ")"
}

# Edge weights are in graph[node1,node2]
# Returns the weight of the shortest path
# Shortest path is in path[1] ... path[n]
function shortest(from, to,    queue, q, dist, v, i, min, edge, e, prev, n) {
    delete path
    dist[from] = 0
    queue[q=1] = from

    while (q > 0) {
        min = 1
        for (i = 2; i <= q; i++)
            if (dist[queue[i]] < dist[queue[min]])
                min = i
        v = queue[min]
        queue[min] = queue[q--]

        if (v == to)
            break
        for (edge in graph) {
            split(edge, e, SUBSEP)
            if (e[1] != v)
                continue
            if (!(e[2] in dist) || dist[e[1]] + graph[edge] < dist[e[2]]) {
                dist[e[2]] = dist[e[1]] + graph[edge]
                prev[e[2]] = e[1]
                queue[++q] = e[2]
            }
        }
    }
    if (v != to)
        return "n/a"

    # Build the path
    n = 1
    for (v = to; v != from; v = prev[v])
        n++
    for (v = to; n > 0; v = prev[v])
       path[n--] = v
    return dist[to]
}

$ cat dijkstra.txt
a b 7
a c 9
a f 14
b c 10
b d 15
c d 11
c f 2
d e 6
e f 9
a e
a f
f a

$ awk -f dijkstra.awk dijkstra.txt
a-c-d-e (26)
a-c-f (11)
f-a (n/a)

The code implements Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a given graph. The graph is represented by an adjacency matrix or list and a start node. The algorithm iteratively updates the cost of reaching each vertex and keeps track of the path leading to the minimum cost. The output is a set of edges depicting the shortest path to each reachable node from the source. The code also includes functionality to interpret the output and display the shortest path from the source node to specific nodes.


"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."


BEGIN {
    srand()  # randomize the RNG
	for (;;) {
		print n = int(rand() * 20)
		if (n == 10)
			break
		print int(rand() * 20)
	}
}

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.


# syntax: GAWK -f DAY_OF_THE_WEEK.AWK
# runtime does not support years > 2037 on my 32-bit Windows XP O/S
BEGIN {
    for (i=2008; i<=2121; i++) {
      x = strftime("%Y/%m/%d %a",mktime(sprintf("%d 12 25 0 0 0",i)))
      if (x ~ /Sun/) { print(x) }
    }
}

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.


$ awk 'BEGIN{split("a b c d c b a",a);for(i in a)b[a[i]]=1;r="";for(i in b)r=r" "i;print r}'
a b c d

"Removes duplicate elements from an array using three possible methods: hashing, sorting and removing consecutive duplicates, or checking the rest of the list for each element. The output is a string representation of a new array with unique elements only."