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
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#M2000_Interpreter
M2000 Interpreter
  Inventory K=0:=0,1:=1 fib=Lambda K (x as decimal)-> { If Exist(K, x) Then =Eval(K) :Exit Def Ret as Decimal Ret=If(x>1->Lambda(x-1)+Lambda(x-2), x) Append K, x:=Ret =Ret } \\ maximum 139 For i=1 to 139 { Print Fib(i) }  
Give a code snippet in #M2000_Interpreter The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive s...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#EchoLisp
EchoLisp
  (define my-list '( albert simon antoinette)) (for ((h my-list)) (write h)) albert simon antoinette   (define my-vector #(55 66 soixante-dix-sept)) (for (( u my-vector)) (write u)) 55 66 soixante-dix-sept   (define my-string "Longtemps") (for ((une-lettre my-string)) (write une-lettre)) "L" "o" "n" "g" "t"...
Give a code snippet in #EchoLisp Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Lambdatalk
Lambdatalk
  {def fdiff {lambda {:l} {A.new {S.map {{lambda {:l :i} {- {A.get {+ :i 1} :l} {A.get :i :l}} } :l} {S.serie 0 {- {A.length :l} 2}}}}}} -> fdiff   {def disp {lambda {:l} {if {A.empty? {A.rest :l}} then else {let { {:l {fdiff :l}} } {br}:l {disp :l}}}}} -> disp   {def L {A.new 90 47 58 29 22 32...
Give a code snippet in #Lambdatalk Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. L...
christopher/rosetta-code
http://rosettacode.org/wiki/Law_of_cosines_-_triples
Law of cosines - triples
The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   this becomes the more familiar ...
#Wren
Wren
var squares13 = {} var squares10000 = {}   var initMaps = Fn.new { for (i in 1..13) squares13[i*i] = i for (i in 1..10000) squares10000[i*i] = i }   var solve = Fn.new { |angle, maxLen, allowSame| var solutions = [] for (a in 1..maxLen) { for (b in a..maxLen) { var lhs = a*a + b*b ...
Give a code snippet in #Wren The Law of cosines states that for an angle γ, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(γ) = C2 Specific angles For an angle of of   90º   t...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#AutoHotkey
AutoHotkey
A := 13 B := 9 N := FourBitAdd(A, B) MsgBox, % A " + " B ":`n" . GetBin4(A) " + " GetBin4(B) " = " N.S " (Carry = " N.C ")" return   Xor(A, B) { return (~A & B) | (A & ~B) }   HalfAdd(A, B) { return {"S": Xor(A, B), "C": A & B} }   FullAdd(A, B, C=0) { X := HalfAdd(A, C) Y := HalfAdd(B, X.S) return {"S": Y.S, "C"...
Give a code snippet in #AutoHotkey Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Ursala
Ursala
(r "f") "x" = "f"("f","x") my_fix "h" = r ("f","x"). ("h" r "f") "x"
Give a code snippet in #Ursala In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a v...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#AutoHotkey
AutoHotkey
MsgBox, % UriEncode("http://foo bar/")   ; Modified from http://goo.gl/0a0iJq UriEncode(Uri) { VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0) StrPut(Uri, &Var, "UTF-8") f := A_FormatInteger SetFormat, IntegerFast, H While Code := NumGet(Var, A_Index - 1, "UChar") If (Code >= 0x30 && Code <= 0x39 ; 0-9 || Code >...
Give a code snippet in #AutoHotkey Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character enc...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#AutoHotkey
AutoHotkey
try BadlyCodedFunc() catch e MsgBox % "Error in " e.What ", which was called at line " e.Line   BadlyCodedFunc() { throw Exception("Fail", -1) }
Give a code snippet in #AutoHotkey Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Excep...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Tcl
Tcl
package require Tcl 8.5 proc palindrome {s} { return [expr {$s eq [string reverse $s]}] }
Give a code snippet in #Tcl A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Arturo
Arturo
loop 0..10 .step:2 'i [ print i ]
Give a code snippet in #Arturo Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/In...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#360_Assembly
360 Assembly
* Comma quibbling 13/03/2017 COMMAQUI CSECT USING COMMAQUI,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...
Give a code snippet in #360_Assembly Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}"....
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Phix
Phix
-- -- demo\rosetta\Archimedean_spiral.exw -- =================================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/) integer {w, h} = IupGetIntInt(canvas, "DRAWSIZE"), a = 0, b = 5, cx = floor(w/2), cy = floor(...
Give a code snippet in #Phix The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#i
i
software { for each 1 to 100 if i % 15 = 0 print("FizzBuzz") else if i % 3 = 0 print("Fizz") else if i % 5 = 0 print("Buzz") else print(i) end end }
Give a code snippet in #i Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz    ...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Raku
Raku
sub twice(&todo) { todo(); todo(); # declaring &todo also defines bare function } twice { say "Boing!" } # output: # Boing! # Boing!   sub twice-with-param(&todo) { todo(0); todo(1); } twice-with-param -> $time { say "{$time+1}: Hello!" } # output: # 1: Hello! # 2: Hello!
Give a code snippet in #Raku Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#E
E
'T' # character "The quick brown fox" # string `The $kind brown fox` # "simple" quasiliteral term`the($adjectives*, fox)` # "term" quasiliteral
Give a code snippet in #E Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Her...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Perl
Perl
use HTTP::Tiny;   my $site = "http://rosettacode.org"; my $list_url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml";   my $response = HTTP::Tiny->new->get("$site$list_url"); for ($response->{content} =~ /cm.*?title="(.*?)"/g) { (my $slug = $_) =~ tr/ /_/; ...
Give a code snippet in #Perl task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program inputXml64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
Give a code snippet in #AArch64_Assembly Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="B...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#R
R
dir("/bar/foo", "mp3",recursive=T)
Give a code snippet in #R Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a d...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#KL1
KL1
  :- module main.   main :- nats(100, Nats), fizzbuzz(Nats, Output), display(Output).   nats(Max, Out) :- nats(Max, 1, Out). nats(Max, Count, Out) :- Count =< Max | Out = [Count|NewOut], NewCount := Count + 1, nats(Max, NewCount, NewOut). nats(Max, Count, Out) :- Count > Max | Out = []. ...
Give a code snippet in #KL1 Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Ruby
Ruby
def kaprekar(n, base = 10) return [1, 1, 1, ""] if n == 1 return if n*(n-1) % (base-1) != 0 # casting out nine sqr = (n ** 2).to_s(base) (1...sqr.length).each do |i| a = sqr[0 ... i] b = sqr[i .. -1] break if b.delete("0").empty? sum = a.to_i(base) + b.to_i(base) return n.to_s(base), sq...
Give a code snippet in #Ruby A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#R
R
# Antiprimes   max_divisors <- 0   findFactors <- function(x){ myseq <- seq(x) myseq[(x %% myseq) == 0] }   antiprimes <- vector() x <- 1 n <- 1 while(length(antiprimes) < 20){ y <- findFactors(x) if (length(y) > max_divisors){ antiprimes <- c(antiprimes, x) max_divisors <- length(y) n <- n + 1 } ...
Give a code snippet in #R The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Limbo
Limbo
implement Hailstone;   include "sys.m"; sys: Sys; include "draw.m";   Hailstone: module { init: fn(ctxt: ref Draw->Context, args: list of string); };   init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH;   seq := hailstone(big 27); l := len seq;   sys->print("hailstone(27): "); for(i :=...
Give a code snippet in #Limbo The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#C
C
Trigraph Replacement letter  ??( [  ??) ]  ??< {  ??> }  ??/ \  ??= #  ??' ^  ??! |  ??- ~
Give a code snippet in #C Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Quackery
Quackery
0 [ 1+ dup echo cr again ]
Give a code snippet in #Quackery Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Beads
Beads
// time_to_str(format, time, city, lang) // format directives: // [sun] - abbreviated weekday, e.g. Sun // [sunday] - full weekday name, e.g. Sunday // [jan] - abbrev month // [january] - full month // [day] - day of the month 1, 2, ..31 // [day2] - day of the month as tw...
Give a code snippet in #Beads This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#Clojure
Clojure
(defn get-color-at [x y] (.getPixelColor (java.awt.Robot.) x y))
Give a code snippet in #Clojure Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#ALGOL_68
ALGOL 68
STRING hostname; get(read OF execve child pipe("/bin/hostname","hostname",""), hostname); print(("hostname: ", hostname, new line))
Give a code snippet in #ALGOL_68 Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Negative_base_numbers
Negative base numbers
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2] Task Encode the decimal number 10 as negabinary (expect 11110) Encode the decimal number 146 as negaternary...
#Wren
Wren
import "/fmt" for Fmt   var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"   var encodeNegBase = Fn.new { |n, b| if (b < -62 || b > -1) Fiber.abort("Base must be between -1 and -62") if (n == 0) return "0" var out = "" while (n != 0) { var rem = n % b n = (n/b)...
Give a code snippet in #Wren Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2] Task Encode the decimal number 10 as negabinary (expect 11110) Encode the dec...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Modula-3
Modula-3
MODULE Logical EXPORTS Main;   FROM IO IMPORT Put; FROM Fmt IMPORT Bool;   PROCEDURE Test(a, b: BOOLEAN) = BEGIN Put("a AND b is " & Bool(a AND b) & "\n"); Put("a OR b is " & Bool(a OR b) & "\n"); Put("NOT a is " & Bool(NOT a) & "\n"); END Test;   BEGIN Test(TRUE, FALSE); END Logical.
Give a code snippet in #Modula-3 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Rust
Rust
  struct Point { x: i32, y: i32 }   fn main() { let mut points: Vec<Point> = Vec::new(); points.append(&mut get_coordinates(1, 20, 20, 28)); points.append(&mut get_coordinates(20, 28, 69, 0)); draw_line(points, 70, 30); }   fn get_coordinates(x1: i32, y1: i32, x2: i32, y2: i32) -> Vec<Point> { ...
Give a code snippet in #Rust Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
solve[sudoku_] := NestWhile[ Join @@ Table[ Table[ReplacePart[s, #1 -> n], {n, #2}] & @@ First@SortBy[{#, Complement[Range@9, s[[First@#]], s[[;; , Last@#]], Catenate@ Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@ Position[s, 0, {2}], L...
Give a code snippet in #Mathematica.2FWolfram_Language Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#AWK
AWK
function isodd(x) { return (x%2)!=0; }   function iseven(x) { return (x%2)==0; }
Give a code snippet in #AWK Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Tcl
Tcl
package require Tcl 8.6 namespace path ::tcl::mathop   # {*} is like apply in Scheme--it turns a list into multiple arguments proc sum_of_squares lst { + {*}[lmap x $lst {* $x $x}] } puts [sum_of_squares {1 2 3 4}]; # ==> 30 puts [sum_of_squares {}]; # ==> 0  
Give a code snippet in #Tcl Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Clojure
Clojure
  (ns a) (def ^:private priv :secret)   ; From REPL, in another namespace 'user': user=> @a/priv ; fails with: IllegalStateException: var: a/priv is not public user=> @#'a/priv ; succeeds :secret  
Give a code snippet in #Clojure Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Erlang
Erlang
  -module(triangle). -export([start/1]). start(N)-> print(1,1,N). print(N,N,N)-> 1; print(A,B,N) when A>=B-> io:format("~p ",[formula(A,B)]), print(A,B+1,N); print(A,B,N) when B>A-> io:format("~n"), print(A+1,1,N).   formula(_,0)-> 0; formula(B,B)-> 1; formula(A,B) when B>A-> 0; formula(A1,B1)-> f...
Give a code snippet in #Erlang This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 ha...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve
Sierpinski arrowhead curve
Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
#Nim
Nim
import math   const Sqrt3_2 = sqrt(3.0) / 2.0   type Point = tuple[x, y: float]     func sierpinskiArrowheadNext(points: seq[Point]): seq[Point] = result.setLen(3 * (points.len - 1) + 1) var j = 0 for i in 0..<points.high: let (x0, y0) = points[i] let (x1, y1) = points[i + 1] let dx = x1 - x0 resu...
Give a code snippet in #Nim Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Axe
Axe
If 1 YEP() End
Give a code snippet in #Axe Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common co...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Liberty_BASIC
Liberty BASIC
  itemCount = 20 dim item(itemCount) for i = 1 to itemCount item(i) = int(rnd(1) * 100) next i print "Before Sort" for i = 1 to itemCount print item(i) next i print: print counter = itemCount do hasChanged = 0 for i = 1 to counter - 1 i...
Give a code snippet in #Liberty_BASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp>   using big_float = boost::multiprecision::cpp_dec_float_100;   big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)...
Give a code snippet in #C.2B.2B Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#Common_Lisp
Common Lisp
  (defun primep (n) ; https://stackoverflow.com/questions/15817350/ (cond ((= 2 n) t) ; Hard-code "2 is a prime" ((= 3 n) t) ; Hard-code "3 is a prime" ((evenp n) nil) ; If we're looking at an even now, i...
Give a code snippet in #Common_Lisp Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop ...
christopher/rosetta-code
http://rosettacode.org/wiki/List_rooted_trees
List rooted trees
You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all...
#Haskell
Haskell
-- break n down into sum of smaller integers parts :: Int -> [[(Int, Int)]] parts n = f n 1 where f n x | n == 0 = [[]] | x > n = [] | otherwise = f n (x + 1) ++ concatMap (\c -> map ((c, x) :) (f (n - c * x) (x + 1))) [1 .. n `div` x]   -- choose n strings ou...
Give a code snippet in #Haskell You came back from grocery shopping.   After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various w...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#HicEst
HicEst
x = value1 /= 0 y = value2 /= 0 NOTx = x == 0 xANDy = x * y xORy = x + y /= 0 EOR = x /= y
Give a code snippet in #HicEst Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Phix
Phix
with javascript_semantics constant LIMIT = 24 include mpfr.e mpz z = mpz_init() sequence fn = repeat(0,LIMIT) fn[1] = 1 integer k = 1 printf(1,"The first %d terms in the sequence are:\n",LIMIT) for i=1 to LIMIT do if is_prime(i) then mpz_ui_pow_ui(z,get_prime(i),i-1) printf(1,"%2d : %s\n",{i,mpz_...
Give a code snippet in #Phix Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Standard_ML
Standard ML
fun sumDigits (0, _) = 0 | sumDigits (n, base) = n mod base + sumDigits (n div base, base)   val testInput = [(1, 10), (1234, 10), (0xfe, 16), (0xf0e, 16)] val () = print (String.concatWith " " (map (Int.toString o sumDigits) testInput) ^ "\n")
Give a code snippet in #Standard_ML Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
w[partitions_]:=Module[{s={},t=Total@partitions,list=partitions,k}, n=Length[list]; While[n>0,s=Join[s,{Take[t,(k=First[list])]}];t=Drop[t,k];list=Rest[list];n--]; s] m[p_]:=(Sort/@#)&/@(w[#,p]&/@Permutations[Range@Total[p]])//Union
Give a code snippet in #Mathematica.2FWolfram_Language In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p ...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#Crystal
Crystal
def self_describing?(n) digits = n.to_s.chars.map(&.to_i) # 12345 => [1, 2, 3, 4, 5] digits.each_with_index.all? { |digit, idx| digits.count(idx) == digit } end   t = Time.monotonic 600_000_000.times { |n| (puts "#{n} in #{(Time.monotonic - t).total_seconds} secs";\ t = Time.monotoni...
Give a code snippet in #Crystal Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#R
R
  suppressMessages(library(gmp)) ONE <- as.bigz("1") TWO <- as.bigz("2") THREE <- as.bigz("3") FOUR <- as.bigz("4") SEVEN <- as.bigz("7") TEN <- as.bigz("10")   q <- as.bigz("1") r <- as.bigz("0") t <- as.bigz("1") k <- as.bigz("1") n <- as.bigz("3") l <- as.bigz("3")   char_printed <- 0   how_many <- 1000   first <- T...
Give a code snippet in #R Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#zkl
zkl
var BN=Import("zklBigNum"); a:=BN("2988348162058574136915891421498819466320163312926952423791023078876139"); b:=BN("2351399303373464486466122544523690094744975233415544072992656881240319"); m:=BN(10).pow(40); a.powm(b,m).println(); a.powm(b,m) : "%,d".fmt(_).println();
Give a code snippet in #zkl Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Ruby
Ruby
def fibonacci_word(n) words = ["1", "0"] (n-1).times{ words << words[-1] + words[-2] } words[n] end   def print_fractal(word) area = Hash.new(" ") x = y = 0 dx, dy = 0, -1 area[[x,y]] = "S" word.each_char.with_index(1) do |c,n| area[[x+dx, y+dy]] = dx.zero? ? "|" : "-" x, y = x+2*dx, y+2*dy ...
Give a code snippet in #Ruby The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#PicoLisp
PicoLisp
(de closestPairBF (Lst) (let Min T (use (Pt1 Pt2) (for P Lst (for Q Lst (or (== P Q) (>= (setq N (let (A (- (car P) (car Q)) B (- (cdr P) (cdr Q))) (+ (* A A) (* B B)...
Give a code snippet in #PicoLisp This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#PicoLisp
PicoLisp
(de disdate (Year Month Day) (let? Date (date Year Month Day) (let (Leap (date Year 2 29) D (- Date (date Year 1 1))) (if (and Leap (= 2 Month) (= 29 Day)) (pack "St. Tib's Day, YOLD " (+ Year 1166)) (and Leap (>= D 60) (dec 'D)) (pack (get ...
Give a code snippet in #PicoLisp Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Argile
Argile
use std printf "%f\n" atof "infinity" (: this prints "inf" :) #extern :atof<text>: -> real
Give a code snippet in #Argile Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Run_BASIC
Run BASIC
function stripchars(texto, remove) s = texto for i = 1 to length(remove) s = replace(s, mid(remove, i, 1), "", true) next i   return s end function
Give a code snippet in #Run_BASIC Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters ...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Dart
Dart
  main() { var total = 0; var empty = <int>[]; for (var year = 1900; year < 2101; year++) { var months = [1, 3, 5, 7, 8, 10, 12].where((m) => DateTime(year, m, 1).weekday == 5); print('$year\t$months'); total += months.length; if (months.isEmpty) empty.add(year); } print('Total: $total...
Give a code snippet in #Dart The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there...
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#D
D
import std.stdio, std.datetime;   void printEasterRelatedHolidays(in int year) { static struct Holyday { string name; int offs; } static immutable Holyday[] holidayOffsets = [{"Easter", 0}, {"Ascension", 39}, ...
Give a code snippet in #D Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Scala
Scala
object BoxingTheCompass extends App { val cardinal = List("north", "east", "south", "west") val pointDesc = List("1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1")   val pointDeg: Int => Double = i => { val fswitch: Int => Int = i => i match {case 1 => 1; case 2 => -1; case _ => 0} i*11.25+fswitch(...
Give a code snippet in #Scala There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and di...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program 2048_64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64...
Give a code snippet in #AArch64_Assembly Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direc...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Ada
Ada
  package Prisoners is   type Win_Percentage is digits 2 range 0.0 .. 100.0; type Drawers is array (1 .. 100) of Positive;   function Play_Game (Repetitions : in Positive; Strategy  : not null access function (Cupboard  : in Drawers; Max_Prisoners : Integer; Max_Attempts : ...
Give a code snippet in #Ada The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start out...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ say "Number of trials: " dup echo cr 0 ( heads count ) 0 ( sleeps count ) rot times [ 1+ 2 random if [ 1+ dip 1+ ] ] say "Data: heads count: " over echo cr say " sleeps count: " dup echo cr say "Credence of heads:...
Give a code snippet in #Quackery Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a...
christopher/rosetta-code
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#Racket
Racket
  > (require math) > (matrix-qr (matrix [[12 -51 4] [ 6 167 -68] [-4 24 -41]])) (array #[#[6/7 -69/175 -58/175] #[3/7 158/175 6/175] #[-2/7 6/35 -33/35]]) (array #[#[14 21 -14] #[0 175 -70] #[0 0 35]])  
Give a code snippet in #Racket Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Vlang
Vlang
import rand import rand.seed import os   fn main() { seed_array := seed.time_seed_array(2) rand.seed(seed_array) num := rand.intn(10) + 1 // Random number 1-10 for { print('Please guess a number from 1-10 and press <Enter>: ') guess := os.get_line() if guess.int() == num { ...
Give a code snippet in #Vlang Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Oz
Oz
declare fun {DropUntil Xs Prefix} case Xs of nil then nil [] _|Xr then if {List.isPrefix Prefix Xs} then Xs else {DropUntil Xr Prefix} end end end   Digits = "1234567890" in {ForAll [{List.take {List.drop Digits 2} 3} = "345" {List.drop Digits 2} ...
Give a code snippet in #Oz Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Con...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Ruby
Ruby
require 'rubygems' require 'gl' require 'glut'   W, H = 320, 240 SIZE = W * H   Glut.glutInit ARGV Glut.glutInitWindowSize W, H   Glut.glutIdleFunc lambda { i = Time.now noise = (1..SIZE).map { rand > 0.5 ? 0xFFFFFFFF : 0xFF000000 }.pack("I*")   Gl.glClear Gl::GL_COLOR_BUFFER_BIT Gl.glDrawPixels W, H, Gl::GL_RG...
Give a code snippet in #Ruby Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#EchoLisp
EchoLisp
  ;; ppows ;; input : a list g of grouped prime factors ( 3 3 3 ..) ;; returns (1 3 9 27 ...)   (define (ppows g (mult 1)) (for/fold (ppows '(1)) ((a g)) (set! mult (* mult a)) (cons mult ppows)))   ;; factors ;; decomp n into ((2 2 ..) ( 3 3 ..) ) prime factors groups ;; combines (1 2 4 8 ..) (1 3 9 ..) li...
Give a code snippet in #EchoLisp Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Forth
Forth
:noname ( n -- n' ) dup 2 < ?exit 1- dup recurse swap 1- recurse + ; ( xt )   : fib ( +n -- n' ) dup 0< abort" Negative numbers don't exist." [ ( xt from the :NONAME above ) compile, ] ;
Give a code snippet in #Forth While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwant...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program dateFormat.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */   /*************************************...
Give a code snippet in #ARM_Assembly This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Delphi
Delphi
  program geometric_mean;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function Fabs(value: Double): Double; begin Result := value; if Result < 0 then Result := -Result; end;   function agm(a, g: Double):Double; var iota, a1, g1: Double; begin iota := 1.0E-16; if a * g < 0.0 then begin Writeln('...
Give a code snippet in #Delphi This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function ...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#EasyLang
EasyLang
len v[] 6 repeat vsum = 0 vmin = 0 for i range 6 val = 0 min = 6 for j range 4 h = random 6 + 1 val += h if h < min min = h . . val -= min v[i] = val if val >= 15 vmin += 1 . vsum += val . until vsum >= 75 and vmin >= 2 . print "Attribu...
Give a code snippet in #EasyLang RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Icon_and_Unicon
Icon and Unicon
fruits := [ "apple", "banana", "cherry", "apple" ] # a list keeps ordered data fruits := set("apple", "banana", "cherry") # a set keeps unique data fruits := table() # table keeps an unique data with values fruits["apple"] := 1 fruits["banana"] := 2 fruits["cher...
Give a code snippet in #Icon_and_Unicon Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Haskell
Haskell
#!/usr/bin/runhaskell   import Data.Numbers.Primes import Control.Monad (guard)   carmichaels = do p <- takeWhile (<= 61) primes h3 <- [2..(p-1)] let g = h3 + p d <- [1..(g-1)] guard $ (g * (p - 1)) `mod` d == 0 && (-1 * p * p) `mod` h3 == d `mod` h3 let q = 1 + (((p - 1) * g) `div` d) guard $ isPrime q ...
Give a code snippet in #Haskell A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to inv...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#BASIC
BASIC
10 LIST
Give a code snippet in #BASIC A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const pi As Double = 3.141592653589793   Function sumSeries (n As UInteger) As Double If n = 0 Then Return 0 Dim sum As Double = 0 For k As Integer = 1 To n sum += 1.0/(k * k) Next Return sum End Function   Print "s(1000) = "; sumSeries(1000) Print "zeta(2) = "; Pi * pi / 6 Print Print...
Give a code snippet in #FreeBASIC Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Zig
Zig
const std = @import("std");   const debug = std.debug; const heap = std.heap; const process = std.process;   pub fn main() !void { var args = process.args();   const program_name = try args.next(heap.page_allocator) orelse unreachable; defer heap.page_allocator.free(program_name);   debug.warn("{}\n", ....
Give a code snippet in #Zig The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script na...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#C
C
using System; class Point { protected int x, y; public Point() : this(0) {} public Point(int x) : this(x,0) {} public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public virtual void print() { Sy...
Give a code snippet in #C Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Inform_7
Inform 7
let N be 1024; while N > 0: say "[N][line break]"; let N be N / 2;
Give a code snippet in #Inform_7 Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Down...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Logo
Logo
show apply "sum readlist
Give a code snippet in #Logo A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Yorick
Yorick
func stoogesort(&L, i, j) { if(is_void(i)) i = 1; if(is_void(j)) j = numberof(L); if(L(j) < L(i)) L([i,j]) = L([j,i]); if(j - i > 1) { t = (j - i + 1)/3; stoogesort, L, i, j-t; stoogesort, L, i+t, j; stoogesort, L, i, j-t; } }
Give a code snippet in #Yorick Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Lua
Lua
function MatMul( m1, m2 ) if #m1[1] ~= #m2 then -- inner matrix-dimensions must agree return nil end   local res = {}   for i = 1, #m1 do res[i] = {} for j = 1, #m2[1] do res[i][j] = 0 for k = 1, #m2 do res[i][j] = res[i][j] + ...
Give a code snippet in #Lua Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Elena
Elena
import extensions; import system'collections;   singleton Alphabet : Enumerable { Enumerator enumerator() = new Enumerator { char current;   get() = current;   bool next() { if (nil==current) { current := $97 } else ...
Give a code snippet in #Elena Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#MatLab
MatLab
  abundant=0; deficient=0; perfect=0; p=[]; for N=2:20000 K=1:ceil(N/2); D=K(~(rem(N, K))); sD=sum(D); if sD<N deficient=deficient+1; elseif sD==N perfect=perfect+1; else abundant=abundant+1; end end disp(table([deficient;perfect;abundant],'RowNames',{'Deficient','Per...
Give a code snippet in #MatLab These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficien...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#11l
11l
F lpd(n) L(i) (n - 1 .< 0).step(-1) I n % i == 0 R i R 1   L(i) 1..100 print(‘#3’.format(lpd(i)), end' I i % 10 == 0 {"\n"} E ‘’)
Give a code snippet in #11l Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#Wren
Wren
var mianChowla = Fn.new { |n| var mc = List.filled(n, 0) var sums = {} var ts = {} mc[0] = 1 sums[2] = true for (i in 1...n) { var j = mc[i-1] + 1 while (true) { mc[i] = j for (k in 0..i) { var sum = mc[k] + j if (sums[sum])...
Give a code snippet in #Wren The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Python
Python
"""A Maybe Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations   from typing import Any from typing import Callable from typing import Generic from typing import Optional from typing import TypeVar from typing import Union     T = TypeVar("T")     class Maybe(Generic[T]): def __init_...
Give a code snippet in #Python 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 re...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#Red
Red
Red[] seed: 675248 rand: does [seed: to-integer (seed * 1.0 * seed / 1000) % 1000000] ; multiply by 1.0 to avoid integer overflow (32-bit) loop 5 [print rand]
Give a code snippet in #Red Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the resu...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#Red
Red
Red [ Title: "Bitwise IO" Link: http://rosettacode.org/wiki/Bitwise_IO Source: https://github.com/vazub/rosetta-red File: "%bitwiseio.red" Rights: "Copyright (C) 2020 Vasyl Zubko. All rights reserved." License: "Blue Oak Model License - https://blueoakcouncil.org/lice...
Give a code snippet in #Red The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the out...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Ruby
Ruby
module OperatingSystem require 'rbconfig' module_function def operating_system case RbConfig::CONFIG["host_os"] when /linux/i :linux when /cygwin|mswin|mingw|windows/i :windows when /darwin/i :mac when /solaris/i :solaris else nil end end def linux?; ...
Give a code snippet in #Ruby Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Objeck
Objeck
class ShortCircuit { function : a(a : Bool) ~ Bool { "a"->PrintLine(); return a; }   function : b(b : Bool) ~ Bool { "b"->PrintLine(); return b; }   function : Main(args : String[]) ~ Nil { result := a(false) & b(false); "F and F = {$result}"->PrintLine(); result := a(false) | b(fa...
Give a code snippet in #Objeck Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable re...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Python
Python
  import random   def rand9999(): return random.randint(1000, 9999)   def tag(attr='', **kwargs): for tag, txt in kwargs.items(): return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())   if __name__ == '__main__': header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n' rows =...
Give a code snippet in #Python Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#PHP
PHP
  function median($arr) { sort($arr); $count = count($arr); //count the number of values in array $middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value if ($count % 2) { // odd number, middle is the median $median = $arr[$middleval]; } else { // even number, ...
Give a code snippet in #PHP Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle Sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Go
Go
package main   import "fmt"   func circleSort(a []int, lo, hi, swaps int) int { if lo == hi { return swaps } high, low := hi, lo mid := (hi - lo) / 2 for lo < hi { if a[lo] > a[hi] { a[lo], a[hi] = a[hi], a[lo] swaps++ } lo++ hi-- }...
Give a code snippet in #Go Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Colorful_numbers
Colorful numbers
A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 Every product is unique. 2346 ...
#Haskell
Haskell
import Data.List ( nub ) import Data.List.Split ( divvy ) import Data.Char ( digitToInt )   isColourful :: Integer -> Bool isColourful n |n >= 0 && n <= 10 = True |n > 10 && n < 100 = ((length s) == (length $ nub s)) && (not $ any (\c -> elem c "01") s) |n >= 100 = ((length s) == (length $ nub s)) && (...
Give a code snippet in #Haskell A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Perl
Perl
use strict; use warnings; use ntheory qw<is_prime>; use constant Inf => 1e10;   sub is_Brazilian { my($n) = @_; return 1 if $n > 6 && 0 == $n%2; LOOP: for (my $base = 2; $base < $n - 1; ++$base) { my $digit; my $nn = $n; while (1) { my $x = $nn % $base; $digi...
Give a code snippet in #Perl Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#C
C
#include <stdio.h>   unsigned int divisor_count(unsigned int n) { unsigned int total = 1; unsigned int p;   // Deal with powers of 2 first for (; (n & 1) == 0; n >>= 1) { ++total; } // Odd prime factors up to the square root for (p = 3; p * p <= n; p += 2) { unsigned int coun...
Give a code snippet in #C A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Smalltalk
Smalltalk
Stderr nextPutAll: 'Goodbye, World!'
Give a code snippet in #Smalltalk Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   var bigInteger: total is 0_; var bigInteger: prim is 0_; var bigInteger: max_peri is 10_;   const proc: new_tri (in bigInteger: a, in bigInteger: b, in bigInteger: c) is func local var bigInteger: p is 0_; begin p := a + b + c; if p <= max_peri then ...
Give a code snippet in #Seed7 A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Groovy
Groovy
def cruncher = { x1, x2, program -> Eval.x(x1, program) - Eval.x(x2, program) }
Give a code snippet in #Groovy x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples an...
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific la...
#Erlang
Erlang
  -module(currying).   -compile(export_all).   % Function that curry the first or the second argument of a given function of arity 2   curry_first(F,X) -> fun(Y) -> F(X,Y) end.   curry_second(F,Y) -> fun(X) -> F(X,Y) end.   % Usual curry   curry(Fun,Arg) -> case erlang:fun_info(Fun,arity) of {arity,0} -> ...
Give a code snippet in #Erlang This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative exam...
christopher/rosetta-code
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. ...
#D
D
import std.stdio;   /* * Using just what is built-in, D only supports single dimension arrays. Like other languages, arrays can be built up as jagged arrays. * Arrays can either be created with a fixed size, or dynamically with support for resizing. */ void nativeExample() { int[3] staticArray; // Statically all...
Give a code snippet in #D 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Raku
Raku
sub expmod(Int $a is copy, Int $b is copy, $n) { my $c = 1; repeat while $b div= 2 { ($c *= $a) %= $n if $b % 2; ($a *= $a) %= $n; } $c; }   say expmod 2988348162058574136915891421498819466320163312926952423791023078876139, 23513993033734644864661225445236900947449752334155440729...
Give a code snippet in #Raku Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#PL.2FI
PL/I
Soundex: procedure (pword) returns (character(4)); declare pword character (*) varying, value character (length(pword)) varying; declare word character (length(pword)); declare (prevCode, currCode) character (1); declare alphabet CHARACTER (26) STATIC INITIAL ('AEIOUHWYBFPVCGJKQSXZDTLMNR'); declare repla...
Give a code snippet in #PL.2FI Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There ...
christopher/rosetta-code