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/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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Ruby | Ruby | [Foo.new] * n # here Foo.new can be any expression that returns a new object
Array.new(n, Foo.new) |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Rust | Rust | use std::rc::Rc;
use std::cell::RefCell;
fn main() {
let size = 3;
// Clone the given element to fill out the vector.
let mut v: Vec<String> = vec![String::new(); size];
v[0].push('a');
println!("{:?}", v);
// Run a given closure to create each element.
let mut v: Vec<String> = (0..size).map(|i| i.to_string()).collect();
v[0].push('a');
println!("{:?}", v);
// For multiple mutable views of the same thing, use something like Rc and RefCell.
let v: Vec<Rc<RefCell<String>>> = vec![Rc::new(RefCell::new(String::new())); size];
v[0].borrow_mut().push('a');
println!("{:?}", v);
} |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Scala | Scala | for (i <- (0 until n)) yield new Foo() |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Scheme | Scheme | sash[r7rs]> (define-record-type <a> (make-a x) a? (x get-x))
#<unspecified>
sash[r7rs]> (define l1 (make-list 5 (make-a 3)))
#<unspecified>
sash[r7rs]> (eq? (list-ref l1 0) (list-ref l1 1))
#t
|
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 support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.
See also
oeis:A001006 Motzkin numbers
| #REXX | REXX | /*REXX program to display the first N Motzkin numbers, and if that number is prime. */
numeric digits 92 /*max number of decimal digits for task*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 42 /*Not specified? Then use the default.*/
w= length(n) + 1; wm= digits()%4 /*define maximum widths for two columns*/
say center('n', w ) center("Motzkin[n]", wm) center(' primality', 11)
say center('' , w, "─") center('' , wm, "─") center('', 11, "─")
@.= 1 /*define default vale for the @. array.*/
do m=0 for n /*step through indices for Motzkin #'s.*/
if m>1 then @.m= (@(m-1)*(m+m+1) + @(m-2)*(m*3-3))%(m+2) /*calculate a Motzkin #*/
call show /*display a Motzkin number ──► terminal*/
end /*m*/
say center('' , w, "─") center('' , wm, "─") center('', 11, "─")
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@: parse arg i; return @.i /*return function expression based on I*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
prime: if isPrime(@.m) then return " prime"; return ''
show: y= commas(@.m); say right(m, w) right(y, max(wm, length(y))) prime(); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure expose p?. p#. p_.; parse arg x /*persistent P·· REXX variables.*/
if symbol('P?.#')\=='VAR' then /*1st time here? Then define primes. */
do /*L is a list of some low primes < 100.*/
L= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101
p?.=0 /* [↓] define P_index, P, P squared.*/
do i=1 for words(L); _= word(L,i); p?._= 1; p#.i= _; p_.i= _*_
end /*i*/; p?.0= x2d(3632c8eb5af3b) /*bypass big ÷*/
p?.n= _ + 4 /*define next prime after last prime. */
p?.#= i - 1 /*define the number of primes found. */
end /* p?. p#. p_ must be unique. */
if x<p?.n then return p?.x /*special case, handle some low primes.*/
if x==p?.0 then return 1 /*save a number of primality divisions.*/
parse var x '' -1 _ /*obtain right─most decimal digit of X.*/
if _==5 then return 0; if x//2 ==0 then return 0 /*X ÷ by 5? X ÷ by 2?*/
if x//3==0 then return 0; if x//7 ==0 then return 0 /*" " " 3? " " " 7?*/
/*weed numbers that're ≥ 11 multiples. */
do j=5 to p?.# while p_.j<=x; if x//p#.j ==0 then return 0
end /*j*/
/*weed numbers that're>high multiple Ps*/
do k=p?.n by 6 while k*k<=x; if x//k ==0 then return 0
if x//(k+2)==0 then return 0
end /*k*/; return 1 /*Passed all divisions? It's a prime.*/ |
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 -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #C.2B.2B | C++ | #include <iostream>
#include <cmath>
#include <optional>
#include <vector>
using namespace std;
// std::optional can be a maybe monad. Use the >> operator as the bind function
template <typename T>
auto operator>>(const optional<T>& monad, auto f)
{
if(!monad.has_value())
{
// Return an empty maybe monad of the same type as if there
// was a value
return optional<remove_reference_t<decltype(*f(*monad))>>();
}
return f(*monad);
}
// The Pure function returns a maybe monad containing the value t
auto Pure(auto t)
{
return optional{t};
}
// A safe function to invert a value
auto SafeInverse(double v)
{
if (v == 0)
{
return optional<decltype(v)>();
}
else
{
return optional(1/v);
}
}
// A safe function to calculate the arc cosine
auto SafeAcos(double v)
{
if(v < -1 || v > 1)
{
// The input is out of range, return an empty monad
return optional<decltype(acos(v))>();
}
else
{
return optional(acos(v));
}
}
// Print the monad
template<typename T>
ostream& operator<<(ostream& s, optional<T> v)
{
s << (v ? to_string(*v) : "nothing");
return s;
}
int main()
{
// Use bind to compose SafeInverse and SafeAcos
vector<double> tests {-2.5, -1, -0.5, 0, 0.5, 1, 2.5};
cout << "x -> acos(1/x) , 1/(acos(x)\n";
for(auto v : tests)
{
auto maybeMonad = Pure(v);
auto inverseAcos = maybeMonad >> SafeInverse >> SafeAcos;
auto acosInverse = maybeMonad >> SafeAcos >> SafeInverse;
cout << v << " -> " << inverseAcos << ", " << acosInverse << "\n";
}
}
|
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
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #11l | 11l | F monte_carlo_pi(n)
V inside = 0
L 1..n
V x = random:()
V y = random:()
I x * x + y * y <= 1
inside++
R 4.0 * inside / n
print(monte_carlo_pi(1000000)) |
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.
Encoding algorithm
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
Decoding algorithm
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
Example
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters a-to-z
Input
Output
SymbolTable
broood
1
'abcdefghijklmnopqrstuvwxyz'
broood
1 17
'bacdefghijklmnopqrstuvwxyz'
broood
1 17 15
'rbacdefghijklmnopqstuvwxyz'
broood
1 17 15 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0 5
'orbacdefghijklmnpqstuvwxyz'
Decoding the indices back to the original symbol order:
Input
Output
SymbolTable
1 17 15 0 0 5
b
'abcdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
br
'bacdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
bro
'rbacdefghijklmnopqstuvwxyz'
1 17 15 0 0 5
broo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
brooo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
broood
'orbacdefghijklmnpqstuvwxyz'
Task
Encode and decode the following three strings of characters using the symbol table of the lowercase characters a-to-z as above.
Show the strings and their encoding here.
Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| #Haskell | Haskell | import Data.List (delete, elemIndex, mapAccumL)
import Data.Maybe (fromJust)
table :: String
table = ['a' .. 'z']
encode :: String -> [Int]
encode =
let f t s = (s : delete s t, fromJust (elemIndex s t))
in snd . mapAccumL f table
decode :: [Int] -> String
decode = snd . mapAccumL f table
where
f t i =
let s = (t !! i)
in (s : delete s t, s)
main :: IO ()
main =
mapM_ print $
(,) <*> uncurry ((==) . fst) <$> -- Test that ((fst . fst) x) == snd x)
((,) <*> (decode . snd) <$>
((,) <*> encode <$> ["broood", "bananaaa", "hiphophiphop"])) |
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 \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Ada | Ada |
with Ada.Text_IO;use Ada.Text_IO;
procedure modular_inverse is
-- inv_mod calculates the inverse of a mod n. We should have n>0 and, at the end, the contract is a*Result=1 mod n
-- If this is false then we raise an exception (don't forget the -gnata option when you compile
function inv_mod (a : Integer; n : Positive) return Integer with post=> (a * inv_mod'Result) mod n = 1 is
-- To calculate the inverse we do as if we would calculate the GCD with the Euclid extended algorithm
-- (but we just keep the coefficient on a)
function inverse (a, b, u, v : Integer) return Integer is
(if b=0 then u else inverse (b, a mod b, v, u-(v*a)/b));
begin
return inverse (a, n, 1, 0);
end inv_mod;
begin
-- This will output -48 (which is correct)
Put_Line (inv_mod (42,2017)'img);
-- The further line will raise an exception since the GCD will not be 1
Put_Line (inv_mod (42,77)'img);
exception when others => Put_Line ("The inverse doesn't exist.");
end modular_inverse;
|
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 language the following:
Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
Write three simple functions: root, addOne, and half
Derive Writer monad versions of each of these functions
Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.) | #JavaScript | JavaScript | (function () {
'use strict';
// START WITH THREE SIMPLE FUNCTIONS
// Square root of a number more than 0
function root(x) {
return Math.sqrt(x);
}
// Add 1
function addOne(x) {
return x + 1;
}
// Divide by 2
function half(x) {
return x / 2;
}
// DERIVE LOGGING VERSIONS OF EACH FUNCTION
function loggingVersion(f, strLog) {
return function (v) {
return {
value: f(v),
log: strLog
};
}
}
var log_root = loggingVersion(root, "obtained square root"),
log_addOne = loggingVersion(addOne, "added 1"),
log_half = loggingVersion(half, "divided by 2");
// UNIT/RETURN and BIND for the the WRITER MONAD
// The Unit / Return function for the Writer monad:
// 'Lifts' a raw value into the wrapped form
// a -> Writer a
function writerUnit(a) {
return {
value: a,
log: "Initial value: " + JSON.stringify(a)
};
}
// The Bind function for the Writer monad:
// applies a logging version of a function
// to the contents of a wrapped value
// and return a wrapped result (with extended log)
// Writer a -> (a -> Writer b) -> Writer b
function writerBind(w, f) {
var writerB = f(w.value),
v = writerB.value;
return {
value: v,
log: w.log + '\n' + writerB.log + ' -> ' + JSON.stringify(v)
};
}
// USING UNIT AND BIND TO COMPOSE LOGGING FUNCTIONS
// We can compose a chain of Writer functions (of any length) with a simple foldr/reduceRight
// which starts by 'lifting' the initial value into a Writer wrapping,
// and then nests function applications (working from right to left)
function logCompose(lstFunctions, value) {
return lstFunctions.reduceRight(
writerBind,
writerUnit(value)
);
}
var half_of_addOne_of_root = function (v) {
return logCompose(
[log_half, log_addOne, log_root], v
);
};
return half_of_addOne_of_root(5);
})(); |
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #FreeBASIC | FreeBASIC | Dim As Integer m1(1 To 3) = {3,4,5}
Dim As String m2 = "["
Dim As Integer x, y ,z
For x = 1 To Ubound(m1)
y = m1(x) + 1
z = y * 2
m2 &= Str(z) & ", "
Next x
m2 = Left(m2, Len(m2) -2)
m2 &= "]"
Print m2
Sleep |
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #Go | Go | package main
import "fmt"
type mlist struct{ value []int }
func (m mlist) bind(f func(lst []int) mlist) mlist {
return f(m.value)
}
func unit(lst []int) mlist {
return mlist{lst}
}
func increment(lst []int) mlist {
lst2 := make([]int, len(lst))
for i, v := range lst {
lst2[i] = v + 1
}
return unit(lst2)
}
func double(lst []int) mlist {
lst2 := make([]int, len(lst))
for i, v := range lst {
lst2[i] = 2 * v
}
return unit(lst2)
}
func main() {
ml1 := unit([]int{3, 4, 5})
ml2 := ml1.bind(increment).bind(double)
fmt.Printf("%v -> %v\n", ml1.value, ml2.value)
} |
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.
Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.
Task
State if the language supports multi-dimensional arrays in its syntax and usual implementation.
State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array.
The idiomatic method for the language is preferred.
The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
| #Objeck | Objeck | class MultiArray {
function : Main(args : String[]) ~ Nil {
a4 := Int->New[5,4,3,2];
a4_size := a4->Size();
m := 1;
for(i := 0; i < a4_size[0]; i += 1;) {
for(j := 0; j < a4_size[1]; j += 1;) {
for(k := 0; k < a4_size[2]; k += 1;) {
for(l := 0; l < a4_size[3]; l += 1;) {
a4[i,j,k,l] := m++;
};
};
};
};
System.IO.Standard->Print("First element = ")->PrintLine(a4[0,0,0,0]);
a4[0,0,0,0] := 121;
for(i := 0; i < a4_size[0]; i += 1;) {
for(j := 0; j < a4_size[1]; j += 1;) {
for(k := 0; k < a4_size[2]; k += 1;) {
for(l := 0; l < a4_size[3]; l += 1;) {
System.IO.Standard->Print(a4[i,j,k,l])->Print(" ");
};
};
};
};
""->PrintLine();
}
} |
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.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Multiplication_Table is
package IO is new Integer_IO (Integer);
use IO;
begin
Put (" | ");
for Row in 1..12 loop
Put (Row, Width => 4);
end loop;
New_Line;
Put_Line ("--+-" & 12 * 4 * '-');
for Row in 1..12 loop
Put (Row, Width => 2);
Put ("| ");
for Column in 1..12 loop
if Column < Row then
Put (" ");
else
Put (Row * Column, Width => 4);
end if;
end loop;
New_Line;
end loop;
end Multiplication_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
,
.
.
.
,
y
n
}
{\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}
X
i
=
{
x
i
1
,
x
i
2
,
.
.
.
,
x
i
n
}
,
i
∈
1..
k
{\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}
Compute the vector
β
=
{
β
1
,
β
2
,
.
.
.
,
β
k
}
{\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}}
using ordinary least squares regression using the following equation:
y
j
=
Σ
i
β
i
⋅
x
i
j
,
j
∈
1..
n
{\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}
You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
| #Kotlin | Kotlin | // Version 1.2.31
typealias Vector = DoubleArray
typealias Matrix = Array<Vector>
operator fun Matrix.times(other: Matrix): Matrix {
val rows1 = this.size
val cols1 = this[0].size
val rows2 = other.size
val cols2 = other[0].size
require(cols1 == rows2)
val result = Matrix(rows1) { Vector(cols2) }
for (i in 0 until rows1) {
for (j in 0 until cols2) {
for (k in 0 until rows2) {
result[i][j] += this[i][k] * other[k][j]
}
}
}
return result
}
fun Matrix.transpose(): Matrix {
val rows = this.size
val cols = this[0].size
val trans = Matrix(cols) { Vector(rows) }
for (i in 0 until cols) {
for (j in 0 until rows) trans[i][j] = this[j][i]
}
return trans
}
fun Matrix.inverse(): Matrix {
val len = this.size
require(this.all { it.size == len }) { "Not a square matrix" }
val aug = Array(len) { DoubleArray(2 * len) }
for (i in 0 until len) {
for (j in 0 until len) aug[i][j] = this[i][j]
// augment by identity matrix to right
aug[i][i + len] = 1.0
}
aug.toReducedRowEchelonForm()
val inv = Array(len) { DoubleArray(len) }
// remove identity matrix to left
for (i in 0 until len) {
for (j in len until 2 * len) inv[i][j - len] = aug[i][j]
}
return inv
}
fun Matrix.toReducedRowEchelonForm() {
var lead = 0
val rowCount = this.size
val colCount = this[0].size
for (r in 0 until rowCount) {
if (colCount <= lead) return
var i = r
while (this[i][lead] == 0.0) {
i++
if (rowCount == i) {
i = r
lead++
if (colCount == lead) return
}
}
val temp = this[i]
this[i] = this[r]
this[r] = temp
if (this[r][lead] != 0.0) {
val div = this[r][lead]
for (j in 0 until colCount) this[r][j] /= div
}
for (k in 0 until rowCount) {
if (k != r) {
val mult = this[k][lead]
for (j in 0 until colCount) this[k][j] -= this[r][j] * mult
}
}
lead++
}
}
fun printVector(v: Vector) {
println(v.asList())
println()
}
fun multipleRegression(y: Vector, x: Matrix): Vector {
val cy = (arrayOf(y)).transpose() // convert 'y' to column vector
val cx = x.transpose() // convert 'x' to column vector array
return ((x * cx).inverse() * x * cy).transpose()[0]
}
fun main(args: Array<String>) {
var y = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0)
var x = arrayOf(doubleArrayOf(2.0, 1.0, 3.0, 4.0, 5.0))
var v = multipleRegression(y, x)
printVector(v)
y = doubleArrayOf(3.0, 4.0, 5.0)
x = arrayOf(
doubleArrayOf(1.0, 2.0, 1.0),
doubleArrayOf(1.0, 1.0, 2.0)
)
v = multipleRegression(y, x)
printVector(v)
y = doubleArrayOf(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)
val a = doubleArrayOf(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)
x = arrayOf(DoubleArray(a.size) { 1.0 }, a, a.map { it * it }.toDoubleArray())
v = multipleRegression(y, x)
printVector(v)
} |
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)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #Dart | Dart |
main()
{
int n=5,d=3;
int z= fact(n,d);
print('$n factorial of degree $d is $z');
for(var j=1;j<=5;j++)
{
print('first 10 numbers of degree $j :');
for(var i=1;i<=10;i++)
{
int z=fact(i,j);
print('$z');
}
print('\n');
}
}
int fact(int a,int b)
{
if(a<=b||a==0)
return a;
if(a>1)
return a*fact((a-b),b);
}
|
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)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #Draco | Draco | proc nonrec multifac(int n, deg) ulong:
ulong result;
result := 1;
while n > 1 do
result := result * n;
n := n - deg
od;
result
corp
proc nonrec main() void:
byte n, d;
for n from 1 upto 10 do
for d from 1 upto 5 do
write(multifac(n,d):10)
od;
writeln()
od
corp |
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.
| #Icon_and_Unicon | Icon and Unicon | until *Pending() > 0 & Event() == "q" do { # loop until there is something to do
px := WAttrib("pointerx")
py := WAttrib("pointery")
# do whatever is needed
WDelay(5) # wait and share processor
}
|
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.
| #Java | Java | Point mouseLocation = MouseInfo.getPointerInfo().getLocation(); |
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | NrQueens := function(n)
local a, up, down, m, sub;
a := [1 .. n];
up := ListWithIdenticalEntries(2*n - 1, true);
down := ListWithIdenticalEntries(2*n - 1, true);
m := 0;
sub := function(i)
local j, k, p, q;
for k in [i .. n] do
j := a[k];
p := i + j - 1;
q := i - j + n;
if up[p] and down[q] then
if i = n then
m := m + 1;
else
up[p] := false;
down[q] := false;
a[k] := a[i];
a[i] := j;
sub(i + 1);
up[p] := true;
down[q] := true;
a[i] := a[k];
a[k] := j;
fi;
fi;
od;
end;
sub(1);
return m;
end;
Queens := function(n)
local a, up, down, v, sub;
a := [1 .. n];
up := ListWithIdenticalEntries(2*n - 1, true);
down := ListWithIdenticalEntries(2*n - 1, true);
v := [];
sub := function(i)
local j, k, p, q;
for k in [i .. n] do
j := a[k];
p := i + j - 1;
q := i - j + n;
if up[p] and down[q] then
if i = n then
Add(v, ShallowCopy(a));
else
up[p] := false;
down[q] := false;
a[k] := a[i];
a[i] := j;
sub(i + 1);
up[p] := true;
down[q] := true;
a[i] := a[k];
a[k] := j;
fi;
fi;
od;
end;
sub(1);
return v;
end;
NrQueens(8);
a := Queens(8);;
PrintArray(PermutationMat(PermList(a[1]), 8));
[ [ 1, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 1, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 1 ],
[ 0, 0, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 1, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 1, 0 ],
[ 0, 1, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 1, 0, 0, 0, 0 ] ] |
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.
| #Tcl | Tcl | proc nthroot {n A} {
expr {pow($A, 1.0/$n)}
} |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Nim | Nim | const Suffix = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"]
proc nth(n: Natural): string =
$n & "'" & (if n mod 100 in 11..20: "th" else: Suffix[n mod 10])
for j in countup(0, 1000, 250):
for i in j..j+24:
stdout.write nth(i), " "
echo "" |
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #Pascal | Pascal | {$IFDEF FPC}{$MODE objFPC}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
sysutils;
type
tdigit = byte;
const
base = 10;
maxDigits = base-1;// set for 32-compilation otherwise overflow.
var
DgtPotDgt : array[0..base-1] of NativeUint;
cnt: NativeUint;
function CheckSameDigits(n1,n2:NativeUInt):boolean;
var
dgtCnt : array[0..Base-1] of NativeInt;
i : NativeUInt;
Begin
fillchar(dgtCnt,SizeOf(dgtCnt),#0);
repeat
//increment digit of n1
i := n1;n1 := n1 div base;i := i-n1*base;inc(dgtCnt[i]);
//decrement digit of n2
i := n2;n2 := n2 div base;i := i-n2*base;dec(dgtCnt[i]);
until (n1=0) AND (n2= 0 );
result := true;
For i := 0 to Base-1 do
result := result AND (dgtCnt[i]=0);
end;
procedure Munch(number,DgtPowSum,minDigit:NativeUInt;digits:NativeInt);
var
i: NativeUint;
begin
inc(cnt);
number := number*base;
IF digits > 1 then
Begin
For i := minDigit to base-1 do
Munch(number+i,DgtPowSum+DgtPotDgt[i],i,digits-1);
end
else
For i := minDigit to base-1 do
//number is always the arrangement of the digits leading to smallest number
IF (number+i)<= (DgtPowSum+DgtPotDgt[i]) then
IF CheckSameDigits(number+i,DgtPowSum+DgtPotDgt[i]) then
iF number+i>0 then
writeln(Format('%*d %.*d',
[maxDigits,DgtPowSum+DgtPotDgt[i],maxDigits,number+i]));
end;
procedure InitDgtPotDgt;
var
i,k,dgtpow: NativeUint;
Begin
// digit ^ digit ,special case 0^0 here 0
DgtPotDgt[0]:= 0;
For i := 1 to Base-1 do
Begin
dgtpow := i;
For k := 2 to i do
dgtpow := dgtpow*i;
DgtPotDgt[i] := dgtpow;
end;
end;
begin
cnt := 0;
InitDgtPotDgt;
Munch(0,0,0,maxDigits);
writeln('Check Count ',cnt);
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Idris | Idris | mutual {
F : Nat -> Nat
F Z = (S Z)
F (S n) = (S n) `minus` M(F(n))
M : Nat -> Nat
M Z = Z
M (S n) = (S n) `minus` F(M(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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func array file: openFiles (in array string: fileNames) is func
result
var array file: fileArray is 0 times STD_NULL; # Define array variable
local
var integer: i is 0;
begin
fileArray := length(fileNames) times STD_NULL; # Array size computed at run-time
for key i range fileArray do
fileArray[i] := open(fileNames[i], "r"); # Assign multiple distinct objects
end for;
end func;
const proc: main is func
local
var array file: files is 0 times STD_NULL;
begin
files := openFiles([] ("abc.txt", "def.txt", "ghi.txt", "jkl.txt"));
end func; |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Sidef | Sidef | [Foo.new] * n; # incorrect (only one distinct object is created) |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Smalltalk | Smalltalk | |c|
"Create an ordered collection that will grow while we add elements"
c := OrderedCollection new.
"fill the collection with 9 arrays of 10 elements; elements (objects)
are initialized to the nil object, which is a well-defined 'state'"
1 to: 9 do: [ :i | c add: (Array new: 10) ].
"However, let us show a way of filling the arrays with object number 0"
c := OrderedCollection new.
1 to: 9 do: [ :i | c add: ((Array new: 10) copyReplacing: nil withObject: 0) ].
"demonstrate that the arrays are distinct: modify the fourth of each"
1 to: 9 do: [ :i | (c at: i) at: 4 put: i ].
"show it"
c do: [ :e | e printNl ]. |
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 support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.
See also
oeis:A001006 Motzkin numbers
| #Ruby | Ruby | require "prime"
motzkin = Enumerator.new do |y|
m = [1,1]
m.each{|m| y << m }
2.step do |i|
m << (m.last*(2*i+1) + m[-2]*(3*i-3)) / (i+2)
m.unshift # an arr with last 2 elements is sufficient
y << m.last
end
end
motzkin.take(42).each_with_index do |m, i|
puts "#{'%2d' % i}: #{m}#{m.prime? ? ' prime' : ''}"
end
|
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 support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.
See also
oeis:A001006 Motzkin numbers
| #Rust | Rust | // [dependencies]
// primal = "0.3"
// num-format = "0.4"
fn motzkin(n: usize) -> Vec<usize> {
let mut m = vec![0; n];
m[0] = 1;
m[1] = 1;
for i in 2..n {
m[i] = (m[i - 1] * (2 * i + 1) + m[i - 2] * (3 * i - 3)) / (i + 2);
}
m
}
fn main() {
use num_format::{Locale, ToFormattedString};
let count = 42;
let m = motzkin(count);
println!(" n M(n) Prime?");
println!("-----------------------------------");
for i in 0..count {
println!(
"{:2} {:>23} {}",
i,
m[i].to_formatted_string(&Locale::en),
primal::is_prime(m[i] as u64)
);
}
} |
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 support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.
See also
oeis:A001006 Motzkin numbers
| #Sidef | Sidef | say 50.of { .motzkin } |
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 -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #C.23 | C# | using System;
namespace RosettaMaybe
{
// courtesy of https://www.dotnetcurry.com/patterns-practices/1510/maybe-monad-csharp
public abstract class Maybe<T>
{
public sealed class Some : Maybe<T>
{
public Some(T value) => Value = value;
public T Value { get; }
}
public sealed class None : Maybe<T> { }
}
class Program
{
static Maybe<double> MonadicSquareRoot(double x)
{
if (x >= 0)
{
return new Maybe<double>.Some(Math.Sqrt(x));
}
else
{
return new Maybe<double>.None();
}
}
static void Main(string[] args)
{
foreach (double x in new double[] { 4.0D, 8.0D, -15.0D, 16.23D, -42 })
{
Maybe<double> maybe = MonadicSquareRoot(x);
if (maybe is Maybe<double>.Some some)
{
Console.WriteLine($"The square root of {x} is " + some.Value);
}
else
{
Console.WriteLine($"Square root of {x} is undefined.");
}
}
}
}
} |
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
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #360_Assembly | 360 Assembly | * Monte Carlo methods 08/03/2017
MONTECAR CSECT
USING MONTECAR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R8,1000 isamples=1000
LA R6,4 i=4
DO WHILE=(C,R6,LE,=F'7') do i=4 to 7
MH R8,=H'10' isamples=isamples*10
ZAP HITS,=P'0' hits=0
LA R7,1 j=1
DO WHILE=(CR,R7,LE,R8) do j=1 to isamples
BAL R14,RNDPK call random
ZAP X,RND x=rnd
BAL R14,RNDPK call random
ZAP Y,RND y=rnd
ZAP WP,X x
MP WP,X x**2
DP WP,ONE ~
ZAP XX,WP(8) x**2 normalized
ZAP WP,Y y
MP WP,Y y**2
DP WP,ONE ~
ZAP YY,WP(8) y**2 normalized
AP XX,YY xx=x**2+y**2
IF CP,XX,LT,ONE THEN if x**2+y**2<1 then
AP HITS,=P'1' hits=hits+1
ENDIF , endif
LA R7,1(R7) j++
ENDDO , enddo j
CVD R8,PSAMPLES psamples=isamples
ZAP WP,=P'4' 4
MP WP,ONE ~
MP WP,HITS *hits
DP WP,PSAMPLES /psamples
ZAP MCPI,WP(8) mcpi=4*hits/psamples
XDECO R6,WC edit i
MVC PG+4(1),WC+11 output i
MVC WC,MASK load mask
ED WC,PSAMPLES edit psamples
MVC PG+6(8),WC+8 output psamples
UNPK WC,MCPI unpack mcpi
OI WC+15,X'F0' zap sign
MVC PG+31(1),WC+6 output mcpi
MVC PG+33(6),WC+7 output mcpi decimals
XPRNT PG,L'PG print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
RNDPK EQU * ---- random number generator
ZAP WP,RNDSEED w=seed
MP WP,RNDCNSTA w*=cnsta
AP WP,RNDCNSTB w+=cnstb
MVC RNDSEED,WP+8 seed=w mod 10**15
MVC RND,=PL8'0' 0<=rnd<1
MVC RND+3(5),RNDSEED+3 return rnd
BR R14 ---- return
PSAMPLES DS 0D,PL8 F(15,0)
RNDSEED DC PL8'613058151221121' linear congruential constant
RNDCNSTA DC PL8'944021285986747' "
RNDCNSTB DC PL8'852529586767995' "
RND DS PL8 fixed(15,9)
ONE DC PL8'1.000000000' 1 fixed(15,9)
HITS DS PL8 fixed(15,0)
X DS PL8 fixed(15,9)
Y DS PL8 fixed(15,9)
MCPI DS PL8 fixed(15,9)
XX DS PL8 fixed(15,9)
YY DS PL8 fixed(15,9)
PG DC CL80'10**x xxxxxxxx samples give Pi=x.xxxxxx' buffer
MASK DC X'40202020202020202020202020202120' mask CL16 15num
WC DS PL16 character 16
WP DS PL16 packed decimal 16
YREGS
END MONTECAR |
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
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
DEFINE REAL_SIZE="6"
BYTE ARRAY realArray(1536)
PTR FUNC RealArrayPointer(BYTE i)
PTR p
p=realArray+i*REAL_SIZE
RETURN (p)
PROC InitRealArray()
REAL r2,r255,ri,div
REAL POINTER pow
INT i
IntToReal(2,r2)
IntToReal(255,r255)
FOR i=0 TO 255
DO
IntToReal(i,ri)
RealDiv(ri,r255,div)
pow=RealArrayPointer(i)
Power(div,r2,pow)
OD
RETURN
PROC CalcPi(INT n REAL POINTER pi)
BYTE x,y
INT i,counter
REAL tmp1,tmp2,tmp3,r1,r4
REAL POINTER pow
counter=0
IntToReal(1,r1)
IntToReal(4,r4)
FOR i=1 TO n
DO
x=Rand(0)
pow=RealArrayPointer(x)
RealAssign(pow,tmp1)
y=Rand(0)
pow=RealArrayPointer(y)
RealAssign(pow,tmp2)
RealAdd(tmp1,tmp2,tmp3)
IF RealGreaterOrEqual(tmp3,r1)=0 THEN
counter==+1
FI
OD
IntToReal(counter,tmp1)
RealMult(r4,tmp1,tmp2)
IntToReal(n,tmp3)
RealDiv(tmp2,tmp3,pi)
RETURN
PROC Test(INT n)
REAL pi
PrintF("%I samples -> ",n)
CalcPi(n,pi)
PrintRE(pi)
RETURN
PROC Main()
Put(125) PutE() ;clear the screen
PrintE("Initialization of data...")
InitRealArray()
Test(10)
Test(100)
Test(1000)
Test(10000)
RETURN |
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.
Encoding algorithm
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
Decoding algorithm
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
Example
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters a-to-z
Input
Output
SymbolTable
broood
1
'abcdefghijklmnopqrstuvwxyz'
broood
1 17
'bacdefghijklmnopqrstuvwxyz'
broood
1 17 15
'rbacdefghijklmnopqstuvwxyz'
broood
1 17 15 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0 5
'orbacdefghijklmnpqstuvwxyz'
Decoding the indices back to the original symbol order:
Input
Output
SymbolTable
1 17 15 0 0 5
b
'abcdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
br
'bacdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
bro
'rbacdefghijklmnopqstuvwxyz'
1 17 15 0 0 5
broo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
brooo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
broood
'orbacdefghijklmnpqstuvwxyz'
Task
Encode and decode the following three strings of characters using the symbol table of the lowercase characters a-to-z as above.
Show the strings and their encoding here.
Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every writes(s := !A, " -> [") do {
every writes(!(enc := encode(&lcase,s))," ")
writes("] -> ",s2 := decode(&lcase,enc))
write((s == s2, " (Correct)") | " (Incorrect)")
}
end
procedure encode(m,s)
enc := []
every c := !s do {
m ?:= reorder(tab(i := upto(c)),move(1),tab(0))
put(enc,i-1) # Strings are 1-based
}
return enc
end
procedure decode(m,enc)
dec := ""
every i := 1 + !enc do { # Lists are 1-based
dec ||:= m[i]
m ?:= reorder(tab(i),move(1),tab(0))
}
return dec
end
procedure reorder(s1,s2,s3)
return s2||s1||s3
end |
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,
or indicate them somehow (e.g. with a different pitch).
| #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
;;; I/O ports
KBB: equ 61h ; Keyboard controller port B (also controls speaker)
PITC2: equ 42h ; Programmable Interrupt Timer, channel 2 (frequency)
PITCTL: equ 43h ; PIT control port.
;;; Control bits
SPKR: equ 3 ; Lower two bits of KBB determine speaker on/off
CTR: equ 6 ; Counter select offset in PIT control byte
CBITS: equ 4 ; Size select offset in PIT control byte
B16: equ 3 ; 16-bit mode for the PIT counter
MODE: equ 1 ; Offset of mode in PIT control byte
SQWV: equ 3 ; Square wave mode
;;; Software interrupts
CLOCK: equ 1Ah ; BIOS clock function interrupt
DOS: equ 21h ; MS-DOS syscall interrupt
;;; MS-DOS syscalls
read: equ 3Fh ; Read from file
section .text
org 100h
;;; Set up the PIT to generate a 'C' note
cli
mov al,(2<<CTR)|(B16<<CBITS)|(SQWV<<MODE)
out PITCTL,al
mov ax,2280 ; Divisor of main oscillator frequency
out PITC2,al ; Output low byte first,
xchg al,ah
out PITC2,al ; Then high byte.
sti
;;; Read from stdin and sound as morse
input: mov ah,read ; Read
xor bx,bx ; from STDIN
mov cx,buf.size ; into the buffer
mov dx,buf
int DOS
jc stop ; Carry set = error, stop
test ax,ax ; Did we get any characters?
jnz go ; If not, we're done, so stop
stop: ret
go: mov cx,ax ; Loop counter = how many characters we have
mov si,buf ; Start at buffer size
dochar: lodsb ; Get current character
cmp al,26 ; End of file?
je stop ; Then stop
push cx ; Save pointer and counter
push si
call char ; Sound out this character
pop si ; Restore pointer and counter
pop cx
loop dochar ; If more characters, do the next one
jmp input ; Afterwards, try to get more input
;;; Sound ASCII character in AL
char: and al,127 ; 7-bit ASCII
sub al,32 ; Word separator? (<=32)
ja .snd ; If not, look up in table
mov bx,4 ; Otherwise, 'sound' a word space
jmp delay ; (4 more ticks to form 7-tick delay)
.snd: mov bx,morse ; Find offset in morse pulse table
xlatb
test al,al ; If it is zero, we want to ignore it
jz .out
xor ah,ah ; Otherwise, find its address
mov bx,ax
lea si,[bx+morse.P] ; and store it in SI.
xor bh,bh ; BX = BL in the following code
.byte: lodsb ; Get pulse byte
mov cx,4 ; Four pulses per byte
.pulse: mov bl,3 ; Load low pulse in BL
and bl,al
test bl,bl ; If it is zero,
jz .out ; We're done
mov bp,ax ; Otherwise, keep AX
call pulse ; Sound the pulse
mov ax,bp ; Restore AX
shr al,1 ; Next pulse
shr al,1
loop .pulse
jmp .byte ; If no zero pulse seen yet, next byte
.out: mov bl,2 ; 2 ticks more delay to form inter-char space
jmp delay
;;; Sound morse code pulse w/delay
pulse: cli ; Turn off interrupts
in al,KBB ; Read current configuration
or al,SPKR ; Turn speaker on
out KBB,al ; Write configuration back
sti ; Turn interrupts back on
call delay ; Delay for BX ticks
cli ; Turn off interrupts
in al,KBB ; Read current configuration
and al,~SPKR ; Turn speaker off
out KBB,al ; Write configuration back
sti ; Turn interrupts back on
mov bx,1 ; Intra-character delay = 1 tick
;;; Delay for BX ticks
delay: push bx ; Keep the registers we alter
push cx
push dx
xor ah,ah ; Clock function 0 = get ticks
int CLOCK ; Get current ticks (in CX:DX)
add bx,dx ; BX = time for which to wait
.wait: int CLOCK ; Wait for that time to occur
cmp dx,bx ; Are we there yet?
jbe .wait ; If not, try again
pop dx ; Restore the registers
pop cx
pop bx
ret
section .data
morse: ;;; Printable ASCII to pulse mapping (32-122)
db .n_-.P, .excl-.P, .dquot-.P, .n_-.P ; !"#
db .dolar-.P, .n_-.P, .amp-.P, .quot-.P;$%&'
db .open-.P, .close-.P, .n_-.P, .plus-.P;()*+
db .comma-.P, .minus-.P, .dot-.P, .slsh-.P;,-./
db .n0-.P, .n1-.P, .n2-.P, .n3-.P ;0123
db .n4-.P, .n5-.P, .n6-.P, .n7-.P ;4567
db .n8-.P, .n9-.P, .colon-.P, .semi-.P;89:;
db .n_-.P, .eq-.P, .n_-.P, .qm-.P ;<=>?
db .at-.P, .a-.P, .b-.P, .c-.P ;@ABC
db .d-.P, .e-.P, .f-.P, .g-.P ;DEFG
db .h-.P, .i-.P, .j-.P, .k-.P ;HIJK
db .l-.P, .m-.P, .n-.P, .o-.P ;LMNO
db .p-.P, .q-.P, .r-.P, .s-.P ;PQRS
db .t-.P, .u-.P, .v-.P, .w-.P ;TUVW
db .x-.P, .y-.P, .z-.P, .n_-.P ;XYZ[
db .n_-.P, .n_-.P, .n_-.P, .uscr-.P;\]^_
db .n_-.P, .a-.P, .b-.P, .c-.P ;`abc
db .d-.P, .e-.P, .f-.P, .g-.P ;defg
db .h-.P, .i-.P, .j-.P, .k-.P ;hijk
db .l-.P, .m-.P, .n-.P, .o-.P ;lmno
db .p-.P, .q-.P, .r-.P, .s-.P ;pqrs
db .t-.P, .u-.P, .v-.P, .w-.P ;tuvw
db .x-.P, .y-.P, .z-.P, .n_-.P ;xyz{
db .n_-.P, .n_-.P, .n_-.P, .n_-.P ;|}~
.P: ;;; Morse pulses are stored four to a byte, lowest bits first
.n_: db 0 ; To ignore undefined characters
.a: db 0Dh
.b: db 57h,0
.c: db 77h,0
.d: db 17h
.e: db 1h
.f: db 75h,0
.g: db 1Fh
.h: db 55h,0
.i: db 5h
.j: db 0FDh,0
.k: db 37h
.l: db 5Dh,0
.m: db 0Fh
.n: db 7h
.o: db 3Fh
.p: db 7Dh,0
.q: db 0DFh,0
.r: db 1Dh
.s: db 15h
.t: db 3h
.u: db 35h
.v: db 0D5h,0
.w: db 3Dh
.x: db 0D7h,0
.y: db 0F7h,0
.z: db 5Fh,0
.n0: db 0FFh,3
.n1: db 0FDh,3
.n2: db 0F5h,3
.n3: db 0D5h,3
.n4: db 55h,3
.n5: db 55h,1
.n6: db 57h,1
.n7: db 5Fh,1
.n8: db 7Fh,1
.n9: db 0FFh,1
.dot: db 0DDh,0Dh
.comma: db 5Fh,0Fh
.qm: db 0F5h,5
.quot: db 0FDh,7
.excl: db 77h,0Fh
.slsh: db 0D7h,1
.open: db 0F7h,1
.close: db 0F7h,0Dh
.amp: db 5Dh,1
.colon: db 7Fh,5
.semi: db 77h,7
.eq: db 57h,3
.plus: db 0DDh,1
.minus: db 57h,0Dh
.uscr: db 0F5h,0Dh
.dquot: db 5Dh,7
.dolar: db 0D5h,35h
.at: db 7Dh,7
section .bss
buf: resb 1024 ; 1K buffer
.size: equ $-buf |
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #11l | 11l | V stay = 0
V sw = 0
L 1000
V lst = [1, 0, 0]
random:shuffle(&lst)
V ran = random:(3)
V user = lst[ran]
lst.pop(ran)
V huh = 0
L(i) lst
I i == 0
lst.pop(huh)
L.break
huh++
I user == 1
stay++
I lst[0] == 1
sw++
print(‘Stay = ’stay)
print(‘Switch = ’sw) |
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 \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #ALGOL_68 | ALGOL 68 |
BEGIN
PROC modular inverse = (INT a, m) INT :
BEGIN
PROC extended gcd = (INT x, y) []INT :
CO
Algol 68 allows us to return three INTs in several ways. A [3]INT
is used here but it could just as well be a STRUCT.
CO
BEGIN
INT v := 1, a := 1, u := 0, b := 0, g := x, w := y;
WHILE w>0
DO
INT q := g % w, t := a - q * u;
a := u; u := t;
t := b - q * v;
b := v; v := t;
t := g - q * w;
g := w; w := t
OD;
a PLUSAB (a < 0 | u | 0);
(a, b, g)
END;
[] INT egcd = extended gcd (a, m);
(egcd[3] > 1 | 0 | egcd[1] MOD m)
END;
printf (($"42 ^ -1 (mod 2017) = ", g(0)$, modular inverse (42, 2017)))
CO
Note that if ϕ(m) is known, then a^-1 = a^(ϕ(m)-1) mod m which
allows an alternative implementation in terms of modular
exponentiation but, in general, this requires the factorization of
m. If m is prime the factorization is trivial and ϕ(m) = m-1.
2017 is prime which may, or may not, be ironic within the context
of the Rosetta Code conditions.
CO
END
|
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 language the following:
Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
Write three simple functions: root, addOne, and half
Derive Writer monad versions of each of these functions
Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.) | #Jsish | Jsish | 'use strict';
/* writer monad, in Jsish */
function writerMonad() {
// START WITH THREE SIMPLE FUNCTIONS
// Square root of a number more than 0
function root(x) {
return Math.sqrt(x);
}
// Add 1
function addOne(x) {
return x + 1;
}
// Divide by 2
function half(x) {
return x / 2;
}
// DERIVE LOGGING VERSIONS OF EACH FUNCTION
function loggingVersion(f, strLog) {
return function (v) {
return {
value: f(v),
log: strLog
};
};
}
var log_root = loggingVersion(root, "obtained square root"),
log_addOne = loggingVersion(addOne, "added 1"),
log_half = loggingVersion(half, "divided by 2");
// UNIT/RETURN and BIND for the the WRITER MONAD
// The Unit / Return function for the Writer monad:
// 'Lifts' a raw value into the wrapped form
// a -> Writer a
function writerUnit(a) {
return {
value: a,
log: "Initial value: " + JSON.stringify(a)
};
}
// The Bind function for the Writer monad:
// applies a logging version of a function
// to the contents of a wrapped value
// and return a wrapped result (with extended log)
// Writer a -> (a -> Writer b) -> Writer b
function writerBind(w, f) {
var writerB = f(w.value),
v = writerB.value;
return {
value: v,
log: w.log + '\n' + writerB.log + ' -> ' + JSON.stringify(v)
};
}
// USING UNIT AND BIND TO COMPOSE LOGGING FUNCTIONS
// We can compose a chain of Writer functions (of any length) with a simple foldr/reduceRight
// which starts by 'lifting' the initial value into a Writer wrapping,
// and then nests function applications (working from right to left)
function logCompose(lstFunctions, value) {
return lstFunctions.reduceRight(
writerBind,
writerUnit(value)
);
}
var half_of_addOne_of_root = function (v) {
return logCompose(
[log_half, log_addOne, log_root], v
);
};
return half_of_addOne_of_root(5);
}
var writer = writerMonad();
;writer.value;
;writer.log;
/*
=!EXPECTSTART!=
writer.value ==> 1.61803398874989
writer.log ==> Initial value: 5
obtained square root -> 2.23606797749979
added 1 -> 3.23606797749979
divided by 2 -> 1.61803398874989
=!EXPECTEND!=
*/ |
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #Haskell | Haskell | main = print $ [3,4,5] >>= (return . (+1)) >>= (return . (*2)) -- prints [8,10,12] |
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #J | J | bind=: S:0
unit=: boxopen
m_num=: unit
m_str=: unit@": |
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.
Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.
Task
State if the language supports multi-dimensional arrays in its syntax and usual implementation.
State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array.
The idiomatic method for the language is preferred.
The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
| #Perl | Perl | use feature 'say';
# Perl arrays are internally always one-dimensional, but multi-dimension arrays are supported via references.
# So a two-dimensional array is an arrays-of-arrays, (with 'rows' that are references to arrays), while a
# three-dimensional array is an array of arrays-of-arrays, and so on. There are no arbitrary limits on the
# sizes or number of dimensions (i.e. the 'depth' of nesting references).
# To generate a zero-initialized 2x3x4x5 array
for $i (0..1) {
for $j (0..2) {
for $k (0..3) {
$a[$i][$j][$k][$l] = [(0)x5];
}
}
}
# There is no requirement that the overall shape of array be regular, or that contents of
# the array elements be of the the same type. Arrays can contain almost any type of values
@b = (
[1, 2, 4, 8, 16, 32], # numbers
[<Mon Tue Wed Thu Fri Sat Sun>], # strings
[sub{$_[0]+$_[1]}, sub{$_[0]-$_[1]}, sub{$_[0]*$_[1]}, sub{$_[0]/$_[1]}] # coderefs
);
say $b[0][5]; # prints '32'
say $b[1][2]; # prints 'Wed'
say $b[2][0]->(40,2); # prints '42', sum of 40 and 2
# Pre-allocation is possible, can result in a more efficient memory layout
# (in general though Perl allows minimal control over memory)
$#$big = 1_000_000;
# But dimensions do not need to be pre-declared or pre-allocated.
# Perl will auto-vivify the necessary storage slots on first access.
$c[2][2] = 42;
# @c =
# [undef]
# [undef]
# [undef, undef, 42]
# Negative indicies to count backwards from the end of each dimension
say $c[-1][-1]; # prints '42'
# Elements of an array can be set one-at-a-time or in groups via slices
my @d = <Mon Tue Ned Sat Fri Thu>;
push @d, 'Sun';
$d[2] = 'Wed';
@d[3..5] = @d[reverse 3..5];
say "@d"; # prints 'Mon Tue Wed Thu Fri Sat Sun' |
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.
| #Agena | Agena | scope
# print a school style multiplication table
# NB: print outputs a newline at the end, write and printf do not
write( " " );
for i to 12 do printf( " %3d", i ) od;
printf( "\n +" );
for i to 12 do write( "----" ) od;
for i to 12 do
printf( "\n%3d|", i );
for j to i - 1 do write( " " ) od;
for j from i to 12 do printf( " %3d", i * j ) od;
od;
print()
epocs |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
y
n
}
{\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}
X
i
=
{
x
i
1
,
x
i
2
,
.
.
.
,
x
i
n
}
,
i
∈
1..
k
{\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}
Compute the vector
β
=
{
β
1
,
β
2
,
.
.
.
,
β
k
}
{\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}}
using ordinary least squares regression using the following equation:
y
j
=
Σ
i
β
i
⋅
x
i
j
,
j
∈
1..
n
{\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}
You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
| #Maple | Maple | n:=200:
X:=<ArrayTools[RandomArray](n,4,distribution=normal)|Vector(n,1,datatype=float[8])>:
Y:=X.<4.2,-2.8,-1.4,3.1,1.75>+convert(ArrayTools[RandomArray](n,1,distribution=normal),Vector): |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
y
n
}
{\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}
X
i
=
{
x
i
1
,
x
i
2
,
.
.
.
,
x
i
n
}
,
i
∈
1..
k
{\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}
Compute the vector
β
=
{
β
1
,
β
2
,
.
.
.
,
β
k
}
{\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}}
using ordinary least squares regression using the following equation:
y
j
=
Σ
i
β
i
⋅
x
i
j
,
j
∈
1..
n
{\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}
You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 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};
LeastSquares[Transpose@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)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #Elixir | Elixir | defmodule RC do
def multifactorial(n,d) do
Enum.take_every(n..1, d) |> Enum.reduce(1, fn x,p -> x*p end)
end
end
Enum.each(1..5, fn d ->
multifac = for n <- 1..10, do: RC.multifactorial(n,d)
IO.puts "Degree #{d}: #{inspect multifac}"
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)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #Erlang | Erlang | -module(multifac).
-compile(export_all).
multifac(N,D) ->
lists:foldl(fun (X,P) -> X * P end, 1, lists:seq(N,1,-D)).
main() ->
Ds = lists:seq(1,5),
Ns = lists:seq(1,10),
lists:foreach(fun (D) ->
io:format("Degree ~b: ~p~n",[D, [ multifac(N,D) || N <- Ns]])
end, Ds). |
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.
| #JavaScript | JavaScript | document.addEventListener('mousemove', function(e){
var position = { x: e.clientX, y: e.clientY }
} |
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.
| #Julia | Julia | using Gtk
const win = GtkWindow("Get Mouse Position", 600, 800)
const butn = GtkButton("Click Me Somewhere")
push!(win, butn)
callback(b, evt) = set_gtk_property!(win, :title, "Mouse Position: X is $(evt.x), Y is $(evt.y)")
signal_connect(callback, butn, "button-press-event")
showall(win)
c = Condition()
endit(w) = notify(c)
signal_connect(endit, win, :destroy)
wait(c)
|
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #GAP | GAP | NrQueens := function(n)
local a, up, down, m, sub;
a := [1 .. n];
up := ListWithIdenticalEntries(2*n - 1, true);
down := ListWithIdenticalEntries(2*n - 1, true);
m := 0;
sub := function(i)
local j, k, p, q;
for k in [i .. n] do
j := a[k];
p := i + j - 1;
q := i - j + n;
if up[p] and down[q] then
if i = n then
m := m + 1;
else
up[p] := false;
down[q] := false;
a[k] := a[i];
a[i] := j;
sub(i + 1);
up[p] := true;
down[q] := true;
a[i] := a[k];
a[k] := j;
fi;
fi;
od;
end;
sub(1);
return m;
end;
Queens := function(n)
local a, up, down, v, sub;
a := [1 .. n];
up := ListWithIdenticalEntries(2*n - 1, true);
down := ListWithIdenticalEntries(2*n - 1, true);
v := [];
sub := function(i)
local j, k, p, q;
for k in [i .. n] do
j := a[k];
p := i + j - 1;
q := i - j + n;
if up[p] and down[q] then
if i = n then
Add(v, ShallowCopy(a));
else
up[p] := false;
down[q] := false;
a[k] := a[i];
a[i] := j;
sub(i + 1);
up[p] := true;
down[q] := true;
a[i] := a[k];
a[k] := j;
fi;
fi;
od;
end;
sub(1);
return v;
end;
NrQueens(8);
a := Queens(8);;
PrintArray(PermutationMat(PermList(a[1]), 8));
[ [ 1, 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 1, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0, 1 ],
[ 0, 0, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 1, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 1, 0 ],
[ 0, 1, 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 1, 0, 0, 0, 0 ] ] |
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.
| #True_BASIC | True BASIC | FUNCTION Nroot (n, a)
LET precision = .00001
LET x1 = a
LET x2 = a / n
DO WHILE ABS(x2 - x1) > precision
LET x1 = x2
LET x2 = ((n - 1) * x2 + a / x2 ^ (n - 1)) / n
LOOP
LET Nroot = x2
END FUNCTION
PRINT " n 5643 ^ 1 / n nth_root ^ n"
PRINT " ------------------------------------"
FOR n = 3 TO 11 STEP 2
LET tmp = Nroot(n, 5643)
PRINT USING "####": n;
PRINT " ";
PRINT USING "###.########": tmp;
PRINT " ";
PRINT USING "####.########": (tmp ^ n)
NEXT n
PRINT
FOR n = 25 TO 125 STEP 25
LET tmp = Nroot(n, 5643)
PRINT USING "####": n;
PRINT " ";
PRINT USING "###.########": tmp;
PRINT " ";
PRINT USING "####.########": (tmp ^ n)
NEXT n
END |
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 the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Objeck | Objeck | class Nth {
function : OrdinalAbbrev(n : Int ) ~ String {
ans := "th"; # most of the time it should be "th"
if(n % 100 / 10 = 1) {
return ans; # teens are all "th"
};
select(n % 10){
label 1: { ans := "st"; }
label 2: { ans := "nd"; }
label 3: { ans := "rd"; }
};
return ans;
}
function : Main(args : String[]) ~ Nil {
for(i := 0; i <= 25; i+=1;) {
abbr := OrdinalAbbrev(i);
"{$i}{$abbr} "->Print();
};
""->PrintLine();
for(i := 250; i <= 265; i+=1;) {
abbr := OrdinalAbbrev(i);
"{$i}{$abbr} "->Print();
};
""->PrintLine();
for(i := 1000; i <= 1025; i+=1;) {
abbr := OrdinalAbbrev(i);
"{$i}{$abbr} "->Print();
};
}
} |
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #Perl | Perl | use List::Util "sum";
for my $n (1..5000) {
print "$n\n" if $n == sum( map { $_**$_ } split(//,$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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Io | Io | f := method(n, if( n == 0, 1, n - m(f(n-1))))
m := method(n, if( n == 0, 0, n - f(m(n-1))))
Range
0 to(19) map(n,f(n)) println
0 to(19) map(n,m(n)) println |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Swift | Swift | class Foo { }
var foos = [Foo]()
for i in 0..<n {
foos.append(Foo())
}
// incorrect version:
var foos_WRONG = [Foo](count: n, repeatedValue: Foo()) // Foo() only evaluated once |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Tcl | Tcl | package require TclOO
# The class that we want to make unique instances of
set theClass Foo
# Wrong version; only a single object created
set theList [lrepeat $n [$theClass new]]
# Right version; objects distinct
set theList {}
for {set i 0} {$i<$n} {incr i} {
lappend theList [$theClass new]
} |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Wren | Wren | class Foo {
static init() { __count = 0 } // set object counter to zero
construct new() {
__count = __count + 1 // increment object counter
_number = __count // allocates a unique number to each object created
}
number { _number }
}
Foo.init() // set object counter to zero
var n = 10 // say
// Create a List of 'n' distinct Foo objects
var foos = List.filled(n, null)
for (i in 0...foos.count) foos[i] = Foo.new()
// Show they're distinct by printing out their object numbers
foos.each { |f| System.write("%(f.number) ") }
System.print("\n")
// Now create a second List where each of the 'n' elements is the same Foo object
var foos2 = List.filled(n, Foo.new())
// Show they're the same by printing out their object numbers
foos2.each { |f| System.write("%(f.number) ") }
System.print() |
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 support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.
See also
oeis:A001006 Motzkin numbers
| #Swift | Swift | import Foundation
extension BinaryInteger {
@inlinable
public var isPrime: Bool {
if self == 0 || self == 1 {
return false
} else if self == 2 {
return true
}
let max = Self(ceil((Double(self).squareRoot())))
for i in stride(from: 2, through: max, by: 1) where self % i == 0 {
return false
}
return true
}
}
func motzkin(_ n: Int) -> [Int] {
var m = Array(repeating: 0, count: n)
m[0] = 1
m[1] = 1
for i in 2..<n {
m[i] = (m[i - 1] * (2 * i + 1) + m[i - 2] * (3 * i - 3)) / (i + 2)
}
return m
}
let m = motzkin(42)
for (i, n) in m.enumerated() {
print("\(i): \(n) \(n.isPrime ? "prime" : "")")
} |
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 support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.
See also
oeis:A001006 Motzkin numbers
| #Wren | Wren | import "/long" for ULong
import "/fmt" for Fmt
var motzkin = Fn.new { |n|
var m = List.filled(n+1, 0)
m[0] = ULong.one
m[1] = ULong.one
for (i in 2..n) {
m[i] = (m[i-1] * (2*i + 1) + m[i-2] * (3*i -3))/(i + 2)
}
return m
}
System.print(" n M[n] Prime?")
System.print("-----------------------------------")
var m = motzkin.call(41)
for (i in 0..41) {
Fmt.print("$2d $,23i $s", i, m[i], m[i].isPrime)
} |
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 -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #Clojure | Clojure |
(defn bind [val f]
(if-let [v (:value val)] (f v) val))
(defn unit [val] {:value val})
(defn opt_add_3 [n] (unit (+ 3 n))) ; takes a number and returns a Maybe number
(defn opt_str [n] (unit (str n))) ; takes a number and returns a Maybe string
(bind (unit 4) opt_add_3) ; evaluates to {:value 7}
(bind (unit nil) opt_add_3) ; evaluates to {:value nil}
(bind (bind (unit 8) opt_add_3) opt_str) ; evaluates to {:value "11"}
(bind (bind (unit nil) opt_add_3) opt_str) ; evaluates to {:value nil}
|
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 -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #Delphi | Delphi |
program Maybe_monad;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TmList = record
Value: PInteger;
function ToString: string;
function Bind(f: TFunc<PInteger, TmList>): TmList;
end;
function _Unit(aValue: Integer): TmList; overload;
begin
Result.Value := GetMemory(sizeof(Integer));
Result.Value^ := aValue;
end;
function _Unit(aValue: PInteger): TmList; overload;
begin
Result.Value := aValue;
end;
{ TmList }
function TmList.Bind(f: TFunc<PInteger, TmList>): TmList;
begin
Result := f(self.Value);
end;
function TmList.ToString: string;
begin
if Value = nil then
Result := 'none'
else
Result := value^.ToString;
end;
function Decrement(p: PInteger): TmList;
begin
if p = nil then
exit(_Unit(nil));
Result := _Unit(p^ - 1);
end;
function Triple(p: PInteger): TmList;
begin
if p = nil then
exit(_Unit(nil));
Result := _Unit(p^ * 3);
end;
var
m1, m2: TmList;
i, a, b, c: Integer;
p: Tarray<PInteger>;
begin
a := 3;
b := 4;
c := 5;
p := [@a, @b, nil, @c];
for i := 0 to High(p) do
begin
m1 := _Unit(p[i]);
m2 := m1.Bind(Decrement).Bind(Triple);
Writeln(m1.ToString: 4, ' -> ', m2.ToString);
end;
Readln;
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
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
procedure Test_Monte_Carlo is
Dice : Generator;
function Pi (Throws : Positive) return Float is
Inside : Natural := 0;
begin
for Throw in 1..Throws loop
if Random (Dice) ** 2 + Random (Dice) ** 2 <= 1.0 then
Inside := Inside + 1;
end if;
end loop;
return 4.0 * Float (Inside) / Float (Throws);
end Pi;
begin
Put_Line (" 10_000:" & Float'Image (Pi ( 10_000)));
Put_Line (" 100_000:" & Float'Image (Pi ( 100_000)));
Put_Line (" 1_000_000:" & Float'Image (Pi ( 1_000_000)));
Put_Line (" 10_000_000:" & Float'Image (Pi ( 10_000_000)));
Put_Line ("100_000_000:" & Float'Image (Pi (100_000_000)));
end Test_Monte_Carlo; |
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.
Encoding algorithm
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
Decoding algorithm
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
Example
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters a-to-z
Input
Output
SymbolTable
broood
1
'abcdefghijklmnopqrstuvwxyz'
broood
1 17
'bacdefghijklmnopqrstuvwxyz'
broood
1 17 15
'rbacdefghijklmnopqstuvwxyz'
broood
1 17 15 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0 5
'orbacdefghijklmnpqstuvwxyz'
Decoding the indices back to the original symbol order:
Input
Output
SymbolTable
1 17 15 0 0 5
b
'abcdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
br
'bacdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
bro
'rbacdefghijklmnopqstuvwxyz'
1 17 15 0 0 5
broo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
brooo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
broood
'orbacdefghijklmnpqstuvwxyz'
Task
Encode and decode the following three strings of characters using the symbol table of the lowercase characters a-to-z as above.
Show the strings and their encoding here.
Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| #J | J | spindizzy=:3 :0
'seq table'=. y
ndx=.$0
orig=. table
for_sym. seq do.
ndx=.ndx,table i.sym
table=. sym,table-.sym
end.
ndx
assert. seq-:yzzidnips ndx;orig
)
yzzidnips=:3 :0
'ndx table'=. y
seq=.''
for_n. ndx do.
seq=.seq,sym=. n{table
table=. sym,table-.sym
end.
seq
) |
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.
Encoding algorithm
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
Decoding algorithm
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
Example
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters a-to-z
Input
Output
SymbolTable
broood
1
'abcdefghijklmnopqrstuvwxyz'
broood
1 17
'bacdefghijklmnopqrstuvwxyz'
broood
1 17 15
'rbacdefghijklmnopqstuvwxyz'
broood
1 17 15 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0 5
'orbacdefghijklmnpqstuvwxyz'
Decoding the indices back to the original symbol order:
Input
Output
SymbolTable
1 17 15 0 0 5
b
'abcdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
br
'bacdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
bro
'rbacdefghijklmnopqstuvwxyz'
1 17 15 0 0 5
broo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
brooo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
broood
'orbacdefghijklmnpqstuvwxyz'
Task
Encode and decode the following three strings of characters using the symbol table of the lowercase characters a-to-z as above.
Show the strings and their encoding here.
Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| #Java | Java | import java.util.LinkedList;
import java.util.List;
public class MTF{
public static List<Integer> encode(String msg, String symTable){
List<Integer> output = new LinkedList<Integer>();
StringBuilder s = new StringBuilder(symTable);
for(char c : msg.toCharArray()){
int idx = s.indexOf("" + c);
output.add(idx);
s = s.deleteCharAt(idx).insert(0, c);
}
return output;
}
public static String decode(List<Integer> idxs, String symTable){
StringBuilder output = new StringBuilder();
StringBuilder s = new StringBuilder(symTable);
for(int idx : idxs){
char c = s.charAt(idx);
output = output.append(c);
s = s.deleteCharAt(idx).insert(0, c);
}
return output.toString();
}
private static void test(String toEncode, String symTable){
List<Integer> encoded = encode(toEncode, symTable);
System.out.println(toEncode + ": " + encoded);
String decoded = decode(encoded, symTable);
System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
}
public static void main(String[] args){
String symTable = "abcdefghijklmnopqrstuvwxyz";
test("broood", symTable);
test("bananaaa", symTable);
test("hiphophiphop", symTable);
}
} |
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,
or indicate them somehow (e.g. with a different pitch).
| #ABAP | ABAP | REPORT morse_code.
TYPES: BEGIN OF y_morse_code,
letter TYPE string,
code TYPE string,
END OF y_morse_code,
ty_morse_code TYPE STANDARD TABLE OF y_morse_code WITH EMPTY KEY.
cl_demo_output=>new(
)->begin_section( |Morse Code|
)->write( REDUCE stringtab( LET words = VALUE stringtab( ( |sos| )
( | Hello World!| )
( |Rosetta Code| ) )
morse_code = VALUE ty_morse_code( ( letter = 'A' code = '.- ' )
( letter = 'B' code = '-... ' )
( letter = 'C' code = '-.-. ' )
( letter = 'D' code = '-.. ' )
( letter = 'E' code = '. ' )
( letter = 'F' code = '..-. ' )
( letter = 'G' code = '--. ' )
( letter = 'H' code = '.... ' )
( letter = 'I' code = '.. ' )
( letter = 'J' code = '.--- ' )
( letter = 'K' code = '-.- ' )
( letter = 'L' code = '.-.. ' )
( letter = 'M' code = '-- ' )
( letter = 'N' code = '-. ' )
( letter = 'O' code = '--- ' )
( letter = 'P' code = '.--. ' )
( letter = 'Q' code = '--.- ' )
( letter = 'R' code = '.-. ' )
( letter = 'S' code = '... ' )
( letter = 'T' code = '- ' )
( letter = 'U' code = '..- ' )
( letter = 'V' code = '...- ' )
( letter = 'W' code = '.- - ' )
( letter = 'X' code = '-..- ' )
( letter = 'Y' code = '-.-- ' )
( letter = 'Z' code = '--.. ' )
( letter = '0' code = '----- ' )
( letter = '1' code = '.---- ' )
( letter = '2' code = '..--- ' )
( letter = '3' code = '...-- ' )
( letter = '4' code = '....- ' )
( letter = '5' code = '..... ' )
( letter = '6' code = '-.... ' )
( letter = '7' code = '--... ' )
( letter = '8' code = '---.. ' )
( letter = '9' code = '----. ' )
( letter = '''' code = '.----. ' )
( letter = ':' code = '---... ' )
( letter = ',' code = '--..-- ' )
( letter = '-' code = '-....- ' )
( letter = '(' code = '-.--.- ' )
( letter = '.' code = '.-.-.- ' )
( letter = '?' code = '..--.. ' )
( letter = ';' code = '-.-.-. ' )
( letter = '/' code = '-..-. ' )
( letter = '_' code = '..--.- ' )
( letter = ')' code = '---.. ' )
( letter = '=' code = '-...- ' )
( letter = '@' code = '.--.-. ' )
( letter = '\' code = '.-..-. ' )
( letter = '+' code = '.-.-. ' )
( letter = ' ' code = '/' ) )
IN INIT word_coded_tab TYPE stringtab
FOR word IN words
NEXT word_coded_tab = VALUE #( BASE word_coded_tab ( REDUCE string( INIT word_coded TYPE string
FOR index = 1 UNTIL index > strlen( word )
LET _morse_code = VALUE #( morse_code[ letter = COND #( WHEN index = 1 THEN to_upper( word(index) )
ELSE LET prev = index - 1 IN to_upper( word+prev(1) ) ) ]-code OPTIONAL )
IN NEXT word_coded = |{ word_coded } { _morse_code }| ) ) ) )
)->display( ). |
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #8086_Assembly | 8086 Assembly | time: equ 2Ch ; MS-DOS syscall to get current time
puts: equ 9 ; MS-DOS syscall to print a string
cpu 8086
bits 16
org 100h
section .text
;;; Initialize the RNG with the current time
mov ah,time
int 21h
mov di,cx ; RNG state is kept in DI and BP
mov bp,dx
mov dx,sw ; While switching doors,
mov bl,1
call simrsl ; run simulations,
mov dx,nsw ; While not switching doors,
xor bl,bl ; run simulations.
;;; Print string in DX, run 65536 simulations (according to BL),
;;; then print the amount of cars won.
simrsl: mov ah,puts ; Print the string
int 21h
xor cx,cx ; Run 65536 simulations
call simul
mov ax,si ; Print amount of cars
mov bx,number ; String pointer
mov cx,10 ; Divisor
.dgt: xor dx,dx ; Divide AX by ten
div cx
add dl,'0' ; Add ASCII '0' to the remainder
dec bx ; Move string pointer backwards
mov [bx],dl ; Store digit in string
test ax,ax ; If quotient not zero,
jnz .dgt ; calculate next digit.
mov dx,bx ; Print string starting at first digit
mov ah,puts
int 21h
ret
;;; Run CX simulations.
;;; If BL = 0, don't switch doors, otherwise, always switch
simul: xor si,si ; SI is the amount of cars won
.loop: call door ; Behind which door is the car?
xchg dl,al ; DL = car door
call door ; Which door does the contestant choose?
xchg ah,al ; AH = contestant door
.monty: call door ; Which door does Monty open?
cmp al,dl ; It can't be the door with the car,
je .monty
cmp al,ah ; or the door the contestant picked.
je .monty
test bl,bl ; Will the contestant switch doors?
jz .nosw
xor ah,al ; If so, he switches
.nosw: cmp ah,dl ; Did he get the car?
jne .next
inc si ; If so, add a car
.next: loop .loop
ret
;;; Generate a pseudorandom byte in AL using "X ABC" method
;;; Use it to select a door (1,2,3).
door: xchg bx,bp ; Load RNG state into byte-addressable
xchg cx,di ; registers.
.loop: inc bl ; X++
xor bh,ch ; A ^= C
xor bh,bl ; A ^= X
add cl,bh ; B += A
mov al,cl ; C' = B
shr al,1 ; C' >>= 1
add al,ch ; C' += C
xor al,bh ; C' ^= A
mov ch,al ; C = C'
and al,3 ; ...but we only want the last two bits,
jz .loop ; and if it was 0, get a new random number.
xchg bx,bp ; Restore the registers
xchg cx,di
ret
section .data
sw: db 'When switching doors: $'
nsw: db 'When not switching doors: $'
db '*****'
number: db 13,10,'$' |
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 \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #Arturo | Arturo | modInverse: function [a,b][
if b = 1 -> return 1
b0: b x0: 0 x1: 1
z: a
while [z > 1][
q: z / b t: b
b: z % b z: t
t: x0 x0: x1 - q * x0
x1: t
]
(x1 < 0) ? -> x1 + b0
-> x1
]
print modInverse 42 2017 |
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 \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #AutoHotkey | AutoHotkey | MsgBox, % ModInv(42, 2017)
ModInv(a, b) {
if (b = 1)
return 1
b0 := b, x0 := 0, x1 :=1
while (a > 1) {
q := a // b
, t := b
, b := Mod(a, b)
, a := t
, t := x0
, x0 := x1 - q * x0
, x1 := t
}
if (x1 < 0)
x1 += b0
return x1
} |
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 language the following:
Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
Write three simple functions: root, addOne, and half
Derive Writer monad versions of each of these functions
Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.) | #Julia | Julia | struct Writer x::Real; msg::String; end
Base.show(io::IO, w::Writer) = print(io, w.msg, ": ", w.x)
unit(x, logmsg) = Writer(x, logmsg)
bind(f, fmsg, w) = unit(f(w.x), w.msg * ", " * fmsg)
f1(x) = 7x
f2(x) = x + 8
a = unit(3, "after intialization")
b = bind(f1, "after times 7 ", a)
c = bind(f2, "after plus 8", b)
println("$a => $b => $c")
println(bind(f2, "after plus 8", bind(f1, "after times 7", unit(3, "after intialization"))))
|
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 language the following:
Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
Write three simple functions: root, addOne, and half
Derive Writer monad versions of each of these functions
Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.) | #Kotlin | Kotlin | // version 1.2.10
import kotlin.math.sqrt
class Writer<T : Any> private constructor(val value: T, s: String) {
var log = " ${s.padEnd(17)}: $value\n"
private set
fun bind(f: (T) -> Writer<T>): Writer<T> {
val new = f(this.value)
new.log = this.log + new.log
return new
}
companion object {
fun <T : Any> unit(t: T, s: String) = Writer<T>(t, s)
}
}
fun root(d: Double) = Writer.unit(sqrt(d), "Took square root")
fun addOne(d: Double) = Writer.unit(d + 1.0, "Added one")
fun half(d: Double) = Writer.unit(d / 2.0, "Divided by two")
fun main(args: Array<String>) {
val iv = Writer.unit(5.0, "Initial value")
val fv = iv.bind(::root).bind(::addOne).bind(::half)
println("The Golden Ratio is ${fv.value}")
println("\nThis was derived as follows:-\n${fv.log}")
} |
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #JavaScript | JavaScript |
Array.prototype.bind = function (func) {
return this.map(func).reduce(function (acc, a) { return acc.concat(a); });
}
Array.unit = function (elem) {
return [elem];
}
Array.lift = function (func) {
return function (elem) { return Array.unit(func(elem)); };
}
inc = function (n) { return n + 1; }
doub = function (n) { return 2 * n; }
listy_inc = Array.lift(inc);
listy_doub = Array.lift(doub);
[3,4,5].bind(listy_inc).bind(listy_doub); // [8, 10, 12]
|
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #Julia | Julia | julia> unit(v) = [v...]
unit (generic function with 1 method)
julia> import Base.bind
julia> bind(v, f) = f.(v)
bind (generic function with 5 methods)
julia> f1(x) = x + 1
f1 (generic function with 1 method)
julia> f2(x) = 2x
f2 (generic function with 1 method)
julia> bind(bind(unit([2, 3, 4]), f1), f2)
3-element Array{Int64,1}:
6
8
10
julia> unit([2, 3, 4]) .|> f1 .|> f2
3-element Array{Int64,1}:
6
8
10
|
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.
Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.
Task
State if the language supports multi-dimensional arrays in its syntax and usual implementation.
State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array.
The idiomatic method for the language is preferred.
The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
| #Phix | Phix | sequence xyz = repeat(repeat(repeat(0,x),y),z)
|
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.
Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.
Task
State if the language supports multi-dimensional arrays in its syntax and usual implementation.
State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array.
The idiomatic method for the language is preferred.
The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, if indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
| #Phixmonti | Phixmonti | include ..\Utilitys.pmt
0 ( 5 4 3 2 ) dim
5432 ( 5 4 3 2 ) sset
( 5 4 3 2 ) sget print nl
( 5 4 3 ) sget var row
row print nl
row 1 2 set var row
row print nl
row ( 5 4 3 ) sset
0 10 repeat ( 5 4 2 ) sset
pstack |
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.
| #ALGOL_68 | ALGOL 68 | main:(
INT max = 12;
INT width = ENTIER(log(max)*2)+1;
STRING empty = " "*width, sep="|", hr = "+" + (max+1)*(width*"-"+"+");
FORMAT ifmt = $g(-width)"|"$; # remove leading zeros #
printf(($gl$, hr));
print(sep + IF width<2 THEN "x" ELSE " "*(width-2)+"x " FI + sep);
FOR col TO max DO printf((ifmt, col)) OD;
printf(($lgl$, hr));
FOR row TO max DO
[row:max]INT product;
FOR col FROM row TO max DO product[col]:=row*col OD;
STRING prefix=(empty+sep)*(row-1);
printf(($g$, sep, ifmt, row, $g$, prefix, ifmt, product, $l$))
OD;
printf(($gl$, hr))
) |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
y
n
}
{\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}
X
i
=
{
x
i
1
,
x
i
2
,
.
.
.
,
x
i
n
}
,
i
∈
1..
k
{\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}
Compute the vector
β
=
{
β
1
,
β
2
,
.
.
.
,
β
k
}
{\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}}
using ordinary least squares regression using the following equation:
y
j
=
Σ
i
β
i
⋅
x
i
j
,
j
∈
1..
n
{\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}
You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
| #MATLAB | MATLAB | n=100; k=10;
y = randn (1,n); % generate random vector y
X = randn (k,n); % generate random matrix X
b = y / X
b = 0.1457109 -0.0777564 -0.0712427 -0.0166193 0.0292955 -0.0079111 0.2265894 -0.0561589 -0.1752146 -0.2577663 |
http://rosettacode.org/wiki/Multiple_regression | Multiple regression | Task
Given a set of data vectors in the following format:
y
=
{
y
1
,
y
2
,
.
.
.
,
y
n
}
{\displaystyle y=\{y_{1},y_{2},...,y_{n}\}\,}
X
i
=
{
x
i
1
,
x
i
2
,
.
.
.
,
x
i
n
}
,
i
∈
1..
k
{\displaystyle X_{i}=\{x_{i1},x_{i2},...,x_{in}\},i\in 1..k\,}
Compute the vector
β
=
{
β
1
,
β
2
,
.
.
.
,
β
k
}
{\displaystyle \beta =\{\beta _{1},\beta _{2},...,\beta _{k}\}}
using ordinary least squares regression using the following equation:
y
j
=
Σ
i
β
i
⋅
x
i
j
,
j
∈
1..
n
{\displaystyle y_{j}=\Sigma _{i}\beta _{i}\cdot x_{ij},j\in 1..n}
You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix).
| #Nim | Nim | # Using Wikipedia data sample.
import math
import arraymancer, sequtils
var
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].toTensor()
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].toTensor()
# Create Vandermonde matrix.
var a = stack(height.ones_like, height, height *. height, axis = 1)
echo toSeq(least_squares_solver(a, weight).solution.items) |
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)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #ERRE | ERRE |
PROGRAM MULTIFACTORIAL
PROCEDURE MULTI_FACT(NUM,DEG->MF)
RESULT=NUM
N=NUM
IF N=0 THEN
MF=1
EXIT PROCEDURE
END IF
LOOP
N-=DEG
EXIT IF N<=0
RESULT*=N
END LOOP
MF=RESULT
END PROCEDURE
BEGIN
PRINT(CHR$(12);)
FOR DEG=1 TO 10 DO
PRINT("Degree";DEG;":";)
FOR NUM=1 TO 10 DO
MULTI_FACT(NUM,DEG->MF)
PRINT(MF;)
END FOR
PRINT
END FOR
END PROGRAM
|
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)(1)}
n
!
!
=
n
(
n
−
2
)
(
n
−
4
)
.
.
.
{\displaystyle n!!=n(n-2)(n-4)...}
n
!
!
!
=
n
(
n
−
3
)
(
n
−
6
)
.
.
.
{\displaystyle n!!!=n(n-3)(n-6)...}
n
!
!
!
!
=
n
(
n
−
4
)
(
n
−
8
)
.
.
.
{\displaystyle n!!!!=n(n-4)(n-8)...}
n
!
!
!
!
!
=
n
(
n
−
5
)
(
n
−
10
)
.
.
.
{\displaystyle n!!!!!=n(n-5)(n-10)...}
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
Write a function that given n and the degree, calculates the multifactorial.
Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
Note: The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| #F.23 | F# | let rec mfact d = function
| n when n <= d -> n
| n -> n * mfact d (n-d)
[<EntryPoint>]
let main argv =
let (|UInt|_|) = System.UInt32.TryParse >> function | true, v -> Some v | false, _ -> None
let (maxDegree, maxN) =
match argv with
| [| UInt d; UInt n |] -> (int d, int n)
| [| UInt d |] -> (int d, 10)
| _ -> (5, 10)
let showFor d = List.init maxN (fun i -> mfact d (i+1)) |> printfn "%i: %A" d
ignore (List.init maxDegree (fun i -> showFor (i+1)))
0
|
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.
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.MouseInfo
fun main(args: Array<String>) {
(1..5).forEach {
Thread.sleep(1000)
val p = MouseInfo.getPointerInfo().location // gets screen coordinates
println("${it}: x = ${"%-4d".format(p.x)} y = ${"%-4d".format(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.
| #Liberty_BASIC | Liberty BASIC | nomainwin
UpperLeftX = DisplayWidth-WindowWidth
UpperLeftY = DisplayHeight-WindowHeight
struct point, x as long, y as long
stylebits #main.st ,0,0,_WS_EX_STATICEDGE,0
statictext #main.st "",16,16,100,26
stylebits #main ,0,0,_WS_EX_TOPMOST,0
open "move your mouse" for window_nf as #main
#main "trapclose [quit]"
timer 100, [mm]
wait
[mm]
CallDll #user32, "GetForegroundWindow", WndHandle as uLong
#main.st CursorPos$(WndHandle)
wait
[quit]
close #main
end
function CursorPos$(handle)
Calldll #user32, "GetCursorPos",_
point as struct,_
result as long
Calldll #user32, "ScreenToClient",_
handle As Ulong,_
point As struct,_
result as long
x = point.x.struct
y = point.y.struct
CursorPos$=x; ",";y
end function |
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 armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Go | Go | // A fairly literal translation of the example program on the referenced
// WP page. Well, it happened to be the example program the day I completed
// the task. It seems from the WP history that there has been some churn
// in the posted example program. The example program of the day was in
// Pascal and was credited to Niklaus Wirth, from his "Algorithms +
// Data Structures = Programs."
package main
import "fmt"
var (
i int
q bool
a [9]bool
b [17]bool
c [15]bool // offset by 7 relative to the Pascal version
x [9]int
)
func try(i int) {
for j := 1; ; j++ {
q = false
if a[j] && b[i+j] && c[i-j+7] {
x[i] = j
a[j] = false
b[i+j] = false
c[i-j+7] = false
if i < 8 {
try(i + 1)
if !q {
a[j] = true
b[i+j] = true
c[i-j+7] = true
}
} else {
q = true
}
}
if q || j == 8 {
break
}
}
}
func main() {
for i := 1; i <= 8; i++ {
a[i] = true
}
for i := 2; i <= 16; i++ {
b[i] = true
}
for i := 0; i <= 14; i++ {
c[i] = true
}
try(1)
if q {
for i := 1; i <= 8; i++ {
fmt.Println(i, x[i])
}
}
} |
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.
| #Ursala | Ursala | #import nat
#import flo
nthroot =
-+
("n","n-1"). "A". ("x". div\"n" plus/times("n-1","x") div("A",pow("x","n-1")))^== 1.,
float^~/~& predecessor+- |
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 the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #OCaml | OCaml |
let show_nth n =
if (n mod 10 = 1) && (n mod 100 <> 11) then "st"
else if (n mod 10 = 2) && (n mod 100 <> 12) then "nd"
else if (n mod 10 = 3) && (n mod 100 <> 13) then "rd"
else "th"
let () =
let show_ordinals (min, max) =
for i=min to max do
Printf.printf "%d%s " i (show_nth i)
done;
print_newline() in
List.iter show_ordinals [ (0,25); (250,265); (1000,1025) ]
|
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 Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #Phix | Phix | with javascript_semantics
constant powers = sq_power(tagset(9,0),tagset(9,0))
function munchausen(integer n)
integer n0 = n
atom total = 0
while n!=0 do
total += powers[remainder(n,10)+1]
n = floor(n/10)
end while
return (total==n0)
end function
for i=1 to 5000 do
if munchausen(i) then ?i end if
end for
|
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
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #J | J | F =: 1:`(- M @ $: @ <:) @.* M."0
M =: 0:`(- F @ $: @ <:) @.* M."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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #XPL0 | XPL0 | code Reserve=3, IntIn=10;
char A; int N, I;
[N:= IntIn(8); \get number of items from command line
A:= Reserve(N); \create array of N bytes
for I:= 0 to N-1 do A(I):= I*3; \initialize items with different values
for I:= 0 to N-1 do A:= I*3; \error: "references to the same mutable object"
] |
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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Yabasic | Yabasic | sub test()
print "Random number: " + str$(ran(100))
end sub
sub repL$(e$, n)
local i, r$
for i = 1 to n
r$ = r$ + "," + e$
next
return r$
end sub
dim func$(1)
n = token(repL$("test", 5), func$(), ",")
for i = 1 to n
execute(func$(i))
next 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 not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Z80_Assembly | Z80 Assembly | ld hl,RamArea ;a label for an arbitrary section of RAM
ld a,(foo) ;load the value of some memory location. "foo" is the label of a 16-bit address.
ld b,a ;use this as a loop counter.
xor a ;set A to zero
loop: ;creates a list of ascending values starting at zero. Each is stored at a different memory location
ld (hl),a ;store A in ram
inc a ;ensures each value is different.
inc hl ;next element of list
djnz loop |
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 support 64 bit integers, as many such numbers as you can. Indicate which of these numbers are prime.
See also
oeis:A001006 Motzkin numbers
| #Yabasic | Yabasic | dim M(41)
M(0) = 1 : M(1) = 1
print str$(M(0), "%19g")
print str$(M(1), "%19g")
for n = 2 to 41
M(n) = M(n-1)
for i = 0 to n-2
M(n) = M(n) + M(i)*M(n-2-i)
next i
print str$(M(n), "%19.0f"),
if isPrime(M(n)) then print "is a prime" else print : fi
next n
end
sub isPrime(v)
if v < 2 then return False : fi
if mod(v, 2) = 0 then return v = 2 : fi
if mod(v, 3) = 0 then return v = 3 : fi
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub |
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 -> Maybe Int and Int -> Maybe String
Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| #EchoLisp | EchoLisp |
(define (Maybe.domain? x) (or (number? x) (string? x)))
(define (Maybe.unit elem (bool #t)) (cons bool elem))
;; f is a safe or unsafe function
;; (Maybe.lift f) returns a safe Maybe function which returns a Maybe element
(define (Maybe.lift f)
(lambda(x)
(let [(u (f x))]
(if (Maybe.domain? u)
(Maybe.unit u)
(Maybe.unit x #f))))) ;; return offending x
;; elem = Maybe element
;; f is safe or unsafe (lisp) function
;; return Maybe element
(define (Maybe.bind f elem)
(if (first elem) ((Maybe.lift f) (rest elem)) elem))
;; pretty-print
(define (Maybe.print elem)
(if (first elem) (writeln elem ) (writeln '❌ elem)))
;; unsafe functions
(define (u-log x) (if (> x 0) (log x) #f))
(define (u-inv x) (if (zero? x) 'zero-div (/ x)))
;; (print (number->string (exp (log 3))))
(->> 3 Maybe.unit (Maybe.bind u-log) (Maybe.bind exp) (Maybe.bind number->string) Maybe.print)
→ (#t . "3.0000000000000004")
;; (print (number->string (exp (log -666))))
(->> -666 Maybe.unit (Maybe.bind u-log) (Maybe.bind exp) (Maybe.bind number->string) Maybe.print)
→ ❌ (#f . -666)
;; ;; (print (number->string (inverse (log 1))))
(->> 1 Maybe.unit (Maybe.bind u-log) (Maybe.bind u-inv) (Maybe.bind number->string) Maybe.print)
→ ❌ (#f . 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
π
{\displaystyle \pi }
.
If you had a circle and a square where the length of a side of the square
was the same as the diameter of the circle, the ratio of the area of the circle
to the area of the square would be
π
/
4
{\displaystyle \pi /4}
.
So, if you put this circle inside the square and select many random points
inside the square, the number of points inside the circle
divided by the number of points inside the square and the circle
would be approximately
π
/
4
{\displaystyle \pi /4}
.
Task
Write a function to run a simulation like this, with a variable number of random points to select.
Also, show the results of a few different sample sizes.
For software where the number
π
{\displaystyle \pi }
is not built-in,
we give
π
{\displaystyle \pi }
as a number of digits:
3.141592653589793238462643383280
| #ALGOL_68 | ALGOL 68 | PROC pi = (INT throws)REAL:
BEGIN
INT inside := 0;
TO throws DO
IF random ** 2 + random ** 2 <= 1 THEN
inside +:= 1
FI
OD;
4 * inside / throws
END # pi #;
print ((" 10 000:",pi ( 10 000),new line));
print ((" 100 000:",pi ( 100 000),new line));
print ((" 1 000 000:",pi ( 1 000 000),new line));
print ((" 10 000 000:",pi ( 10 000 000),new line));
print (("100 000 000:",pi (100 000 000),new line)) |
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.
Encoding algorithm
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
Decoding algorithm
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
Example
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters a-to-z
Input
Output
SymbolTable
broood
1
'abcdefghijklmnopqrstuvwxyz'
broood
1 17
'bacdefghijklmnopqrstuvwxyz'
broood
1 17 15
'rbacdefghijklmnopqstuvwxyz'
broood
1 17 15 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0
'orbacdefghijklmnpqstuvwxyz'
broood
1 17 15 0 0 5
'orbacdefghijklmnpqstuvwxyz'
Decoding the indices back to the original symbol order:
Input
Output
SymbolTable
1 17 15 0 0 5
b
'abcdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
br
'bacdefghijklmnopqrstuvwxyz'
1 17 15 0 0 5
bro
'rbacdefghijklmnopqstuvwxyz'
1 17 15 0 0 5
broo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
brooo
'orbacdefghijklmnpqstuvwxyz'
1 17 15 0 0 5
broood
'orbacdefghijklmnpqstuvwxyz'
Task
Encode and decode the following three strings of characters using the symbol table of the lowercase characters a-to-z as above.
Show the strings and their encoding here.
Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| #JavaScript | JavaScript | var encodeMTF = function (word) {
var init = {wordAsNumbers: [], charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};
return word.split('').reduce(function (acc, char) {
var charNum = acc.charList.indexOf(char); //get index of char
acc.wordAsNumbers.push(charNum); //add original index to acc
acc.charList.unshift(acc.charList.splice(charNum, 1)[0]); //put at beginning of list
return acc;
}, init).wordAsNumbers; //return number list
};
var decodeMTF = function (numList) {
var init = {word: '', charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};
return numList.reduce(function (acc, num) {
acc.word += acc.charList[num];
acc.charList.unshift(acc.charList.splice(num, 1)[0]); //put at beginning of list
return acc;
}, init).word;
};
//test our algorithms
var words = ['broood', 'bananaaa', 'hiphophiphop'];
var encoded = words.map(encodeMTF);
var decoded = encoded.map(decodeMTF);
//print results
console.log("from encoded:");
console.log(encoded);
console.log("from decoded:");
console.log(decoded); |
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,
or indicate them somehow (e.g. with a different pitch).
| #Action.21 | Action! | DEFINE PTR="CARD"
DEFINE COUNT="$60"
PTR ARRAY code(COUNT)
BYTE
PALNTSC=$D014,
dotDuration,dashDuration,
intraGapDuration,letterGapDuration,wordGapDuration
PROC Init()
Zero(code,COUNT)
code('!)="-.-.--" code('")=".-..-."
code('$)="...-..-" code('&)=".-..."
code('')=".----." code('()="-.--.-"
code('))="---.." code('+)=".-.-."
code(',)="--..--" code('-)="-....-"
code('.)=".-.-.-" code('/)="-..-."
code('0)="-----" code('1)=".----"
code('2)="..---" code('3)="...--"
code('4)="....-" code('5)="....."
code('6)="-...." code('7)="--..."
code('8)="---.." code('9)="----."
code(':)="---..." code(';)="-.-.-."
code('=)="-...-" code('?)="..--.."
code('@)=".--.-." code('A)=".-"
code('B)="-..." code('C)="-.-."
code('D)="-.." code('E)="."
code('F)="..-." code('G)="--."
code('H)="...." code('I)=".."
code('J)=".---" code('K)="-.-"
code('L)=".-.." code('M)="--"
code('N)="-." code('O)="---"
code('P)=".--." code('Q)="--.-"
code('R)=".-." code('S)="..."
code('T)="-" code('U)="..-"
code('V)="...-" code('W)=".--"
code('X)="-..-" code('Y)="-.--"
code('Z)="--.." code('\)=".-..-."
code('_)="..--.-"
IF PALNTSC=15 THEN
dotDuration=6
ELSE
dotDuration=5
FI
dashDuration=2*dotDuration
intraGapDuration=dotDuration
letterGapDuration=3*intraGapDuration
wordGapDuration=7*intraGapDuration
RETURN
PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC ProcessSound(CHAR ARRAY s BYTE last)
BYTE i
FOR i=1 TO s(0)
DO
Sound(0,30,10,10)
IF s(i)='. THEN
Wait(dotDuration)
ELSE
Wait(dashDuration)
FI
Sound(0,0,0,0)
IF i<s(0) THEN
Wait(intraGapDuration)
FI
OD
RETURN
PROC Process(CHAR ARRAY a)
CHAR ARRAY seq,subs
BYTE i,first,afterSpace
CHAR c
PrintE(a)
first=1
afterSpace=0
FOR i=1 TO a(0)
DO
c=a(i)
IF c>='a AND c<='z THEN
c=c-'a+'A
ELSEIF c>=COUNT THEN
c=0
FI
seq=code(c)
IF seq#0 THEN
IF first=1 THEN
first=0
ELSE
Put(' )
IF afterSpace=0 THEN
Wait(letterGapDuration)
FI
FI
subs=code(c)
Print(subs)
ProcessSound(subs)
afterSpace=0
ELSEIF c=' THEN
Print(" ")
Wait(wordGapDuration)
afterSpace=1
ELSE
afterSpace=0
FI
OD
PutE() PutE()
Wait(wordGapDuration)
RETURN
PROC Main()
Init()
Process("SOS")
Process("Atari Action!")
Process("www.rosettacode.org")
RETURN |
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 host, Monty Hall, who knows what is behind the doors, now has to open one of the two remaining doors, and the door he opens must have a goat behind it.
If both remaining doors have goats behind them, he chooses one randomly.
After Monty Hall opens a door with a goat, he will ask you to decide whether you want to stay with your first choice or to switch to the last remaining door.
Imagine that you chose Door 1 and the host opens Door 3, which has a goat.
He then asks you "Do you want to switch to Door Number 2?"
The question
Is it to your advantage to change your choice?
Note
The player may initially choose any of the three doors (not just Door 1), that the host opens a different door revealing a goat (not necessarily Door 3), and that he gives the player a second choice between the two remaining unopened doors.
Task
Run random simulations of the Monty Hall game. Show the effects of a strategy of the contestant always keeping his first guess so it can be contrasted with the strategy of the contestant always switching his guess.
Simulate at least a thousand games using three doors for each strategy and show the results in such a way as to make it easy to compare the effects of each strategy.
References
Stefan Krauss, X. T. Wang, "The psychology of the Monty Hall problem: Discovering psychological mechanisms for solving a tenacious brain teaser.", Journal of Experimental Psychology: General, Vol 132(1), Mar 2003, 3-22 DOI: 10.1037/0096-3445.132.1.3
A YouTube video: Monty Hall Problem - Numberphile.
| #ActionScript | ActionScript | package {
import flash.display.Sprite;
public class MontyHall extends Sprite
{
public function MontyHall()
{
var iterations:int = 30000;
var switchWins:int = 0;
var stayWins:int = 0;
for (var i:int = 0; i < iterations; i++)
{
var doors:Array = [0, 0, 0];
doors[Math.floor(Math.random() * 3)] = 1;
var choice:int = Math.floor(Math.random() * 3);
var shown:int;
do
{
shown = Math.floor(Math.random() * 3);
} while (doors[shown] == 1 || shown == choice);
stayWins += doors[choice];
switchWins += doors[3 - choice - shown];
}
trace("Switching wins " + switchWins + " times. (" + (switchWins / iterations) * 100 + "%)");
trace("Staying wins " + stayWins + " times. (" + (stayWins / iterations) * 100 + "%)");
}
}
} |
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 \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #AWK | AWK |
# syntax: GAWK -f MODULAR_INVERSE.AWK
# converted from C
BEGIN {
printf("%s\n",mod_inv(42,2017))
exit(0)
}
function mod_inv(a,b, b0,t,q,x0,x1) {
b0 = b
x0 = 0
x1 = 1
if (b == 1) {
return(1)
}
while (a > 1) {
q = int(a / b)
t = b
b = int(a % b)
a = t
t = x0
x0 = x1 - q * x0
x1 = t
}
if (x1 < 0) {
x1 += b0
}
return(x1)
}
|
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 \mathbb {Z} ,\qquad a\,x=1+k\,m}
It can be shown that such an inverse exists if and only if a and m are coprime, but we will ignore this for this task.
Task
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| #BASIC | BASIC |
REM Modular inverse
E = 42
T = 2017
GOSUB CalcModInv:
PRINT ModInv
END
CalcModInv:
REM Increments E Step times until Bal is greater than T
REM Repeats until Bal = 1 (MOD = 1) and returns Count
REM Bal will not be greater than T + E
D = 0
IF E < T THEN
Bal = E
Count = 1
Loop:
Step = T - Bal
Step = Step / E
Step = Step + 1
REM So ... Step = (T - Bal) / E + 1
StepTimesE = Step * E
Bal = Bal + StepTimesE
Count = Count + Step
Bal = Bal - T
IF Bal <> 1 THEN Loop:
D = Count
ENDIF
ModInv = D
RETURN
|
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 language the following:
Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
Write three simple functions: root, addOne, and half
Derive Writer monad versions of each of these functions
Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.) | #Nim | Nim | from math import sqrt
from sugar import `=>`, `->`
type
WriterUnit = (float, string)
WriterBind = proc(a: WriterUnit): WriterUnit
proc bindWith(f: (x: float) -> float; log: string): WriterBind =
result = (a: WriterUnit) => (f(a[0]), a[1] & log)
func doneWith(x: int): WriterUnit =
(x.float, "")
var
logRoot = sqrt.bindWith "obtained square root, "
logAddOne = ((x: float) => x+1'f).bindWith "added 1, "
logHalf = ((x: float) => x/2'f).bindWith "divided by 2, "
echo 5.doneWith.logRoot.logAddOne.logHalf
|
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 language the following:
Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
Write three simple functions: root, addOne, and half
Derive Writer monad versions of each of these functions
Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio φ, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.) | #Perl | Perl | # 20200704 added Perl programming solution
package Writer;
use strict;
use warnings;
sub new {
my ($class, $value, $log) = @_;
return bless [ $value => $log ], $class;
}
sub Bind {
my ($self, $code) = @_;
my ($value, $log) = @$self;
my $n = $code->($value);
return Writer->new( @$n[0], $log.@$n[1] );
}
sub Unit { Writer->new($_[0], sprintf("%-17s: %.12f\n",$_[1],$_[0])) }
sub root { Unit sqrt($_[0]), "Took square root" }
sub addOne { Unit $_[0]+1, "Added one" }
sub half { Unit $_[0]/2, "Divided by two" }
print Unit(5, "Initial value")->Bind(\&root)->Bind(\&addOne)->Bind(\&half)->[1];
|
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #Kotlin | Kotlin | // version 1.2.10
class MList<T : Any> private constructor(val value: List<T>) {
fun <U : Any> bind(f: (List<T>) -> MList<U>) = f(this.value)
companion object {
fun <T : Any> unit(lt: List<T>) = MList<T>(lt)
}
}
fun doubler(li: List<Int>) = MList.unit(li.map { 2 * it } )
fun letters(li: List<Int>) = MList.unit(li.map { "${('@' + it)}".repeat(it) } )
fun main(args: Array<String>) {
val iv = MList.unit(listOf(2, 3, 4))
val fv = iv.bind(::doubler).bind(::letters)
println(fv.value)
} |
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 given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
Construct a List Monad by writing the 'bind' function and the 'pure' (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 -> List Int and Int -> List String
Compose the two functions with bind | #Nim | Nim | import math,sequtils,sugar,strformat
func root(x:float):seq[float] = @[sqrt(x),-sqrt(x)]
func asin(x:float):seq[float] = @[arcsin(x),arcsin(x)+TAU,arcsin(x)-TAU]
func format(x:float):seq[string] = @[&"{x:.2f}"]
#'bind' is a nim keyword, how about an infix operator instead
#our bind is the standard map+cat
func `-->`[T,U](input: openArray[T],f: T->seq[U]):seq[U] =
input.map(f).concat
echo [0.5] --> root --> asin --> format |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.