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/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.
| #MiniScript | MiniScript | print mouse.x, 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.
| #Nanoquery | Nanoquery | import Nanoquery.Util.Windows
// a function to handle the mouse moved event
def mouse_moved($caller, $e)
println "(" + $e.getX() + ", " + $e.getY() + ")"
end
// create a window, set the handler for mouse moved, and show it
w = new("Window")
w.setSize(500, 500)
w.setHandler(w.mouseMoved, mouse_moved)
w.show() |
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... | #IS-BASIC | IS-BASIC | 100 PROGRAM "NQueens.bas"
110 TEXT 80
120 DO
130 INPUT PROMPT "Size of board (2-12): ":N$
140 LET N=VAL(N$)
150 LOOP UNTIL N>1 AND N<13
160 NUMERIC A(1 TO N),X(1 TO N),B(2 TO 2*N),C(-N+1 TO N-1)
170 LET SOL=0
180 CALL INIT(A):CALL INIT(B):CALL INIT(C)
190 CALL TRY(1)
200 PRINT SOL;"solutions."
210 END
220 DEF WRITE... |
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... | #Phix | Phix | constant ordinals = {"th","st","nd","rd"}
function Nth(integer n, bool apostrophe=false)
integer mod10 = mod(n,10)+1
if mod10>4 or mod(n,100)=mod10+9 then mod10 = 1 end if
return sprintf("%d%s",{n,repeat('\'',apostrophe)&ordinals[mod10]})
end function
constant ranges = {{0,25},{250,265},{1000,1025}}
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 ... | #Plain_English | Plain English | To run:
Start up.
Show the Munchausen numbers up to 5000.
Wait for the escape key.
Shut down.
To show the Munchausen numbers up to a number:
If a counter is past the number, exit.
If the counter is Munchausen, convert the counter to a string; write the string to the console.
Repeat.
To decide if a number is Munchau... |
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
)
)
,
... | #Julia | Julia | F(n) = n < 1 ? one(n) : n - M(F(n - 1))
M(n) = n < 1 ? zero(n) : n - F(M(n - 1)) |
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 ... | #Julia | Julia | struct maybe x::Union{Real, Missing}; end
Base.show(io::IO, m::maybe) = print(io, m.x)
unit(x) = maybe(x)
bind(f, x) = unit(f(x.x))
f1(x) = 5x
f2(x) = x + 4
a = unit(3)
b = unit(missing)
println(a, " -> ", bind(f2, bind(f1, a)))
println(b, " -> ", bind(f2, bind(f1, b)))
|
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 ... | #Kotlin | Kotlin | // version 1.2.10
import java.util.Optional
/* doubles 'i' before wrapping it */
fun getOptionalInt(i: Int) = Optional.of(2 * i)
/* returns an 'A' repeated 'i' times wrapped in an Optional<String> */
fun getOptionalString(i: Int) = Optional.of("A".repeat(i))
/* does same as above if i > 0, otherwise returns an ... |
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
π
{\... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double pi(double tolerance)
{
double x, y, val, error;
unsigned long sampled = 0, hit = 0, i;
do {
/* don't check error every turn, make loop tight */
for (i = 1000000; i; i--, sampled++) {
x = rand() / (RAND_MAX + 1.0);
y = rand() / (RAND_MAX + ... |
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... | #MATLAB | MATLAB | function testMTF
symTable = 'abcdefghijklmnopqrstuvwxyz';
inStr = {'broood' 'bananaaa' 'hiphophiphop'};
for k = 1:length(inStr)
outArr = encodeMTF(inStr{k}, symTable);
outStr = decodeMTF(outArr, symTable);
fprintf('%s: [ %s]\n', inStr{k}, sprintf('%d ', outArr))
fprintf('%sco... |
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... | #AWK | AWK | # usage: awk -f morse.awk [inputfile]
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. ";
}
{ for(i=1; i<=NF; i++)
{
c=toupper($i); n=1; b=".";
while((c!=b)&&(b!=" ")) { b=substr(m,n,1); n++; }
b=substr(m,n,1);
... |
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... | #AutoHotkey | AutoHotkey | #SingleInstance, Force
Iterations = 1000
Loop, %Iterations%
{
If Monty_Hall(1)
Correct_Change++
Else
Incorrect_Change++
If Monty_Hall(2)
Correct_Random++
Else
Incorrect_Random++
If Monty_Hall(3)
Correct_Stay++
Else
Incorrect_Stay++
}
Percent_Change := round(Correct_... |
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... | #C.2B.2B | C++ | #include <iostream>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
std::cout << mul_inv(42, 2017) << std::endl;
return 0... |
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... | #zkl | zkl | class Writer{
fcn init(x){ var X=x, logText=Data(Void," init \U2192; ",x.toString()) }
fcn unit(text) { logText.append(text); self }
fcn lift(f,name){ unit("\n %s \U2192; %s".fmt(name,X=f(X))) }
fcn bind(f,name){ lift.fp(f,name) }
fcn toString{ "Result = %s\n%s".fmt(X,logText.text) }
fcn root{ li... |
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... | #uBasic.2F4tH | uBasic/4tH | s := "[" : Push 5, 4, 3
Do While Used ()
y = Set (x, Pop ()) + 1
s = Join (s, Str (Set (z, y * 2)), ", " )
Loop
Print Show (Set (s, Join (Clip (s, 2), "]")))
|
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... | #Wren | Wren | class Mlist {
construct new(value) { _value = value }
value { _value }
bind(f) { f.call(_value) }
static unit(lst) { Mlist.new(lst) }
}
var increment = Fn.new { |lst|
var lst2 = lst.map { |v| v + 1 }.toList
return Mlist.unit(lst2)
}
var double = Fn.new { |lst|
var lst2 = lst.map { ... |
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.
... | #Tcl | Tcl | proc multilist {value args} {
set res $value
foreach dim [lreverse $args] {
set res [lrepeat $dim $res]
}
return $res
} |
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.
... | #Vlang | Vlang | smd := [][]string{len: 4, init: []string{len:2, init: 'Hello'}}
imd := [][]int{len: 3, init: []int{len:4, init: it}}
mut mmd := [][]f64{len: 5, init: []f64{len: 5}}
mmd[0][2] = 2.0
mmd[1][3] = 4.2
mmd[2][4] = 1.8
mmd[3][0] = 5.0
mut omd := [][]bool{} // initialize without defining size
omd << [true, false, true]
printl... |
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.
| #AutoHotkey | AutoHotkey | Gui, -MinimizeBox
Gui, Margin, 0, 0
Gui, Font, s9, Fixedsys
Gui, Add, Edit, h0 w0
Gui, Add, Edit, w432 r14 -VScroll
Gosub, Table
Gui, Show,, Multiplication Table
Return
GuiClose:
GuiEscape:
ExitApp
Return
Table:
; top row
Table := " x |"
Loop, 12
Table .= SubStr(" " A_Index, -3)
Table... |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #Raku | Raku | use Clifford;
my @height = <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>;
my @weight = <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>;
my $w = [+] @weight Z* @e;
my $h0 = [+] @e[^@weight];
my $h1 = [+] @height Z* @e;
my $h2 = [+] (@height X... |
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)(... | #Haskell | Haskell | mulfac :: (Num a, Enum a) => a -> [a]
mulfac k = 1 : s
where
s = [1 .. k] <> zipWith (*) s [k + 1 ..]
-- For single n:
mulfac1 :: (Num a, Enum a) => a -> a -> a
mulfac1 k n = product [n, n - k .. 1]
main :: IO ()
main =
mapM_
(print . take 10 . tail . mulfac)
[1 .. 5]
|
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.
| #Nim | Nim | import gintro/[glib, gobject, gtk, gio]
import gintro/gdk except Window
#---------------------------------------------------------------------------------------------------
proc onButtonPress(window: ApplicationWindow; event: Event; data: pointer): bool =
echo event.getCoords()
result = true
#----------------... |
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.
| #OCaml | OCaml | open Xlib
let () =
let d = xOpenDisplay "" in
(* ask for active window (no error check);
the client must be freedesktop compliant *)
let _, _, _, _, props =
xGetWindowProperty_window d
(xDefaultRootWindow d)
(xInternAtom d "_NET_ACTIVE_WINDOW" true)
0 1 false AnyPropertyType
... |
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... | #J | J | perm =: ! A.&i. ] NB. all permutations of integers 0 to y
comb2 =: (, #: I.@,@(</)&i.)~ NB. all size 2 combinations of integers 0 to y
mask =: [ */@:~:&(|@-/) {
queenst=: comb2 (] #"1~ mask)&.|: perm |
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... | #PHP | PHP | function nth($num) {
$os = "th";
if ($num % 100 <= 10 or $num % 100 > 20) {
switch ($num % 10) {
case 1:
$os = "st";
break;
case 2:
$os = "nd";
break;
case 3:
$os = "rd";
break;
}
}
return $num . $os;
}
foreach ([[0,25], [250,265], [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 ... | #PowerBASIC | PowerBASIC | #COMPILE EXE
#DIM ALL
#COMPILER PBCC 6
DECLARE FUNCTION GetTickCount LIB "kernel32.dll" ALIAS "GetTickCount"() AS DWORD
FUNCTION PBMAIN () AS LONG
LOCAL i, j, n, sum, ten1, ten2, t AS DWORD
LOCAL n0, n1, n2, n3, n4, n5, n6, n7, n8, n9 AS DWORD
LOCAL s1, s2, s3, s4, s5, s6, s7, s8 AS DWORD
DIM pow(9) AS DWORD, num(9... |
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
)
)
,
... | #Kotlin | Kotlin | // version 1.0.6
fun f(n: Int): Int =
when {
n == 0 -> 1
else -> n - m(f(n - 1))
}
fun m(n: Int): Int =
when {
n == 0 -> 0
else -> n - f(m(n - 1))
}
fun main(args: Array<String>) {
val n = 24
print("n :")
for (i in 0..n) print("%3d".format(i))
p... |
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 ... | #Lua | Lua |
-- None is represented by an empty table. Some is represented by any
-- array with one element. You SHOULD NOT compare maybe values with the
-- Lua operator == because it will give incorrect results. Use the
-- functions isMaybe(), isNone(), and isSome().
-- define once for efficiency, to avoid many different em... |
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
π
{\... | #C.23 | C# | using System;
class Program {
static double MonteCarloPi(int n) {
int inside = 0;
Random r = new Random();
for (int i = 0; i < n; i++) {
if (Math.Pow(r.NextDouble(), 2)+ Math.Pow(r.NextDouble(), 2) <= 1) {
inside++;
}
}
return 4.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... | #Nim | Nim | import algorithm, sequtils, strformat
const SymbolTable = toSeq('a'..'z')
func encode(s: string): seq[int] =
var symtable: seq[char] = SymbolTable
for c in s:
let idx = symtable.find(c)
result.add idx
symtable.rotateLeft(0..idx, -1)
func decode(s: seq[int]): string =
var symtable = SymbolTable
... |
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... | #bash | bash |
#!/bin/bash
# michaeltd 2019-11-29 https://github.com/michaeltd/dots/blob/master/dot.files/.bashrc.d/.var/morse.sh
# https://en.wikipedia.org/wiki/Morse_code
# International Morse Code
# 1. Length of dot is 1 unit
# 2. Length of dash is 3 units
# 3. The space between parts of the same letter is 1 unit
# 4. The space ... |
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... | #AWK | AWK | #!/bin/gawk -f
# Monty Hall problem
BEGIN {
srand()
doors = 3
iterations = 10000
# Behind a door:
EMPTY = "empty"; PRIZE = "prize"
# Algorithm used
KEEP = "keep"; SWITCH="switch"; RAND="random";
#
}
function monty_hall( choice, algorithm ) {
# Set up doors
for ( i=0; i<doors; i++ ) {
door[i] = EM... |
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... | #Clojure | Clojure | (ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
(defn extended-gcd
"The extended Euclidean algorithm--using Clojure code from RosettaCode for Extended Eucliean
(see http://en.wikipedia.orwiki/Extended_Euclidean_algorithm)
Returns a list containing the GCD and the Bézout coefficients
corres... |
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... | #zkl | zkl | class MList{
fcn init(xs){ var list=vm.arglist }
fcn bind(f) { list=list.apply(f); self }
fcn toString{ list.toString() }
} |
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.
... | #Wren | Wren | import "/fmt" for Fmt
// create a 4 dimensional list of the required size and initialize successive elements to the values 1 to 120
var m = 1
var a4 = List.filled(5, null)
for (i in 0..4) {
a4[i] = List.filled(4, null)
for (j in 0..3) {
a4[i][j] = List.filled(3, null)
for (k in 0..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.
| #AutoIt | AutoIt | #AutoIt Version: 3.2.10.0
$tableupto=12
$table=""
for $i = 1 To $tableupto
for $j = $i to $tableupto
$prod=string($i*$j)
if StringLen($prod) == 1 then
$prod = " "& $prod
EndIf
if StringLen($prod) == 2 then
$prod = " "& $prod
EndIf
$table = $table&" "&$prod
Next
$ta... |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #Ruby | Ruby | require 'matrix'
def regression_coefficients y, x
y = Matrix.column_vector y.map { |i| i.to_f }
x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}
(x.t * x).inverse * x.t * y
end |
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)(... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
l := integer(A[1]) | 10
every writeRow(n := !l, [: mf(!10,n) :])
end
procedure writeRow(n, r)
writes(right(n,3),": ")
every writes(right(!r,8)|"\n")
end
procedure mf(n, m)
if n <= 0 then return 1
return n*mf(n-m, m)
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.
| #Octave | Octave | [X, Y, BUTTONS] = ginput(N); |
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.
| #Oz | Oz | declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
WindowClosed = {NewCell false}
Label
Window = {QTk.build
td(action:proc {$} WindowClosed := true {Window close} end
label(text:"" handle:Label))}
in
{Window show}
for while:{Not @WindowClosed} do
TopmostWindow = {List.last {Strin... |
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... | #Java | Java | public class NQueens {
private static int[] b = new int[8];
private static int s = 0;
static boolean unsafe(int y) {
int x = b[y];
for (int i = 1; i <= y; i++) {
int t = b[y - i];
if (t == x ||
t == x - i ||
t == x + i) {
return true;
}
}
return ... |
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... | #Picat | Picat | nth2(N) = N.to_string() ++ Th =>
( tween(N) -> Th = "th"
; 1 = N mod 10 -> Th = "st"
; 2 = N mod 10 -> Th = "nd"
; 3 = N mod 10 -> Th = "rd"
; Th = "th" ).
tween(N) => Tween = N mod 100, between(11, 13, Tween). |
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 ... | #Pure | Pure | // split numer into digits
digits n::number = loop n [] with
loop n l = loop (n div 10) ((n mod 10):l) if n > 0;
= l otherwise; end;
munchausen n::int = (filter isMunchausen list) when
list = 1..n; end with
isMunchausen n =... |
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
)
)
,
... | #Lambdatalk | Lambdatalk |
{def F {lambda {:n} {if {= :n 0} then 1 else {- :n {M {F {- :n 1}}}} }}}
{def M {lambda {:n} {if {= :n 0} then 0 else {- :n {F {M {- :n 1}}}} }}}
{map F {serie 0 19}}
-> 1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12
{map M {serie 0 19}}
-> 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 ... | #Nim | Nim | import options,math,sugar,strformat
template checkAndWrap(x:float,body:typed): untyped =
if x.classify in {fcNormal,fcZero,fcNegZero}:
some(body)
else:
none(typeof(body))
func reciprocal(x:float):Option[float] =
let res = 1 / x
res.checkAndWrap(res)
func log(x:float):Option[float] =
let res = ln(x)
... |
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 ... | #Perl | Perl | # 20201101 added Perl programming solution
use strict;
use warnings;
use Data::Monad::Maybe;
sub safeReciprocal { ( $_[0] == 0 ) ? nothing : just( 1 / $_[0] ) }
sub safeRoot { ( $_[0] < 0 ) ? nothing : just( sqrt( $_[0] ) ) }
sub safeLog { ( $_[0] <= 0 ) ? nothing : just( log ( $_[0] ) ) }
... |
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
π
{\... | #C.2B.2B | C++ |
#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main(){
int jmax=1000; // maximum value of HIT number. (Length of output file)
int imax=1000; // maximum value of random numbers for producing HITs.
double x,y; // Coordinates
int hit; // storag... |
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... | #Perl | Perl | use strict;
use warnings;
sub encode {
my ($str) = @_;
my $table = join '', 'a' .. 'z';
map {
$table =~ s/(.*?)$_/$_$1/ or die;
length($1);
} split //, $str;
}
sub decode {
my $table = join '', 'a' .. 'z';
join "", map {
$table =~ s/(.{$_})(.)/$2$1/ or die;
$2;
} @_;
}
for my $test ( qw(broood banana... |
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... | #BASIC | BASIC | DECLARE SUB player (what AS STRING)
'this determines the length of the notes
'lower number = longer duration
CONST noteLen = 16
DIM tones(62) AS STRING
FOR n% = 0 TO 62
READ tones(n%)
NEXT n%
'set up the playing system
PLAY "t255o4l" + LTRIM$(STR$(noteLen))
LINE INPUT "String to convert to Morse code: "; ... |
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... | #BASIC | BASIC | RANDOMIZE TIMER
DIM doors(3) '0 is a goat, 1 is a car
CLS
switchWins = 0
stayWins = 0
FOR plays = 0 TO 32767
winner = INT(RND * 3) + 1
doors(winner) = 1'put a winner in a random door
choice = INT(RND * 3) + 1'pick a door, any door
DO
shown = INT(RND * 3) + 1
'don't show the winner or the choice
LOOP WHILE doors... |
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... | #CLU | CLU | mul_inv = proc (a, b: int) returns (int) signals (no_inverse)
if b<0 then b := -b end
if a<0 then a := b - (-a // b) end
t: int := 0
nt: int := 1
r: int := b
nr: int := a // b
while nr ~= 0 do
q: int := r / nr
t, nt := nt, t - q*nt
r, nr := nr, r - q*nr
end
if... |
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... | #Comal | Comal | 0010 FUNC mulinv#(a#,b#) CLOSED
0020 IF b#<0 THEN b#:=-b#
0030 IF a#<0 THEN a#:=b#-(-a# MOD b#)
0040 t#:=0;nt#:=1;r#:=b#;nr#:=a# MOD b#
0050 WHILE nr#<>0 DO
0060 q#:=r# DIV nr#
0070 tmp#:=nt#;nt#:=t#-q#*nt#;t#:=tmp#
0080 tmp#:=nr#;nr#:=r#-q#*nr#;r#:=tmp#
0090 ENDWHILE
0100 IF r#>1 THEN RETURN -1... |
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.
... | #X86-64_Assembly | X86-64 Assembly |
option casemap:none
printf proto :qword, :vararg
exit proto :dword
ROW_LEN equ (4*4)
MEM_SIZE equ 4
.data
;; A 2d array - 2 rows, 4 columns
;; int twodimen[2][4] = { {0,1,2,3},
;; {4,5,6,7}};
twodimen db 48 dup (0)
tpl db "%d",13,10,0
.code
main proc
l... |
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.
| #AWK | AWK |
BEGIN {
for(i=1;i<=12;i++){
for(j=1;j<=12;j++){
if(j>=i||j==1){printf "%4d",i*j}
else {printf " "}
}
print
}
} |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #SPSS | SPSS | set rng=mc seed=17760704.
new file.
input program.
vector x(4).
loop #i=1 to 200.
loop #j=1 to 4.
compute x(#j)=rv.normal(0,1).
end loop.
end case.
end loop.
end file.
end input program.
compute y=1.5+0.8*x1-0.7*x2+1.1*x3-1.7*x4+rv.normal(0,1).
execute. |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #Stata | Stata | clear
set seed 17760704
set obs 200
forv i=1/4 {
gen x`i'=rnormal()
}
gen y=1.5+0.8*x1-0.7*x2+1.1*x3-1.7*x4+rnormal() |
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)(... | #IS-BASIC | IS-BASIC | 100 PROGRAM "Multifac.bas"
110 FOR I=1 TO 5
120 PRINT "Degree";I;":";
130 FOR N=1 TO 10
140 PRINT MFACT(N,I);
150 NEXT
160 PRINT
170 NEXT
180 DEF MFACT(N,D)
190 NUMERIC I,RES
200 IF N<2 THEN LET MFACT=1:EXIT DEF
210 LET RES=N
220 FOR I=N-D TO 2 STEP-D
230 LET RES=RES*I
240 NEXT
250 LET M... |
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.
| #Perl | Perl | use SDL;
use SDL::Events;
use SDLx::App;
my $app = SDLx::App->new;
$app->add_event_handler( sub {
my $event = shift;
if( $event->type == SDL_MOUSEMOTION ) {
printf( "x=%d y=%d\n", $event->motion_x, $event->motion_y );
$app->stop
}
} );
$app->run;
|
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.
| #Phix | Phix | -- demo\rosetta\Mouse_position.exw
include pGUI.e
Ihandle global_lbl, canvas_lbl, timer_lbl
function globalmotion_cb(integer x, integer y, atom /*pStatus*/)
IupSetStrAttribute(global_lbl,"TITLE","globalmotion_cb %d, %d",{x,y})
return IUP_DEFAULT
end function
function canvas_motion_cb(Ihandle /*canvas*/, i... |
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... | #JavaScript | JavaScript | function queenPuzzle(rows, columns) {
if (rows <= 0) {
return [[]];
} else {
return addQueen(rows - 1, columns);
}
}
function addQueen(newRow, columns, prevSolution) {
var newSolutions = [];
var prev = queenPuzzle(newRow, columns);
for (var i = 0; i < prev.length; i++) {
... |
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... | #PicoLisp | PicoLisp | (de rangeth (A B)
(mapcar
'((I)
(pack I
(if (member (% I 100) (11 12 13))
'th
(case (% I 10)
(1 'st)
(2 'nd)
(3 'rd)
(T 'th) ) ) ) )
(range A B) ) )
(prinl (glue " " (rangeth 0 ... |
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 ... | #PureBasic | PureBasic | EnableExplicit
Declare main()
If OpenConsole("Munchausen_numbers")
main() : Input() : End
EndIf
Procedure main()
Define i.i,
sum.i,
number.i,
digit.i
For i = 1 To 5000
sum = 0
number = i
While number > 0
digit = number % 10
sum + Pow(digit, digit)
num... |
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
)
)
,
... | #Liberty_BASIC | Liberty BASIC |
print "F sequence."
for i = 0 to 20
print f(i);" ";
next
print
print "M sequence."
for i = 0 to 20
print m(i);" ";
next
end
function f(n)
if n = 0 then
f = 1
else
f = n - m(f(n - 1))
end if
end function
function m(n)
if n = 0 then
m = 0
else
m = n - f(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 ... | #Phix | Phix | function bindf(object m, integer f)
return f(m)
end function
function unit(object m)
return m
end function
function times_five(object l)
return iff(integer(l)?l*5:l)
end function
function plus_four(object l)
return iff(integer(l)?l+4:l)
end function
procedure test(object l)
printf(1,"%v -> %... |
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 ... | #Python | Python | """A Maybe Monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Maybe(Generic[T]):
def __init_... |
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
π
{\... | #Clojure | Clojure | (defn calc-pi [iterations]
(loop [x (rand) y (rand) in 0 total 1]
(if (< total iterations)
(recur (rand) (rand) (if (<= (+ (* x x) (* y y)) 1) (inc in) in) (inc total))
(double (* (/ in total) 4)))))
(doseq [x (take 5 (iterate #(* 10 %) 10))] (println (str (format "% 8d" x) ": " (calc-pi 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
π
{\... | #Common_Lisp | Common Lisp | (defun approximate-pi (n)
(/ (loop repeat n count (<= (abs (complex (random 1.0) (random 1.0))) 1.0)) n 0.25))
(dolist (n (loop repeat 5 for n = 1000 then (* n 10) collect n))
(format t "~%~8d -> ~f" n (approximate-pi 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... | #Phix | Phix | with javascript_semantics
function encode(string s)
string symtab = "abcdefghijklmnopqrstuvwxyz"
sequence res = {}
for i=1 to length(s) do
integer ch = s[i], k = find(ch,symtab)
res &= k-1
-- for j=k to 2 by -1 do
-- symtab[j] = symtab[j-1]
-- end for
-- symtab[1] = c... |
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... | #Befunge | Befunge | >~>48*-:0\`#@_2*::"!"%\"!"/3+g75v
^v('_')v!:-*57g+3/"!"\%"!":+1\-*<
^$$,*84_\#!:#:2#-%#15#\9#/*#2+#,<
##X)P)##Z*##3(D)5);(##8(/)A)8)9(#
($(&(*(2(B(A(?(;(3([)M)##1(##V)L)
$%1'-')&$$.''&2'&%$'%&0'#%%%#&,''
'(&*&#$&&*'$&)'%'/'########6)##$%
1'-')&$$.''&2'&%$'%&0'#%%%#&,'''(
&*&#$&&*'$&)'%'/'################ |
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... | #BBC_BASIC | BBC BASIC | total% = 10000
FOR trial% = 1 TO total%
prize_door% = RND(3) : REM. The prize is behind this door
guess_door% = RND(3) : REM. The contestant guesses this door
IF prize_door% = guess_door% THEN
REM. The contestant guessed right, reveal either of the others
reveal_d... |
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... | #Common_Lisp | Common Lisp |
;;
;; Calculates the GCD of a and b based on the Extended Euclidean Algorithm. The function also returns
;; the Bézout coefficients s and t, such that gcd(a, b) = as + bt.
;;
;; The algorithm is described on page http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2
;;
(defun egcd (a b)
(do (... |
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.
... | #XPL0 | XPL0 |
int A(5,4,3,2);
[A(3,1,0,1):= 3100;
A(3,1,0,1):= A(3,1,0,1)+1;
IntOut(0, A(3,1,0,1));
] |
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.
| #Axe | Axe | Fix 5
ClrDraw
For(I,1,10)
Text(I-1*9,0,I▶Dec)
Text(91,I*7+1,I▶Dec)
End
For(J,1,8)
For(I,J,10)
Text(I-1*9,J*7+1,I*J▶Dec)
End
End
HLine(7)
VLine(89)
DispGraph
getKeyʳ
Fix 4 |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #Tcl | Tcl | package require math::linearalgebra
namespace eval multipleRegression {
namespace export regressionCoefficients
namespace import ::math::linearalgebra::*
# Matrix inversion is defined in terms of Gaussian elimination
# Note that we assume (correctly) that we have a square matrix
proc invert {matri... |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #TI-83_BASIC | TI-83 BASIC | {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}→L₁
{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}→L₂
QuadReg L₁,L₂ |
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)(... | #J | J |
NB. tacit implementation of the recursive c function
NB. int multifact(int n,int deg){return n<=deg?n:n*multifact(n-deg,deg);}
multifact=: [`([ * - $: ])@.(<~)
(a:,<' degree'),multifact table >:i.10
┌─────────┬──────────────────────────────────────┐
│ │ degree ... |
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.
| #PicoLisp | PicoLisp | (de mousePosition ()
(prog2
(prin "^[[?9h") # Mouse reporting on
(and
(= "^[" (key))
(key 200)
(key 200)
(key)
(cons
(- (char (key)) 32)
(- (char (key)) 32) ) )
(prin "^[[?9l") ) ) # Mouse reporting off |
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.
| #PureBasic | PureBasic | x = WindowMouseX(#MyWindow)
y = WindowMouseY(#MyWindow) |
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.
| #Processing | Processing | void setup(){
size(640, 480);
}
void draw(){
// mouseX and mouseY provide the current mouse position
ellipse(mouseX, mouseY, 5, 5); // graphic output example
println("x:" + mouseX + " y:" + mouseY);
} |
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... | #jq | jq | def single_solution_queens(n):
def q: "♛";
def init(k): reduce range(0;k) as $i ([]; . + ["."]);
def matrix(k): init(k) as $row | reduce range(0;k) as $i ([]; . + [$row]);
def place(stream; i; j):
# jq indexing is based on offsets but we are using the 1-based formulae:
reduce stream as $s (.; setpath([-... |
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... | #PL.2FI | PL/I | Nth: procedure options (main); /* 1 June 2014 */
declare i fixed (10);
do i = 0 to 25, 250 to 265, 1000 to 1025;
if i = 250 | i = 1000 then put skip (2);
put edit (enth(i)) (x(1), a);
end;
enth: procedure (i) returns (character (25) varying);
declare i fixed (10);
declare suffix charact... |
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... | #PowerShell | PowerShell | function nth($inp){
$suffix = "th"
switch($inp % 10){
1{$suffix="st"}
2{$suffix="nd"}
3{$suffix="rd"}
}
return "$inp$suffix "
}
0..25 | %{Write-host -nonewline (nth "$_")};""
250..265 | %{Write-host -nonewline (nth "$_")};""
1000..1025 | %{Write-host -nonewline (nth "$_")};"" |
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 ... | #Python | Python | for i in range(5000):
if i == sum(int(x) ** int(x) for x in str(i)):
print(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
)
)
,
... | #LibreOffice_Basic | LibreOffice Basic | '// LibreOffice Basic Implementation of Hofstadter Female-Male sequences
'// Utility functions
sub setfont(strfont)
ThisComponent.getCurrentController.getViewCursor.charFontName = strfont
end sub
sub newline
oVC = thisComponent.getCurrentController.getViewCursor
oText = oVC.text
oText.insertControlCharacter(oVC... |
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 ... | #Racket | Racket | #lang racket
(require syntax/parse/define)
(define (bind x f) (and x (f x)))
(define return identity)
;; error when arg = 0
(define reciprocal (curry / 1))
;; error when arg < 0
(define (root x) (if (< x 0) (error 'bad) (sqrt x)))
;; error whe arg <= 0
(define (ln x) (if (<= x 0) (error 'bad) (log x)))
(define... |
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 ... | #Raku | Raku | my $monad = <42>;
say 'Is $monad an Int?: ', $monad ~~ Int;
say 'Is $monad a Str?: ', $monad ~~ Str;
say 'Wait, what? What exactly is $monad?: ', $monad.^name; |
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
π
{\... | #Crystal | Crystal | def approx_pi(throws)
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
end
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end |
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
π
{\... | #D | D | import std.stdio, std.random, std.math;
double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ {
uint inside;
foreach (immutable i; 0 .. nthrows)
if (hypot(uniform01, uniform01) <= 1)
inside++;
return 4.0 * inside / nthrows;
}
void main() {
foreach (immutable p; 1 .. 8)
w... |
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... | #PHP | PHP | <?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[... |
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 | C |
/*
David Lambert, 2010-Dec-09
filter producing morse beep commands.
build:
make morse
use:
$ echo tie a. | ./morse
beep -n -f 440 -l 300 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -f 440 -l 100 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -D 200 -n -D 400 -n -f 440 -l 100 -D 100 -n -f 440 ... |
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 | C | //Evidence of the Monty Hall solution.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define GAMES 3000000
int main(void){
unsigned i, j, k, choice, winsbyswitch=0, door[3];
srand(time(NULL)); //initialize random seed.
for(i=0; i<GA... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
sub mulinv(a: int32, b: int32): (t: int32) is
if b<0 then b := -b; end if;
if a<0 then a := b - (-a % b); end if;
t := 0;
var nt: int32 := 1;
var r := b;
var nr := a % b;
while nr != 0 loop
var q := r / nr;
var tmp := nt; nt := t - q*nt; t := tmp;
... |
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... | #Crystal | Crystal | def modinv(a0, m0)
return 1 if m0 == 1
a, m = a0, m0
x0, inv = 0, 1
while a > 1
inv -= (a // m) * x0
a, m = m, a % m
x0, inv = inv, x0
end
inv += m0 if inv < 0
inv
end |
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.
| #BASIC | BASIC | CLS
'header row
PRINT " ";
FOR n = 1 TO 12
'do it this way for alignment purposes
o$ = " "
MID$(o$, LEN(o$) - LEN(STR$(n)) + 1) = STR$(n)
PRINT o$;
NEXT
PRINT : PRINT " "; STRING$(49, "-");
FOR n = 1 TO 12
PRINT
IF n < 10 THEN PRINT " ";
PRINT n; "|"; 'row labels
FOR m = ... |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #Ursala | Ursala | regression_coefficients = lapack..dgelsd |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Swap(Of T)(ByRef x As T, ByRef y As T)
Dim temp = x
x = y
y = temp
End Sub
Sub Require(condition As Boolean, message As String)
If condition Then
Return
End If
Throw New ArgumentException(message)
End Sub
Class Matr... |
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)(... | #Java | Java | public class MultiFact {
private static long multiFact(long n, int deg){
long ans = 1;
for(long i = n; i > 0; i -= deg){
ans *= i;
}
return ans;
}
public static void main(String[] args){
for(int deg = 1; deg <= 5; deg++){
System.out.print("degree " + deg + ":");
for(long n = 1; n <= 10; n++){
... |
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.
| #Python | Python |
import Tkinter as tk
def showxy(event):
xm, ym = event.x, event.y
str1 = "mouse at x=%d y=%d" % (xm, ym)
# show cordinates in title
root.title(str1)
# switch color to red if mouse enters a set location range
x,y, delta = 100, 100, 10
frame.config(bg='red'
if abs(xm - x)... |
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.
| #Racket | Racket |
#lang racket/gui
(define-values [point _] (get-current-mouse-state))
(send point get-x)
(send point get-y)
|
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... | #Julia | Julia | """
# EightQueensPuzzle
Ported to **Julia** from examples in several languages from
here: https://hbfs.wordpress.com/2009/11/10/is-python-slow
"""
module EightQueensPuzzle
export Board, solve!
mutable struct Board
cols::Int
nodes::Int
diag45::Int
diag135::Int
solutions::Int
Board() = new... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.