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/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#jq
jq
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def motzkin: . as $n | reduce range(2; $n+1) as $i ( {m: [1,1]}; .m[$i] = (.m[$i-1] * (2*$i + 1) + .m[$i-2] * (3*$i -3))/($i + 2)) | .m ;     " n M[n] Prime?", "------------------------------",   (41 | motzkin |...
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Julia
Julia
using Primes   function motzkin(N) m = zeros(Int, N) m[1] = m[2] = 1 for i in 3:N m[i] = (m[i - 1] * (2i - 1) + m[i - 2] * (3i - 6)) ÷ (i + 1) end return m end   println(" n M[n] Prime?\n-----------------------------------") for (i, m) in enumerate(motzkin(42)) println(...
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Table[With[{o = Hypergeometric2F1[(1 - n)/2, -n/2, 2, 4]}, {n, o, PrimeQ[o]}], {n, 0, 41}] // Grid
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...
#Elixir
Elixir
defmodule MoveToFront do @table Enum.to_list(?a..?z)   def encode(text), do: encode(to_char_list(text), @table, [])   defp encode([], _, output), do: Enum.reverse(output) defp encode([h|t], table, output) do i = Enum.find_index(table, &(&1 == h)) encode(t, move2front(table, i), [i | output]) 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...
#F.23
F#
  // Move-to-front algorithm . Nigel Galloway: March 1st., 2021 let fN g=List.permute(fun n->match compare n g with 0->0 |1->n |_->n+1) let decode n=let rec fG n g=[|match n with n::t->yield List.item n g; yield! fG t (fN n g)|_->()|] in fG n ['a'..'z']|>System.String let encode n=let rec fG n g=[match n with n::t->let...
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#C.2B.2B
C++
#include <cmath> #include <iostream> #include <string>   using namespace std;   // Use a struct as the monad struct LoggingMonad { double Value; string Log; };   // Use the >> operator as the bind function auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingM...
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#C.2B.2B
C++
#include <iostream> #include <vector>   using namespace std;   // std::vector can be a list monad. Use the >> operator as the bind function template <typename T> auto operator>>(const vector<T>& monad, auto f) { // Declare a vector of the same type that the function f returns vector<remove_reference_t<decltype...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#jq
jq
# The input is used to initialize the elements of the # multi-dimensional array: def multiarray(d): . as $in | if (d|length) == 1 then [range(0;d[0]) | $in] else multiarray(d[1:]) | multiarray( d[0:1] ) end;
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Julia
Julia
  julia> a4d = rand(Int, 5, 4, 3, 2) 5×4×3×2 Array{Int64,4}: [:, :, 1, 1] = -4071410509370082480 -361121233222804742 6884099527706004770 -3207257047234122321 8613938183523990915 -6284413064884272355 2092274063225757339 2883192477194384468 8063489472918692884 7817079491035828713 4371491775271354348 ...
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.
#8080_Assembly
8080 Assembly
org 100h lxi h,output ;;; Make the header call skip ; Four spaces, mvi m,'|' ; separator, inx h lxi d,0C01h ; 12 fields starting at 1 fnum: mov a,e ; Field number call num inr e dcr d ; If not 12 yet, next field number jnz fnum call nl ; Newline mvi a,'-' ; Four dashes, mvi b,4 call bchr mvi m,'+' ; P...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Hy
Hy
(import [numpy [ones column-stack]] [numpy.random [randn]] [numpy.linalg [lstsq]])   (setv n 1000) (setv x1 (randn n)) (setv x2 (randn n)) (setv y (+ 3 (* 1 x1) (* -2 x2) (* .25 x1 x2) (randn n)))   (print (first (lstsq (column-stack (, (ones n) x1 x2 (* x1 x2))) y)))
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#J
J
NB. Wikipedia data x=: 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 y=: 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 74.46   y %. x ^/ i.3 NB. calculate coefficients b1, b2 and b3 for 2nd degree polynomial 128.813 _143.162 61.9603
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)(...
#CLU
CLU
multifactorial = proc (n, degree: int) returns (int) result: int := 1 for i: int in int$from_to_by(n, 1, -degree) do result := result * i end return (result) end multifactorial   start_up = proc () po: stream := stream$primary_output() for n: int in int$from_to(1, 10) do for d: 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.
#Emacs_Lisp
Emacs Lisp
(mouse-pixel-position) ;; => (FRAME . (X . 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.
#ERRE
ERRE
  ! ! MOUSE WITH 'MOUSE.LIB' LIBRARY !   PROGRAM MOUSE   !$KEY   !$INCLUDE="PC.LIB"   !$INCLUDE="MOUSE.LIB"   PROCEDURE GETMONITORTYPE(->MONITOR$)  !$RCODE="DEF SEG=0" STATUS=PEEK($463)  !$RCODE="DEF SEG" MONITOR$="" IF STATUS=$B4 THEN  !$RCODE="STATUS=(INP(&H3BA) AND &H80)" ...
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.
#F.23
F#
open System.Windows.Forms open System.Runtime.InteropServices   #nowarn "9" [<Struct; StructLayout(LayoutKind.Sequential)>] type POINT = new (x, y) = { X = x; Y = y } val X : int val Y : int   [<DllImport("user32.dll")>] extern nativeint GetForegroundWindow(); [<DllImport("user32.dll", CharSet=CharSet.Auto,...
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...
#Forth
Forth
variable solutions variable nodes   : bits ( n -- mask ) 1 swap lshift 1- ; : lowBit ( mask -- bit ) dup negate and ; : lowBit- ( mask -- bits ) dup 1- and ;   : next3 ( dl dr f files -- dl dr f dl' dr' f' ) invert >r 2 pick r@ and 2* 1+ 2 pick r@ and 2/ 2 pick r> and ;   : try ( dl dr f -- ) dup if 1 no...
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Tcl
Tcl
package require Tcl 8.5 package require struct::list   proc multOrder {a m} { assert {[gcd $a $m] == 1} set mofs [list] dict for {p e} [factor_num $m] { lappend mofs [multOrdr1 $a $p $e] } return [struct::list fold $mofs 1 lcm] }   proc multOrdr1 {a p e} { set m [expr {$p ** $e}] set...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Scheme
Scheme
(define (root number degree tolerance) (define (good-enough? next guess) (< (abs (- next guess)) tolerance)) (define (improve guess) (/ (+ (* (- degree 1) guess) (/ number (expt guess (- degree 1)))) degree)) (define (*root guess) (let ((next (improve guess))) (if (good-enough? next guess) ...
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...
#Microsoft_Small_Basic
Microsoft Small Basic
  loLim = 0 hiLim = 25 PrintImages() loLim = 250 hiLim = 265 PrintImages() loLim = 1000 hiLim = 1025 PrintImages()   Sub PrintImages For i = loLim To hiLim nr = i GetSuffix() TextWindow.Write(i + suffix + " ") EndFor TextWindow.WriteLine("") EndSub   Sub GetSuffix rem10 = Math.Remainder(nr, 10) ...
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 ...
#Maple
Maple
isMunchausen := proc(n::posint) local num_digits; num_digits := map(x -> StringTools:-Ord(x) - 48, StringTools:-Explode(convert(n, string))); return evalb(n = convert(map(x -> x^x, num_digits), `+`)); end proc;   Munchausen_upto := proc(n::posint) local k, count, list_num; list_num := []; for k to n do if is...
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 ) ) , ...
#Go
Go
package main import "fmt"   func F(n int) int { if n == 0 { return 1 } return n - M(F(n-1)) }   func M(n int) int { if n == 0 { return 0 } return n - F(M(n-1)) }   func main() { for i := 0; i < 20; i++ { fmt.Printf("%2d ", F(i)) } fmt.Println() for i := 0; i < 20; i++ { fmt.Printf("%2d ", M(i)) ...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Phix
Phix
with javascript_semantics sequence s = repeat("x",6) ?s s[$] = 5 ?s s[1] &= 'y' ?s -- s[2] = s  ?s s[2] = deep_copy(s) ?s
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#PicoLisp
PicoLisp
: (make (do 5 (link (new)))) -> ($384717187 $384717189 $384717191 $384717193 $384717195)
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#PowerShell
PowerShell
  1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} | Select-Object -Unique | ForEach-Object {$_.ToString()}  
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Nim
Nim
import strformat, strutils   func isPrime(n: Positive): bool = if n == 1: return false if (n and 1) == 0: return n == 2 if n mod 3 == 0: return n == 3 var d = 5 while d * d <= n: if n mod d == 0: return false inc d, 2 if n mod d == 0: return false inc d, 4 result = true   func motzkin(n: Pos...
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#PARI.2FGP
PARI/GP
  M=vector(41) M[1]=1 M[2]=2 for(n=3, 41, M[n]=(M[n-1]*(2*n+1) + M[n-2]*(3*n-3))/(n+2)) M=concat([1], M) for(n=1, 42, print(M[n]," ",isprime(M[n])))  
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 ...
#ALGOL_68
ALGOL 68
BEGIN   # This is a translation of the Javascript sample, main differences are because Algol 68 # # is strongly typed and "on-the-fly" constructon of functions is not really possible - # # we need to define a STRUCT where Javascript would just construct a new function. # # As Algol 68 doe...
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...
#Factor
Factor
USING: formatting kernel locals make sequences ;   : to-front ( elt seq -- seq' ) over [ remove ] dip prefix ;   : encode ( symbols msg -- indices ) [ [ swap 2dup index , to-front ] each ] { } make nip ;   : decode ( symbols indices -- msg ) [ [ swap [ nth ] keep over , to-front ] each ] "" make nip ;   :: roun...
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...
#FreeBASIC
FreeBASIC
#define FAIL -1   sub mtf( s() as string, i as uinteger ) 'moves the symbol at index i to the front and shifts preceding ones back dim as string*1 t = s(i) for j as uinteger = i to 1 step -1 s(j) = s(j-1) next j s(0)=t end sub   sub make_symbols( s() as string ) 'populates an array of st...
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#EchoLisp
EchoLisp
  (define (Writer.unit x (log #f)) (if log (cons log x) (cons (format "init → %d" x) x)))   ;; f is a lisp function ;; (Writer.lift f) returns a Writer function which returns a Writer element   (define (Writer.lift f name) (lambda(elem) (Writer.unit (f (rest elem)) ...
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Clojure
Clojure
  (defn bind [coll f] (apply vector (mapcat f coll))) (defn unit [val] (vector val))   (defn doubler [n] [(* 2 n)]) ; takes a number and returns a List number (def vecstr (comp vector str)) ; takes a number and returns a List string   (bind (bind (vector 3 4 5) doubler) vecstr) ; evaluates to ["6" "8" "10"] (-> [3 4 ...
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Delphi
Delphi
  program List_monad;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TmList = record Value: TArray<Integer>; function ToString: string; function Bind(f: TFunc<TArray<Integer>, TmList>): TmList; end;   function Create(aValue: TArray<Integer>): TmList; begin Result.Value := copy(aValue, 0, length...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Klingphix
Klingphix
include ..\Utilitys.tlhy   0 ( 4 3 2 ) dim pstack   5432 ( 4 3 2 ) set pstack   ( 4 3 2 ) get ?   ( 4 3 ) get %row !row $row ?   $row 1 2 set !row $row ?   $row ( 4 3 ) set 0 4 repeat ( 4 2 ) set   pstack   "End " input
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { // create a regular 4 dimensional array and initialize successive elements to the values 1 to 120 var m = 1 val a4 = Array<Array<Array<Array<Int>>>>(5) { Array<Array<Array<Int>>>(4) { Array<Array<Int>>(3) { Array<Int>(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.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program multtable64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Java
Java
import java.util.Arrays; import java.util.Objects;   public class MultipleRegression { public static void require(boolean condition, String message) { if (condition) { return; } throw new IllegalArgumentException(message); }   public static class Matrix { private ...
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)(...
#Common_Lisp
Common Lisp
  (defun mfac (n m) (reduce #'* (loop for i from n downto 1 by m collect i)))   (loop for i from 1 to 10 do (format t "~2@a: ~{~a~^ ~}~%" i (loop for j from 1 to 10 collect (mfac j 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.
#Factor
Factor
: replace-text ( button text -- ) [ drop children>> pop drop ] [ >label add-gadget drop ] 2bi ; : present-locations ( loc1 loc2 -- string ) [ first2 [ number>string ] bi@ "," glue ] bi@ ";" glue ; : example ( -- ) "click me" [ dup hand-rel ! location relative to the button hand-loc get ! locat...
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.
#FreeBASIC
FreeBASIC
  type MOUSE 'mouse position, button state, wheel state x as integer y as integer buttons as integer wheel as integer end type   screen 12   dim as MOUSE mouse   while inkey="" locate 1,1 getmouse(mouse.x, mouse.y, mouse.wheel, mouse.buttons) if mouse.x < 0 then print "Mouse out of wi...
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...
#Fortran
Fortran
program Nqueens implicit none   integer, parameter :: n = 8 ! size of board integer :: file = 1, rank = 1, queens = 0 integer :: i logical :: board(n,n) = .false.   do while (queens < n) board(file, rank) = .true. if(is_safe(board, file, rank)) then queens = queens + 1 file = 1 ra...
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics Imports System.Runtime.CompilerServices Imports System.Threading   Module Module1 Private s_gen As New ThreadLocal(Of Random)(Function() New Random())   Private Function Gen() Return s_gen.Value End Function   <Extension()> Public Function IsProbablyPrime(value As Big...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Seed7
Seed7
const func float: nthRoot (in integer: n, in float: a) is func result var float: x1 is 0.0; local var float: x0 is 0.0; begin x0 := a; x1 := a / flt(n); while abs(x1 - x0) >= abs(x0 * 1.0E-9) do x0 := x1; x1 := (flt(pred(n)) * x0 + a / x0 ** pred(n)) / flt(n); end while; end...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Sidef
Sidef
func nthroot(n, a, precision=1e-5) { var x = 1.float var prev = 0.float while ((prev-x).abs > precision) { prev = x; x = (((n-1)*prev + a/(prev**(n-1))) / n) } return x }   say nthroot(5, 34) # => 2.024397458501034082599817835297912829678314204
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...
#MiniScript
MiniScript
ordinal = function(n) if n > 3 and n < 20 then return n + "th" if n % 10 == 1 then return n + "st" if n % 10 == 2 then return n + "nd" if n % 10 == 3 then return n + "rd" return n + "th" end function   out = [] test = function(from, to) for i in range(from, to) out.push ordinal(i) en...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Off[Power::indet];(*Supress 0^0 warnings*) Select[Range[5000], Total[IntegerDigits[#]^IntegerDigits[#]] == # &]
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 ...
#min
min
(dup string "" split (int dup pow) (+) map-reduce ==) :munchausen? 1 :i (i 5000 <=) ((i munchausen?) (i puts!) when i succ @i) while
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 ) ) , ...
#Groovy
Groovy
def f, m // recursive closures must be declared before they are defined f = { n -> n == 0 ? 1 : n - m(f(n-1)) } m = { n -> n == 0 ? 0 : n - f(m(n-1)) }
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#PureBasic
PureBasic
n=Random(50)+25 Dim A.i(n) ; Creates a Array of n [25-75] elements depending on the outcome of Random(). ; Each element will be initiated to zero.   For i=0 To ArraySize(A()) A(i)=2*i Next i ; Set each individual element at a wanted (here 2*i) value and ; automatically adjust accordingly to the unknown length of t...
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Python
Python
[Foo()] * n # here Foo() can be any expression that returns a new object
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Motzkin_numbers use warnings; use ntheory qw( is_prime );   sub motzkin { my $N = shift; my @m = ( 0, 1, 1 ); for my $i ( 3 .. $N ) { $m[$i] = ($m[$i - 1] * (2 * $i - 1) + $m[$i - 2] * (3 * $i - 6)) / ($i + 1); } return splice @m, 1; }...
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Phix
Phix
with javascript_semantics include mpfr.e function motzkin(integer n) sequence m = mpz_inits(2,1) -- {1,1} mpz m2 = mpz_init() -- (scratch) for i=3 to n do mpz m1 = mpz_init() -- (a new mpz rqd for every m[i]) mpz_mul_si(m1,m[i-1],2*i-1) -- (nb i is 1-based) mpz_mul_si...
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 ...
#AppleScript
AppleScript
property e : 2.71828182846   on run {}   -- Derive safe versions of three simple functions set sfReciprocal to safeVersion(reciprocal, notZero) set sfRoot to safeVersion(root, isPositive) set sfLog to safeVersion(ln, aboveZero)     -- Test a composition of these function with a range of invalid and ...
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...
#Gambas
Gambas
Public Sub Main() Dim sToCode As String[] = ["broood", "bananaaa", "hiphophiphop"] 'Samples to process Dim sHold As New String[] 'To store results Dim siCount, siCounter, siPos As Short 'Various variables Dim sOutput, sCode, sWork, sEach As String ...
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...
#11l
11l
F mul_inv(=a, =b) V b0 = b V x0 = 0 V x1 = 1 I b == 1 {R 1}   L a > 1 V q = a I/ b (a, b) = (b, a % b) (x0, x1) = (x1 - q * x0, x0)   I x1 < 0 {x1 += b0} R x1   print(mul_inv(42, 2017))
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#Factor
Factor
USING: kernel math math.functions monads prettyprint ; FROM: monads => do ;   { [ 5 "Started with five, " <writer> ] [ sqrt "took square root, " <writer> ] [ 1 + "added one, " <writer> ] [ 2 / "divided by two." <writer> ] } do .
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#Go
Go
package main   import ( "fmt" "math" )   type mwriter struct { value float64 log string }   func (m mwriter) bind(f func(v float64) mwriter) mwriter { n := f(m.value) n.log = m.log + n.log return n }   func unit(v float64, s string) mwriter { return mwriter{v, fmt.Sprintf("  %-17s: %g\...
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#EchoLisp
EchoLisp
  ;; -> and ->> are the pipeline operators ;; (-> x f g h) = (h (g ( f x))) ;; (->> x f (g a) h) = (h (g a ( f x)))   (define (List.unit elem) (append '(List) elem)) (define (List.bind xs f) (List.unit (->> xs rest (map f) (map rest) (apply append)))) (define (List.lift f) (lambda(elem) (List.unit (f elem))))   ...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Lingo
Lingo
on array () cnt = paramCount() if cnt=0 then return arr = [] arr[param(cnt)] = 0 repeat with d = cnt-1 down to 1 newArr = [] repeat with i = 1 to param(d) newArr[i] = arr.duplicate() -- duplicate does a deep copy end repeat arr = newArr.duplicate() end...
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Lua
Lua
-- Variadic, first argument is the value with which to populate the array. function multiArray (initVal, ...) local function copy (t) local new = {} for k, v in pairs(t) do if type(v) == "table" then new[k] = copy(v) else new[k] = v ...
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.
#Action.21
Action!
PROC PrintRight(BYTE num,size) BYTE i   IF num<10 THEN size==-1 ELSEIF num<100 THEN size==-2 ELSE size==-3 FI FOR i=1 TO size DO Put(' ) OD PrintB(num) RETURN   PROC Main() BYTE ARRAY colw=[1 1 1 2 2 2 2 2 2 3 3 3] BYTE i,j,x,w    ;clear screen Put(125)    ;draw frame Positio...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#JavaScript
JavaScript
// modifies the matrix "in place" Matrix.prototype.inverse = function() { if (this.height != this.width) { throw "can't invert a non-square matrix"; }   var I = new IdentityMatrix(this.height); for (var i = 0; i < this.height; i++) this.mtx[i] = this.mtx[i].concat(I.mtx[i]) this....
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)(...
#Crystal
Crystal
def multifact(n, d) n.step(to: 1, by: -d).product end   (1..5).each {|d| puts "Degree #{d}: #{(1..10).map{|n| multifact(n, d)}.join "\t"}"}
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.
#Gambas
Gambas
  PUBLIC SUB Form1_MouseMove() PRINT mouse.X PRINT Mouse.Y 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.
#Go
Go
package main   import ( "fmt" "github.com/go-vgo/robotgo" )   func isInside(x, y, w, h, mx, my int) bool { rx := x + w - 1 ry := y + h - 1 return mx >= x && mx <= rx && my >= y && my <= ry }   func main() { name := "gedit" // say fpid, err := robotgo.FindIds(name) if err == nil && len(fp...
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...
#FreeBASIC
FreeBASIC
' version 13-04-2017 ' compile with: fbc -s console Dim Shared As ULong count, c()   Sub n_queens(row As ULong, n As ULong, show As ULong = 0)   Dim As ULong x, y   For x = 1 To n   For y = 1 To row -1 If c(y) = x OrElse ((row - y) - Abs(x - c(y))) = 0 Then Continue For, For ...
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Wren
Wren
import "/big" for BigInt   class PExp { construct new(prime, exp) { _prime = prime _exp = exp } prime { _prime } exp { _exp } }   var moBachShallit58 = Fn.new { |a, n, pf| var n1 = n - BigInt.one var mo = BigInt.one for (pe in pf) { var y = n1 / pe.prime.pow(pe.exp)...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Smalltalk
Smalltalk
Number extend [ nthRoot: n [ |x0 m x1| x0 := (self / n) asFloatD. m := n - 1. [true] whileTrue: [ x1 := ( (m * x0) + (self/(x0 raisedTo: m))) / n. ((x1 - x0) abs) < ((x0 * 1e-9) abs) ifTrue: [ ^ x1 ]. x0 := x1 ] ] ].
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...
#Modula-2
Modula-2
  MODULE Nth;   FROM STextIO IMPORT WriteString, WriteLn; FROM WholeStr IMPORT IntToStr;   PROCEDURE Suffix(N: CARDINAL; VAR OUT Destination: ARRAY OF CHAR); VAR NMod10, NMod100: CARDINAL; BEGIN NMod10 := N MOD 10; NMod100 := N MOD 100; IF (NMod10 = 1) AND (NMod100 <> 11) THEN Destination := "st"; ELS...
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 ...
#Modula-2
Modula-2
MODULE MunchausenNumbers; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   (* Simple power function, does not handle negatives *) PROCEDURE Pow(b,e : INTEGER) : INTEGER; VAR result : INTEGER; BEGIN IF e=0 THEN RETURN 1; END; IF b=0 THEN RETURN 0; END;  ...
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 ) ) , ...
#Haskell
Haskell
f 0 = 1 f n | n > 0 = n - m (f $ n-1)   m 0 = 0 m n | n > 0 = n - f (m $ n-1)   main = do print $ map f [0..19] print $ map m [0..19]
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#R
R
rep(foo(), n) # foo() is any code returning a value
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Racket
Racket
  #lang racket   ;; a list of 10 references to the same vector (make-list 10 (make-vector 10 0))   ;; a list of 10 distinct vectors (build-list 10 (λ (n) (make-vector 10 0)))  
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#Raku
Raku
my @a = Foo.new xx $n;
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#REXX
REXX
/*REXX program does a list comprehension that will create N random integers, all unique.*/ parse arg n lim . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 1000 /*Not specified? Then use the default.*/ if lim=='' | lim=="," then lim= 100000 ...
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Quackery
Quackery
' [ 1 1 ] 41 times [ dup -2 split nip do i^ 2 + 2 * 1 - * swap i^ 2 + 3 * 6 - * + i^ 3 + / join ] behead drop witheach [ i^ echo sp dup echo isprime if [ say " prime" ] cr ]
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Raku
Raku
use Lingua::EN::Numbers;   constant \C = 1, |[\×] (2, 6 … ∞) Z/ 2 .. *;   sub binomial { [×] ($^n … 0) Z/ 1 .. $^p }   my \𝐌 = 1, |(1..∞).map: -> \𝐧 { sum ^𝐧 .map( -> \𝐤 { C[𝐤] × binomial 𝐧, 2×𝐤 } ) };   say " 𝐧 𝐌[𝐧] Prime?"; 𝐌[^42].kv.map: { printf "%2d %24s  %s\n", $^k, $^v.&comma, $v.i...
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 ...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <stdbool.h>   typedef enum type { INT, STRING } Type;   typedef struct maybe { int i; char *s; Type t; _Bool is_something; } Maybe;   void print_Maybe(Maybe *m) { if (m->t == INT) printf("Just %d : INT\n", m->i);   else if (m->t == STRING) printf...
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...
#Go
Go
package main   import ( "bytes" "fmt" )   type symbolTable string   func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) for i, c := range []byte(s) { x := bytes.IndexByte(pad, c) seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } return seq }   func (...
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...
#8th
8th
  \ return "extended gcd" of a and b; The result satisfies the equation: \ a*x + b*y = gcd(a,b) : n:xgcd \ a b -- gcd x y dup 0 n:= if 1 swap \ -- a 1 0 else tuck n:/mod -rot recurse tuck 4 roll n:* n:neg n:+ then ;   \ Return modular inverse of n modulo mod, or null if it does...
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...
#Action.21
Action!
INT FUNC ModInverse(INT a,b) INT t,nt,r,nr,q,tmp   IF b<0 THEN b=-b FI IF a<0 THEN a=b-(-a MOD b) FI t=0 nt=1 r=b nr=a MOD 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 RETURN (-1) FI IF t<0 THEN t==+b FI RETURN (t)   PROC Test(INT a,b) ...
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#Haskell
Haskell
import Control.Monad.Trans.Writer import Control.Monad ((>=>))   loggingVersion :: (a -> b) -> c -> a -> Writer c b loggingVersion f log x = writer (f x, log)   logRoot = loggingVersion sqrt "obtained square root, " logAddOne = loggingVersion (+1) "added 1, " logHalf = loggingVersion (/2) "divided by 2, "   halfOfAddOn...
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#J
J
root=: %: incr=: >: half=: -:   tostr=: ,@":   loggingVersion=: conjunction define n;~u )   Lroot=: root loggingVersion 'obtained square root' Lincr=: incr loggingVersion 'added 1' Lhalf=: half loggingVersion 'divided by 2'   loggingUnit=: verb define y;'Initial value: ',tostr y )   loggingBind=: adverb define r=...
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#F.23
F#
  type ListMonad() = member o.Bind( (m:'a list), (f: 'a -> 'b list) ) = List.concat( List.map f m ) member o.Return(x) = [x] member o.Zero() = []   let list = ListMonad()   let pyth_triples n = list { let! x = [1..n] let! y = [x..n] let! z = [y..n] ...
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Factor
Factor
USING: kernel math monads prettyprint ; FROM: monads => do ;   { 3 4 5 } >>= [ 1 + array-monad return ] swap call >>= [ 2 * array-monad return ] swap call .
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a = ConstantArray[0, {2, 3, 4, 5}] a[[1, 2, 3, 4]] = 15; a[[1, 2, 3, 4]] a a[[2, 2]] = 8; a
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Nim
Nim
import arraymancer   let c = [ [ [1,2,3], [4,5,6] ], [ [11,22,33], [44,55,66] ], [ [111,222,333], [444,555,666] ], [ [1111,2222,3333], [4444,5555,6666] ...
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.
#ActionScript
ActionScript
  package {   import flash.display.Sprite; import flash.events.Event; import flash.text.TextField; import flash.text.TextFieldAutoSize; import flash.text.TextFormat;   [SWF (width = 550, height = 550)] public class MultiplicationTable extends Sprite {   public function Multiplication...
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#jq
jq
def dot_product(a; b): reduce range(0;a|length) as $i (0; . + (a[$i] * b[$i]) );   # A and B should both be numeric matrices, A being m by n, and B being n by p. def multiply(A; B): (B[0]|length) as $p | (B|transpose) as $BT | reduce range(0; A|length) as $i ([]; reduce range(0; $p) as $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 , . . . , ...
#Julia
Julia
x = [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] y = [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, 74.46] X = [x.^0 x.^1 x.^2]; b = X \ y
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)(...
#D
D
import std.stdio, std.algorithm, std.range;   T multifactorial(T=long)(in int n, in int m) pure /*nothrow*/ { T one = 1; return reduce!q{a * b}(one, iota(n, 0, -m)); }   void main() { foreach (immutable m; 1 .. 11) writefln("%2d: %s", m, iota(1, 11) .map!(n => multifac...
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.
#Groovy
Groovy
1.upto(5) { Thread.sleep(1000) def p = java.awt.MouseInfo.pointerInfo.location println "${it}: x=${p.@x} y=${p.@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.
#HicEst
HicEst
WINDOW(WINdowhandle=handle) AXIS(WINdowhandle=handle, MouSeCall=Mouse_Callback, MouSeX=X, MouSeY=Y) END   SUBROUTINE Mouse_Callback() WRITE(Messagebox, Name) X, Y END
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...
#Frink
Frink
solution[board] := { for q = 0 to length[board] - 1 for c = q+1 to length[board] - 1 if board@q == board@c + (c - q) or board@q == board@c - (c - q) return false return true }   for b = array[1 to 8].permute[] if solution[b] println[b]
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#zkl
zkl
var BN =Import("zklBigNum"); var Sieve=Import("sieve");   // factor n into powers of primes // eg 9090 == 2^1 * 3^2 * 5^1 * 101^1 fcn factor2PP(n){ // lazy factors using lazy primes --> (prime,power) ... Utils.Generator(fcn(a){ primes:=Utils.Generator(Sieve.postponed_sieve); foreach p in (prime...
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#SPL
SPL
nthr(n,r) <= n^(1/r)   nthroot(n,r)= a = n/r g = n > g!=a g = a a = (1/r)*(((r-1)*g)+(n/(g^(r-1)))) < <= a .   #.output(nthr(2,2)) #.output(nthroot(2,2))
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Swift
Swift
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1)   for _ in 0..<e { res *= self }   return res }   @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) ...
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...
#Nanoquery
Nanoquery
def ordinalAbbrev(n) if int(n % 100 / 10) = 1 return "th" end   if n % 10 = 1 return "st" else if n % 10 = 2 return "nd" else if n % 10 = 3 return "rd" else return "th" end end   for i...
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 ...
#Nim
Nim
import math   for i in 1..<5000: var sum: int64 = 0 var number = i while number > 0: var digit = number mod 10 sum += digit ^ digit number = number div 10 if sum == i: echo i
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 ) ) , ...
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) every write(F(!arglist)) # F of all arguments end   procedure F(n) if integer(n) >= 0 then return (n = 0, 1) | n - M(F(n-1)) end   procedure M(n) if integer(n) >= 0 then return (0 = n) | n - F(M(n-1)) end