task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Prolog
Prolog
nth(N, N_Th) :- ( tween(N) -> Th = "th" ; 1 is N mod 10 -> Th = "st" ; 2 is N mod 10 -> Th = "nd" ; 3 is N mod 10 -> Th = "rd" ; Th = "th" ), string_concat(N, Th, N_Th).   tween(N) :- Tween is N mod 100, between(11, 13, Tween).   test :- forall( between(0,25, N), (nth(N, N_Th), form...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Quackery
Quackery
[ dup 0 swap [ dup 0 != while 10 /mod dup ** rot + swap again ] drop = ] is munchausen ( n --> b )   5000 times [ i^ 1+ munchausen if [ i^ 1+ echo sp ] ]
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Logo
Logo
to m :n if 0 = :n [output 0] output :n - f m :n-1 end to f :n if 0 = :n [output 1] output :n - m f :n-1 end   show cascade 20 [lput m #-1 ?] [] [1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12] show cascade 20 [lput f #-1 ?] [] [0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12]
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#REXX
REXX
/*REXX program mimics a bind operation when trying to perform addition upon arguments. */ call add 1, 2 call add 1, 2.0 call add 1, 2.0, -6 call add self, 2 exit 0 /*stick a fork in it, we're all done. */ /*─────────────────────────────────────────────────────────────────────...
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Ruby
Ruby
class Maybe def initialize(value) @value = value end   def map if @value.nil? self else Maybe.new(yield @value) end end end   Maybe.new(3).map { |n| 2*n }.map { |n| n+1 } #=> #<Maybe @value=7>   Maybe.new(nil).map { |n| 2*n }.map { |n| n+1 } #=> #<Maybe @value=nil>   Maybe.new(3).map...
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#Dart
Dart
  import 'dart:async'; import 'dart:html'; import 'dart:math' show Random;   // We changed 5 lines of code to make this sample nicer on // the web (so that the execution waits for animation frame, // the number gets updated in the DOM, and the program ends // after 500 iterations).   main() async { print('Compute π...
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#E
E
def pi(n) { var inside := 0 for _ ? (entropy.nextFloat() ** 2 + entropy.nextFloat() ** 2 < 1) in 1..n { inside += 1 } return inside * 4 / n }
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Picat
Picat
import util.   go => Strings = ["broood", "bananaaa", "hiphophiphop"], foreach(String in Strings) check(String) end, nl.   % adjustments to 1-based index encode(String) = [Pos,Table] => Table = "abcdefghijklmnopqrstuvwxyz", Pos = [], Len = String.length, foreach({C,I} in zip(String,1..Len)) Po...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#PicoLisp
PicoLisp
(de encode (Str) (let Table (chop "abcdefghijklmnopqrstuvwxyz") (mapcar '((C) (dec (prog1 (index C Table) (rot Table @) ) ) ) (chop Str) ) ) )   (de decode (Lst) (let Table (chop "abcdefghijklmnopqrstuvwxyz") (pack ...
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#C.23
C#
using System; using System.Collections.Generic;   namespace Morse { class Morse { static void Main(string[] args) { string word = "sos"; Dictionary<string, string> Codes = new Dictionary<string, string> { {"a", ".- "}, {"b", "-... "}, {"c", "...
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#C.23
C#
using System;   class Program { static void Main(string[] args) { int switchWins = 0; int stayWins = 0;   Random gen = new Random();   for(int plays = 0; plays < 1000000; plays++ ) { int[] doors = {0,0,0};//0 is a goat, 1 is a car   var winner = ge...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#D
D
T modInverse(T)(T a, T b) pure nothrow { if (b == 1) return 1; T b0 = b, x0 = 0, x1 = 1;   while (a > 1) { immutable q = a / b; auto t = b; b = a % b; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } return (x1 < 0) ? (x1 + b0) : ...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#dc
dc
  dc -e "[m=]P?dsm[a=]P?dsa1sv[dsb~rsqlbrldlqlv*-lvsdsvd0<x]dsxxldd[dlmr+]sx0>xdla*lm%[p]sx1=x"  
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#BASIC256
BASIC256
print " X| 1 2 3 4 5 6 7 8 9 10 11 12" print "---+------------------------------------------------"   for i = 1 to 12 nums$ = right(" " + string(i), 3) + "|" for j = 1 to 12 if i <= j then if j >= 1 then nums$ += left(" ", (4 - length(string(i * j)))...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Wren
Wren
import "/matrix" for Matrix   var multipleRegression = Fn.new { |y, x| var cy = y.transpose var cx = x.transpose return ((x * cx).inverse * x * cy).transpose[0] }   var ys = [ Matrix.new([ [1, 2, 3, 4, 5] ]), Matrix.new([ [3, 4, 5] ]), Matrix.new([ [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.9...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#JavaScript
JavaScript
  function multifact(n, deg){ var result = n; while (n >= deg + 1){ result *= (n - deg); n -= deg; } return result; }  
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#jq
jq
# Input: n # Output: n * (n - d) * (n - 2d) ... def multifactorial(d): . as $n | ($n / d | floor) as $k | reduce ($n - (d * range(0; $k))) as $i (1; . * $i);
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Raku
Raku
use java::awt::MouseInfo:from<java>;   given MouseInfo.getPointerInfo.getLocation { say .getX, 'x', .getY; }
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Ring
Ring
  Load "guilib.ring"   lPress = false nX = 0 nY = 0   new qApp {   win1 = new qWidget() {   setWindowTitle("Move this label!") setGeometry(100,100,400,400) setstylesheet("background-color:white;")   Label1 = new qLabel(Win1){ ...
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Kotlin
Kotlin
// version 1.1.3   var count = 0 var c = IntArray(0) var f = ""   fun nQueens(row: Int, n: Int) { outer@ for (x in 1..n) { for (y in 1..row - 1) { if (c[y] == x) continue@outer if (row - y == Math.abs(x - c[y])) continue@outer } c[row] = x if (row ...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#PureBasic
PureBasic
Procedure.s Suffix(n.i) Select n%10 Case 1 : If n%100<>11 : ProcedureReturn "st" : EndIf Case 2 : If n%100<>12 : ProcedureReturn "nd" : EndIf Case 3 : If n%100<>13 : ProcedureReturn "rd" : EndIf EndSelect ProcedureReturn "th" EndProcedure   Procedure put(a.i,b.i) For i=a To b : Print(Str(i)+Suffix...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Racket
Racket
#lang racket   (define (expt:0^0=1 r p) (if (zero? r) 0 (expt r p)))   (define (munchausen-number? n (t n)) (if (zero? n) (zero? t) (let-values (([q r] (quotient/remainder n 10))) (munchausen-number? q (- t (expt:0^0=1 r r))))))   (module+ main (for-each displayln (filter munchausen-number? (r...
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#LSL
LSL
integer iDEPTH = 100; integer f(integer n) { if(n==0) { return 1; } else { return n-m(f(n - 1)); } } integer m(integer n) { if(n==0) { return 0; } else { return n-f(m(n - 1)); } } default { state_entry() { integer x = 0; string s = ""; for(x=0 ; x<iDEPTH ; x++) { s += (string)(f(x))+" "; } l...
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Wren
Wren
import "/fmt" for Fmt   class Maybe { construct new(value) { _value = value }   value { _value }   bind(f) { f.call(_value) }   static unit(i) { Maybe.new(i) } }   var decrement = Fn.new { |i| if (!i) return Maybe.unit(null) return Maybe.unit(i - 1) }   var triple = Fn.new { |i| ...
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#EasyLang
EasyLang
func mc n . . for i range n x = randomf y = randomf if x * x + y * y < 1 hit += 1 . . print 4.0 * hit / n . fscale 4 call mc 10000 call mc 100000 call mc 1000000 call mc 10000000
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#Elixir
Elixir
defmodule MonteCarlo do def pi(n) do count = Enum.count(1..n, fn _ -> x = :rand.uniform y = :rand.uniform  :math.sqrt(x*x + y*y) <= 1 end) 4 * count / n end end   Enum.each([1000, 10000, 100000, 1000000, 10000000], fn n ->  :io.format "~8w samples: PI = ~f~n", [n, MonteCarlo.pi(n)] end...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#PL.2FI
PL/I
*process source attributes xref or(!); /********************************************************************* * 25.5.2014 Walter Pachl translated from REXX *********************************************************************/ ed: Proc Options(main); Call enc_dec('broood'); Call enc_dec('bananaaa'); Call enc_dec...
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#C.2B.2B
C++
  /* Michal Sikorski 06/07/2016 */ #include <cstdlib> #include <iostream> #include <windows.h> #include <string.h> using namespace std; int main(int argc, char *argv[]) { string inpt; char ascii[28] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ", lwcAscii[28] = " abcdefghijklmnopqrstuvwxyz"; string morse[27] = {" ", ".- ...
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#C.2B.2B
C++
#include <iostream> #include <cstdlib> #include <ctime>   int randint(int n) { return (1.0*n*std::rand())/(1.0+RAND_MAX); }   int other(int doorA, int doorB) { int doorC; if (doorA == doorB) { doorC = randint(2); if (doorC >= doorA) ++doorC; } else { for (doorC = 0; doorC == doorA || doo...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Delphi
Delphi
proc mulinv(int a, b) int: int t, nt, r, nr, q, tmp; if b<0 then b := -b fi; if a<0 then a := b - (-a % b) fi; t := 0; nt := 1; r := b; nr := a % b; while nr /= 0 do q := r / nr; tmp := nt; nt := t - q*nt; t := tmp; tmp := nr; nr := r - q*nr; r := tmp od; if r>1 then ...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Draco
Draco
proc mulinv(int a, b) int: int t, nt, r, nr, q, tmp; if b<0 then b := -b fi; if a<0 then a := b - (-a % b) fi; t := 0; nt := 1; r := b; nr := a % b; while nr /= 0 do q := r / nr; tmp := nt; nt := t - q*nt; t := tmp; tmp := nr; nr := r - q*nr; r := tmp od; if r>1 then ...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion ::The Main Thing... cls set colum=12&set row=12 call :multable echo. pause exit /b 0 ::/The Main Thing. ::The Functions... :multable echo. for /l %%. in (1,1,%colum%) do ( call :numstr %%. set firstline=!firstline!!space!%%. set seconline=!seconline!----- ) echo !first...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) height:=GSL.VectorFromData(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83); weight:=GSL.VectorFromData(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Julia
Julia
using Printf   function multifact(n::Integer, k::Integer) n > 0 && k > 0 || throw(DomainError()) k > 1 || factorial(n) return prod(n:-k:2) end   const khi = 5 const nhi = 10 println("Showing multifactorial for n in [1, $nhi] and k in [1, $khi].") for k = 1:khi a = multifact.(1:nhi, k) lab = "n" * "!...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Kotlin
Kotlin
fun multifactorial(n: Long, d: Int) : Long { val r = n % d return (1..n).filter { it % d == r } .reduce { i, p -> i * p } }   fun main(args: Array<String>) { val m = 5 val r = 1..10L for (d in 1..m) { print("%${m}s:".format( "!".repeat(d))) r.forEach { print(" " + multifactorial(it, ...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Ruby
Ruby
Shoes.app(:title => "Mouse Position", :width => 400, :height => 400) do @position = para "Position : ?, ?", :size => 12, :margin => 10   motion do |x, y| @position.text = "Position : #{x}, #{y}" end end
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Rust
Rust
// rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800)   use std::libc::{BOOL, HANDLE, LONG}; use std::ptr::mut_null;   type HWND = HANDLE;   #[deriving(Eq)] struct POINT { x: LONG, y: LONG }   #[link_name = "user32"] extern "system" { fn GetCursorPos(lpPoint:&mut POINT) -> BOOL; fn GetForegroundWindow() -> H...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Scala
Scala
import java.awt.MouseInfo object MousePosition extends App { val mouseLocation = MouseInfo.getPointerInfo.getLocation println (mouseLocation) }
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Liberty_BASIC
Liberty BASIC
  'N queens '>10 would not work due to way permutations used 'anyway, 10 doesn't fit in memory Input "Input N for N queens puzzle (4..9) ";N if N<4 or N>9 then print "N out of range - quitting": end   ABC$= " " dash$ = "" for i = 0 to N-1 ABC$=ABC$+" "+chr$(asc("a")+i) dash$ = dash$+"--" next   dim q(N) t0=time...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Python
Python
_suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']   def nth(n): return "%i'%s" % (n, _suffix[n%10] if n % 100 <= 10 or n % 100 > 20 else 'th')   if __name__ == '__main__': for j in range(0,1001, 250): print(' '.join(nth(i) for i in list(range(j, j+25))))
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Raku
Raku
sub is_munchausen ( Int $n ) { constant @powers = 0, |map { $_ ** $_ }, 1..9; $n == @powers[$n.comb].sum; } .say if .&is_munchausen for 1..5000;
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Lua
Lua
  function m(n) return n > 0 and n - f(m(n-1)) or 0 end function f(n) return n > 0 and n - m(f(n-1)) or 1 end
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#zkl
zkl
fcn bind(a,type,b){ if(type.isType(a)) b else Void } fcn just(x){ if(Deferred.isType(x)) x() else x } // force lazy evaluation fcn rtn(x) { just(x) }
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#Erlang
Erlang
  -module(monte). -export([main/1]).   monte(N)-> monte(N,0,0).   monte(0,InCircle,NumPoints) -> 4 * InCircle / NumPoints;   monte(N,InCircle,NumPoints)-> Xcoord = rand:uniform(), Ycoord = rand:uniform(), monte(N-1, if Xcoord*Xcoord + Ycoord*Ycoord < 1 -> InCircle + 1; true -> InCircle end...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#PowerShell
PowerShell
Function Test-MTF { [CmdletBinding()] Param ( [Parameter(Mandatory=$true,Position=0)] [string]$word,   [Parameter(Mandatory=$false)] [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz' ) Begin { Function Encode { Param ( ...
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#Clojure
Clojure
(import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])   (defn play [sample-rate bs] (let [af (AudioFormat. sample-rate 8 1 true true)] (doto (AudioSystem/getSourceDataLine af) (.open af sample-rate) .start (.write bs 0 (count bs)) .drain .close)))   (defn note [hz sam...
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Chapel
Chapel
use Random;   param doors: int = 3; config const games: int = 1000;   config const maxTasks = 32; var numTasks = 1; while( games / numTasks > 1000000 && numTasks < maxTasks ) do numTasks += 1; const tasks = 1..#numTasks; const games_per_task = games / numTasks ; const remaining_games = games % numTasks ;   var wins_by_...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#EchoLisp
EchoLisp
  (lib 'math) ;; for egcd = extended gcd   (define (mod-inv x m) (define-values (g inv q) (egcd x m)) (unless (= 1 g) (error 'not-coprimes (list x m) )) (if (< inv 0) (+ m inv) inv))   (mod-inv 42 2017) → 1969 (mod-inv 42 666) 🔴 error: not-coprimes (42 666)  
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#BBC_BASIC
BBC BASIC
@% = 5 : REM Set column width FOR row% = 1 TO 12 PRINT row% TAB(row% * @%) ; FOR col% = row% TO 12 PRINT row% * col% ; NEXT col% PRINT NEXT row%
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Lambdatalk
Lambdatalk
  {def multifact {lambda {:n :deg} {if {<= :n :deg} then :n else {* :n {multifact {- :n :deg} :deg}}}}} -> multifact   {S.map {lambda {:deg} {br} Degree :deg: {S.map {{lambda {:deg :n} {multifact :n :deg}} :deg} {S.serie 1 10}}} {S.serie 1 5}} -> Degree 1: 1 2 6 24 120 720 5040 40320 362880 3628800 Degre...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Seed7
Seed7
xPos := pointerXPos(curr_win); yPos := pointerYPos(curr_win);
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Smalltalk
Smalltalk
  World activeHand position. " (394@649.0)"  
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-z 20 while n<4:input "How many queens (N>=4)";n:wend 30 dim q(n),e(n),o(n) 40 r=n mod 6 50 if r<>2 and r<>3 then gosub 320:goto 220 60 for i=1 to int(n/2) 70 e(i)=2*i 80 next 90 for i=1 to round(n/2) 100 o(i)=2*i-1 110 next 120 if r=2 then gosub 410 130 if r=3 then gosub 460 140 s=1 150 for i=1 to n ...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Quackery
Quackery
[ table ] is suffix ( n --> $ )   $ "th st nd rd th th th th th th" nest$ witheach [ ' suffix put ]   [ dup number$ swap dup 100 mod 10 21 within iff [ drop $ "th" join ] else [ 10 mod suffix join ] ] is ordinal$ ( n --> $ )   [ over - 1+ [] swap ...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#REXX
REXX
Do n=0 To 10000 If n=m(n) Then Say n End Exit m: Parse Arg z res=0 Do While z>'' Parse Var z c +1 z res=res+c**c End Return res
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#M2000_Interpreter
M2000 Interpreter
  \\ set console 70 characters by 40 lines Form 70, 40 Module CheckSubs { Flush Document one$, two$ For i =0 to 20 Print format$("{0::-3}",i); f(i) \\ number pop then top value of stack one$=format$("{0::-3}",number) m(i) two$=fo...
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#ERRE
ERRE
  PROGRAM RANDOM_PI   ! ! for rosettacode.org !   !$DOUBLE   PROCEDURE MONTECARLO(T->RES) LOCAL I,N FOR I=1 TO T DO IF RND(1)^2+RND(1)^2<1 THEN N+=1 END IF END FOR RES=4*N/T END PROCEDURE   BEGIN RANDOMIZE(TIMER) ! init rnd number generator MONTECARLO(1000->RES) PRINT(RES...
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function map MonteCarloPI (n,plot=false) ... $ X:=random(1,n); $ Y:=random(1,n); $ if plot then $ plot2d(X,Y,>points,style="."); $ plot2d("sqrt(1-x^2)",color=2,>add); $ endif $ return sum(X^2+Y^2<1)/n*4; $endfunction >MonteCarloPI(10^(1:7)) [ 3.6 2.96 3.224 3.1404 3.1398 3.141548 3.1421492 ] ...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Python
Python
from __future__ import print_function from string import ascii_lowercase   SYMBOLTABLE = list(ascii_lowercase)   def move2front_encode(strng, symboltable): sequence, pad = [], symboltable[::] for char in strng: indx = pad.index(char) sequence.append(indx) pad = [pad.pop(indx)] + pad ...
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#CoffeeScript
CoffeeScript
class Morse constructor : (@unit=0.05, @freq=700) ->   @cont = new AudioContext() @time = @cont.currentTime @alfabet = "..etianmsurwdkgohvf.l.pjbxcyzq..54.3...2.......16.......7...8.90"   getCode : (letter) -> i = @alfabet.indexOf letter result = "" while i > 1 result = ".-"[i%2] + res...
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Clojure
Clojure
(ns monty-hall-problem (:use [clojure.contrib.seq :only (shuffle)]))   (defn play-game [staying] (let [doors (shuffle [:goat :goat :car]) choice (rand-int 3) [a b] (filter #(not= choice %) (range 3)) alternative (if (= :goat (nth doors a)) b a)] (= :car (nth doors (if staying choice alte...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Elixir
Elixir
defmodule Modular do def extended_gcd(a, b) do {last_remainder, last_x} = extended_gcd(abs(a), abs(b), 1, 0, 0, 1) {last_remainder, last_x * (if a < 0, do: -1, else: 1)} end   defp extended_gcd(last_remainder, 0, last_x, _, _, _), do: {last_remainder, last_x} defp extended_gcd(last_remainder, remainder,...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#ERRE
ERRE
PROGRAM MOD_INV   !$INTEGER   PROCEDURE MUL_INV(A,B->T) LOCAL NT,R,NR,Q,TMP IF B<0 THEN B=-B IF A<0 THEN A=B-(-A MOD B) T=0 NT=1 R=B NR=A MOD B WHILE NR<>0 DO Q=R DIV NR TMP=NT NT=T-Q*NT T=TMP TMP=NR NR=R-Q*NR R=TMP END WHILE IF (R>1) THEN T=-1 EXIT PROCEDURE  ! NO INVERSE IF (T...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Befunge
Befunge
0>51p0>52p51g52g*:51g52g`!*\!51g52g+*+0\3>01p::55+%68*+\!28v w^p2<y|!`+66:+1,+*84*"\"!:g25$_,#!>#:<$$_^#!:-1g10/+55\-**<< "$9"^x>$55+,51g1+:66+`#@_055+68*\>\#<1#*-#9:#5_$"+---">:#,_$
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Latitude
Latitude
use 'format importAllSigils.   multiFactorial := { Range make ($1, 0, - $2) product. }.   1 upto 6 visit { takes '[degree]. answers := 1 upto 11 to (Array) map { multiFactorial ($1, degree). }. $stdout printf: ~fmt "Degree ~S: ~S", degree, answers. }.
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Lua
Lua
function multiFact (n, degree) local fact = 1 for i = n, 2, -degree do fact = fact * i end return fact end   print("Degree\t|\tMultifactorials 1 to 10") print(string.rep("-", 52)) for d = 1, 5 do io.write(" " .. d, "\t| ") for n = 1, 10 do io.write(multiFact(n, d) .. " ") end...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Standard_ML
Standard ML
open XWindows ; val dp = XOpenDisplay "" ; val w = XCreateSimpleWindow (RootWindow dp) origin (Area {x=0,y=0,w=400,h=300}) 3 0 0xffffff ; XMapWindow w; val (focus,_)=( Posix.Process.sleep (Time.fromReal 2.0); (* time to move from interpreter + activate arbitrary window *) XGetInputFocus dp ...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Tcl
Tcl
package require Tk 8.5 set curWindow [lindex [wm stackorder .] end] # Everything below will work with anything from Tk 8.0 onwards set x [expr {[winfo pointerx .] - [winfo rootx $curWindow]}] set y [expr {[winfo pointery .] - [winfo rooty $curWindow]}] tk_messageBox -message "the mouse is at ($x,$y) in window $curWindo...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Visual_Basic
Visual Basic
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) 'X and Y are in "twips" -- 15 twips per pixel Me.Print "X:" & X Me.Print "Y:" & Y End Sub
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Logo
Logo
to try :files :diag1 :diag2 :tried if :files = 0 [make "solutions :solutions+1 show :tried stop] localmake "safe (bitand :files :diag1 :diag2) until [:safe = 0] [ localmake "f bitnot bitand :safe minus :safe try bitand :files :f ashift bitand :diag1 :f -1 (ashift bitand :diag2 :f 1)+1 fput bitnot :f ...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#R
R
nth <- function(n) { if (length(n) > 1) return(sapply(n, nth))   mod <- function(m, n) ifelse(!(m%%n), n, m%%n) suffices <- c("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")   if (n %% 100 <= 10 || n %% 100 > 20) suffix <- suffices[mod(n+1, 10)] else suffix <- 'th'   paste(n, "'", suff...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Ring
Ring
  # Project : Munchausen numbers   limit = 5000   for n=1 to limit sum = 0 msum = string(n) for m=1 to len(msum) ms = number(msum[m]) sum = sum + pow(ms, ms) next if sum = n see n + nl ok next  
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Ruby
Ruby
class Integer   def munchausen? self.digits.map{|d| d**d}.sum == self end   end   puts (1..5000).select(&:munchausen?)
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#M4
M4
define(`female',`ifelse(0,$1,1,`eval($1 - male(female(decr($1))))')')dnl define(`male',`ifelse(0,$1,0,`eval($1 - female(male(decr($1))))')')dnl define(`loop',`ifelse($1,$2,,`$3($1) loop(incr($1),$2,`$3')')')dnl loop(0,20,`female') loop(0,20,`male')
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#F.23
F#
  let print x = printfn "%A" x   let MonteCarloPiGreco niter = let eng = System.Random() let action () = let x: float = eng.NextDouble() let y: float = eng.NextDouble() let res: float = System.Math.Sqrt(x**2.0 + y**2.0) if res < 1.0 then 1 else 0 ...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Quackery
Quackery
[ [] 26 times [ char a i^ + join ] ] constant is symbols ( --> $ )   [ [] symbols rot witheach [ over find tuck pluck swap join dip join ] drop ] is encode ( $ --> [ )   [ $ "" symbols rot witheach [ pluck dup rot join ...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Racket
Racket
#lang racket (define default-symtab "abcdefghijklmnopqrstuvwxyz")   (define (move-to-front:encode in (symtab default-symtab)) (define inner-encode (match-lambda** [((? string? (app string->list in)) st acc) ; make input all listy (inner-encode in st acc)] [(in (? string? (app string->list st)) acc...
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#D
D
  import std.conv; import std.stdio;   immutable string[char] morsecode;   static this() { morsecode = [ 'a': ".-", 'b': "-...", 'c': "-.-.", 'd': "-..", 'e': ".", 'f': "..-.", 'g': "--.", 'h': "....", 'i': "..", 'j': ".---", 'k...
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. monty-hall.   DATA DIVISION. WORKING-STORAGE SECTION. 78 Num-Games VALUE 1000000.   *> These are needed so the values are passed to *> get-rand-int correctly. 01 One PIC 9 VALUE 1. 01 ...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#F.23
F#
  // Calculate the inverse of a (mod m) // See here for eea specs: // https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm let modInv m a = let rec eea t t' r r' = match r' with | 0 -> t | _ -> let div = r/r' eea t' (t - div * t') r' (r - div * r') (m + eea 0 1 m a) % m  
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Factor
Factor
USE: math.functions 42 2017 mod-inv
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#BQN
BQN
Table ← { m ← •Repr¨ ×⌜˜1+↕𝕩 # The numbers, formatted individually main ← ⟨ # Bottom part: three sections >(-⌈10⋆⁼𝕩)↑¨⊏m # Original numbers 𝕩⥊'|' # Divider ∾˘(-1+⌈10⋆⁼𝕩×𝕩)↑¨(≤⌜˜↕𝕩)/¨m # Multiplied numbers, padded and joined ...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#MAD
MAD
NORMAL MODE IS INTEGER   INTERNAL FUNCTION(N,DEG) ENTRY TO MLTFAC. RSLT = 1 THROUGH MULT, FOR MPC=N, -DEG, MPC.L.1 MULT RSLT = RSLT * MPC FUNCTION RETURN RSLT END OF FUNCTION   THROUGH SHOW, FOR I=1, 1, I.G.10 SHOW ...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Maple
Maple
  f := proc (n, m) local fac, i; fac := 1; for i from n by -m to 1 do fac := fac*i; end do; return fac; end proc:   a:=Matrix(5,10): for i from 1 to 5 do for j from 1 to 10 do a[i,j]:=f(j,i); end do; end do; a;  
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Wren
Wren
import "dome" for Window import "graphics" for Canvas import "input" for Mouse   class Game { static init() { Window.title = "Mouse position" Canvas.resize(400, 400) Window.resize(400, 400) // get initial mouse coordinates __px = Mouse.x __py = Mouse.y __...
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#XPL0
XPL0
include c:\cxpl\stdlib; if not OpenMouse then Text(0, "A mouse is required") else [ShowMouse(true); IntOut(0, GetMousePosition(0)); ChOut(0, ^,); IntOut(0, GetMousePosition(1)); CrLf(0); ]
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Lua
Lua
N = 8   -- We'll use nil to indicate no queen is present. grid = {} for i = 0, N do grid[i] = {} end   function can_find_solution(x0, y0) local x0, y0 = x0 or 0, y0 or 1 -- Set default vals (0, 1). for x = 1, x0 - 1 do if grid[x][y0] or grid[x][y0 - x0 + x] or grid[x][y0 + x0 - x] then return false ...
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Racket
Racket
#lang racket (define (teen? n) (<= 11 (modulo n 100) 19)) (define (Nth n) (format "~a'~a" n (match* ((modulo n 10) n) [((or 1 2 3) (? teen?)) 'th] [(1 _) 'st] [(2 _) 'nd] [(3 _) 'rd] [(_ _) 'th])))   (for ((range (list (in-range 26) (in-range 250 266) (in-range 1000 1026)))) (displayln (string-join (for...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Rust
Rust
fn main() { let mut solutions = Vec::new();   for num in 1..5_000 { let power_sum = num.to_string() .chars() .map(|c| { let digit = c.to_digit(10).unwrap(); (digit as f64).powi(digit as i32) as usize }) .sum::<usize>();   ...
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Scala
Scala
  object Munch { def main(args: Array[String]): Unit = { import scala.math.pow (1 to 5000).foreach { i => if (i == (i.toString.toCharArray.map(d => pow(d.asDigit,d.asDigit))).sum) println( i + " (munchausen)") } } }  
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#MAD
MAD
NORMAL MODE IS INTEGER   R SET UP STACK SPACE   DIMENSION STACK(100) SET LIST TO STACK   R DEFINE RECURSIVE FUNCTIONS R INPUT ARGUMENT ASSUMED TO BE IN N   INTERNAL FUNCTION(DUMMY) ENTRY TO FREC. WHENEVER N.L...
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#Factor
Factor
USING: kernel math math.functions random sequences ;   : limit ( -- n ) 2 32 ^ ; inline : in-circle ( x y -- ? ) limit [ sq ] tri@ [ + ] [ <= ] bi* ; : rand ( -- r ) limit random ; : pi ( n -- pi ) [ [ drop rand rand in-circle ] count ] keep / 4 * >float ;
http://rosettacode.org/wiki/Monte_Carlo_methods
Monte Carlo methods
A Monte Carlo Simulation is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." A simple Monte Carlo Simulation can be used to calculate the value for π {\...
#Fantom
Fantom
  class MontyCarlo { // assume square/circle of width 1 unit static Float findPi (Int samples) { Int insideCircle := 0 samples.times { x := Float.random y := Float.random if ((x*x + y*y).sqrt <= 1.0f) insideCircle += 1 } return insideCircle * 4.0f / samples }   public st...
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Raku
Raku
sub encode ( Str $word ) { my @sym = 'a' .. 'z'; gather for $word.comb -> $c { die "Symbol '$c' not found in @sym" if $c eq @sym.none; @sym[0 .. take (@sym ... $c).end] .= rotate(-1); } }   sub decode ( @enc ) { my @sym = 'a' .. 'z'; [~] gather for @enc -> $pos { take @sym[$pos]; ...
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#Delphi
Delphi
  program Morse;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.Generics.Collections, SysUtils, Windows;   const Codes: array[0..35, 0..1] of string = (('a', '.- '), ('b', '-... '), ('c', '-.-. '), ('d', '-.. '), ('e', '. '), ('f', '..-. '), ('g', '--. '), ('h', '.... '), ('i', '.. '), ('j'...
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#ColdFusion
ColdFusion
<cfscript> function runmontyhall(num_tests) { // number of wins when player switches after original selection switch_wins = 0; // number of wins when players "sticks" with original selection stick_wins = 0; // run all the tests for(i=1;i<=num_tests;i++) { // unconditioned potential for selection of each...
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Forth
Forth
  : invmod { a m | v b c -- inv } m to v 1 to c 0 to b begin a while v a / >r c b s>d c s>d r@ 1 m*/ d- d>s to c to b a v s>d a s>d r> 1 m*/ d- d>s to a to v repeat b m mod dup to b 0< if m b + else b then ;  
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#FreeBASIC
FreeBASIC
' version 10-07-2018 ' compile with: fbc -s console   Type ext_euclid Dim As Integer a, b End Type   ' "Table method" aka "The Magic Box" Function magic_box(x As Integer, y As Integer) As ext_euclid   Dim As Integer a(1 To 128), b(1 To 128), d(1 To 128), k(1 To 128)   a(1) = 1 : b(1) = 0 : d(1) = x a(2)...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Bracmat
Bracmat
( multiplicationTable = high i j row row2 matrix padFnc tmp , celPad leftCelPad padFnc celDashes leftDashes .  !arg:?high & ( padFnc = L i w d . @(!arg:? [?L) & 1+(!L:?i):?L & " ":?w & "-":?d & whl ' ( !i+-1:~...
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Multifactorial[n_, d_] := Product[x, {x, n, 1, -d}] Table[Multifactorial[j, i], {i, 5}, {j, 10}]//TableForm