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/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Ruby
Ruby
def sign(x) x <=> 0 end   def find_roots(f, range, step=0.001) sign = sign(f[range.begin]) range.step(step) do |x| value = f[x] if value == 0 puts "Root found at #{x}" elsif sign(value) == -sign puts "Root found between #{x-step} and #{x}" end sign = sign(value) end end   f = lam...
Give a code snippet in #Ruby Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
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...
#ArnoldC
ArnoldC
LISTEN TO ME VERY CAREFULLY isOdd I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE n GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE result YOU SET US UP @I LIED GET TO THE CHOPPER result HERE IS MY INVITATION n I LET HIM GO 2 ENOUGH TALK I'LL BE BACK result HASTA LA VISTA, BABY   LISTEN TO ME VERY CAREFULLY showParity I NE...
Give a code snippet in #ArnoldC 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. Di...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#360_Assembly
360 Assembly
* Intersection of two lines 01/03/2019 INTERSEC CSECT USING INTERSEC,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) li...
Give a code snippet in #360_Assembly [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
christopher/rosetta-code
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 ) ) , ...
#F.23
F#
let rec f n = match n with | 0 -> 1 | _ -> n - (m (f (n-1))) and m n = match n with | 0 -> 0 | _ -> n - (f (m (n-1)))
Give a code snippet in #F.23 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 )...
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 ......
#Ruby
Ruby
pi_digits = Enumerator.new do |y| q, r, t, k, n, l = 1, 0, 1, 1, 3, 3 loop do if 4*q+r-t < n*t y << n nr = 10*(r-n*t) n = ((10*(3*q+r)) / t) - 10*n q *= 10 r = nr else nr = (2*q+r) * l nn = (q*(7*k+2)+r*l) / (t*l) q *= k t *= l l += 2 k += 1...
Give a code snippet in #Ruby 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 seque...
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 ...
#F.23
F#
  // We can use Some as return, Option.bind and the pipeline operator in order to have a very concise code     let f1 (v:int) = Some v // int -> Option<int> let f2 (v:int) = Some(string v) // int -> Option<sting>   f1 4 |> Option.bind f2 |> printfn "Value is %A" // bind when option (maybe) has data None |> Option.bin...
Give a code snippet in #F.23 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 retu...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#FutureBasic
FutureBasic
  include "NSLog.incl"   local fn ObserverOne( ref as NotificationRef ) FileHandleRef fh = fn NotificationObject( ref ) CFDataRef dta = fn FileHandleAvailableData( fh )   if ( fn DataLength( dta ) > 0 ) CFStringRef string = fn StringWithData( dta, NSUTF8StringEncoding ) NSLog( @"%@", string ) FileHandleWaitForDataIn...
Give a code snippet in #FutureBasic Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
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. ...
#F.23
F#
  // Count digits in number let digits x = let rec digits' p x = if 10.**p > x then p else digits' (p + 1.) x digits' 1. x     // Is n a Kaprekar number? let isKaprekar n = // Reference: http://oeis.org/A006886 // Positive numbers n such that n=q+r // And n^2=q*10^m+r, // for some m >= ...
Give a code snippet in #F.23 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/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#Zig
Zig
const std = @import("std");   var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);   const allocator = arena.allocator();   pub fn LinkedList(comptime Value: type) type { return struct { const This = @This();   const Node = struct { value: Value, next: ?*Node, ...
Give a code snippet in #Zig singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Conjugate_transpose
Conjugate transpose
Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ( M H ) j i = M i j ...
#PARI.2FGP
PARI/GP
conjtranspose(M)=conj(M~) isHermitian(M)=M==conj(M~) isnormal(M)=my(H=conj(M~));H*M==M*H isunitary(M)=M*conj(M~)==1
Give a code snippet in #PARI.2FGP Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Tcl
Tcl
# Used once to turn the table into a "nice" form proc parseTable table { set map {} set LINE_RE {^ *>= *([0-9.]+) *< *([0-9.]+) *:= *([0-9.]+) *$} foreach line [split $table \n] { if {[string trim $line] eq ""} continue if {[regexp $LINE_RE $line -> min max target]} { lappend map $min $max $target }...
Give a code snippet in #Tcl A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Cowgol
Cowgol
include "cowgol.coh";   # Find the N'th digit in the Thue-Morse sequence sub tm(n: uint32): (d: uint8) is var n2 := n; while n2 != 0 loop n2 := n2 >> 1; n := n ^ n2; end loop; d := (n & 1) as uint8; end sub;   # Print the first 64 digits var i: uint32 := 0; while i < 64 loop print_ch...
Give a code snippet in #Cowgol Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#Phix
Phix
-- -- demo\rosetta\DrawRotatingCube.exw -- ================================= -- -- credits: http://petercollingridge.appspot.com/3D-tutorial/rotating-objects -- https://github.com/ssloy/tinyrenderer/wiki/Lesson-4:-Perspective-projection -- -- Aside: low CPU usage, at least when using a 30ms timer (33 FPS, whic...
Give a code snippet in #Phix Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspec...
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#PureBasic
PureBasic
If OpenConsole() And ReadFile(0,"data.txt") PrintN("Those earthquakes with a magnitude > 6.0 are:") While Not Eof(0) buf$=Trim(ReadString(0)) If ValF((StringField(buf$,CountString(buf$," ")+1," ")))>6.0 PrintN(buf$) EndIf Wend CloseFile(0) Input() EndIf
Give a code snippet in #PureBasic Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example li...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Ruby
Ruby
require 'date'   def last_friday(year, month) # Last day of month: Date.new interprets a negative number as a relative month/day from the end of year/month. d = Date.new(year, month, -1) d -= (d.wday - 5) % 7 # Subtract days after Friday. end   year = Integer(ARGV.shift) (1..12).each {|month| puts last_friday(ye...
Give a code snippet in #Ruby Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#MUMPS
MUMPS
  STRCASE(S) SET UP="ABCDEFGHIJKLMNOPQRSTUVWXYZ" SET LO="abcdefghijklmnopqrstuvwxyz" WRITE !,"Given: "_S WRITE !,"Upper: "_$TRANSLATE(S,LO,UP) WRITE !,"Lower: "_$TRANSLATE(S,UP,LO) QUIT  
Give a code snippet in #MUMPS Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not r...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Bracmat
Bracmat
("---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert -----------------------"  : ?text & ( reverse = token tokens reversed ...
Give a code snippet in #Bracmat Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by sp...
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#MiniScript
MiniScript
exits = [[1,4,7], [0,2,9], [1,3,11], [2,4,13], [0,3,5], [4,6,14], [5,7,16], [0,6,8], [7,9,17], [1,8,10], [9,11,18], [2,10,12], [11,13,19], [3,12,14], [5,13,15], [14,16,19], [6,15,17], [8,16,18], [10,17,19], [12,15,18]] hazard = [null] * 20 emptyRoom = function() while true room = floor(rnd * 20) if not hazar...
Give a code snippet in #MiniScript This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) write(ExpandText( if !arglist == "icon" then "14/\\\n14\\/\n12/\\\n11/1/\n10/1/1/\\\n10\\/1/2\\\n12/1/\\1\\\n_ 12\\1\\1\\/\n10/\\1\\1\\2/\\\n9/2\\1\\/1/2\\\n_ 8/1/\\1\\2/1/\\1\\2/\\\n8\\1\\/1/2\\1\\/1/2\\1\\\n_ 6/\\1\\2/4\\2/1/\\1\\1\\\n5/1/2\\/6\\/1/2\\1\\/\n_ ...
Give a code snippet in #Icon_and_Unicon Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#AWK
AWK
# WST.AWK - Waclaw Sierpinski's triangle contributed by Dan Nielsen # syntax: GAWK -f WST.AWK [-v X=anychar] iterations # example: GAWK -f WST.AWK -v X=* 2 BEGIN { n = ARGV[1] + 0 # iterations if (n !~ /^[0-9]+$/) { exit(1) } if (n == 0) { width = 3 } row = split("X,X X,X X,X X X X",A,",") # seed the ...
Give a code snippet in #AWK Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local...
#JavaScript
JavaScript
const net = require('net');   function handleClient(conn) { console.log('Connection from ' + conn.remoteAddress + ' on port ' + conn.remotePort);   conn.setEncoding('utf-8');   let buffer = '';   function handleData(data) { for (let i = 0; i < data.length; i++) { const char = data.ch...
Give a code snippet in #JavaScript Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessa...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Go
Go
package main   import ( "fmt" "strconv" )   func listProperDivisors(limit int) { if limit < 1 { return } width := len(strconv.Itoa(limit)) for i := 1; i <= limit; i++ { fmt.Printf("%*d -> ", width, i) if i == 1 { fmt.Println("(None)") continue ...
Give a code snippet in #Go The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Fortran
Fortran
e ! Not available. Can be calculated EXP(1.0) pi ! Not available. Can be calculated 4.0*ATAN(1.0) SQRT(x) ! square root LOG(x) ! natural logarithm LOG10(x) ! logarithm to base 10 EXP(x) ! exponential ABS(x) ! absolute value FLOOR(x) ! floor - Fortran 90 or later only CEILING...
Give a code snippet in #Fortran Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
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 ...
#Phix
Phix
with javascript_semantics function cocktailShakerSort(sequence s) s = deep_copy(s) integer beginIdx = 1, endIdx = length(s)-1 while beginIdx <= endIdx do integer newBeginIdx = endIdx, newEndIdx = beginIdx for ii=beginIdx to endIdx do object si = s[ii]...
Give a code snippet in #Phix 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#XPL0
XPL0
proc QPrint(Q); \Display quaternion real Q; [RlOut(0, Q(0)); Text(0, " + "); RlOut(0, Q(1)); Text(0, "i + "); RlOut(0, Q(2)); Text(0, "j + "); RlOut(0, Q(3)); Text(0, "k"); CrLf(0); ]; func real QNorm(Q); \Return norm of a quaternion real Q; return sqrt( Q(0)*Q(0) + Q(1)*Q(1) + Q(2)...
Give a code snippet in #XPL0 Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number m...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Limbo
Limbo
implement HelloWorld;   include "sys.m"; sys: Sys; include "draw.m";   HelloWorld: module { init: fn(nil: ref Draw->Context, nil: list of string); };   init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; sys->print("Goodbye, World!"); # No automatic newline. }
Give a code snippet in #Limbo Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Stand...
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      ...
#Prolog
Prolog
quine :- listing(quine).
Give a code snippet in #Prolog 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/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 ...
#Pascal
Pascal
procedure bubble_sort(var list: array of real); var i, j, n: integer; t: real; begin n := length(list); for i := n downto 2 do for j := 0 to i - 1 do if list[j] > list[j + 1] then begin t := list[j]; list[j] := list[j + 1]; list[j + 1] := t; end; end;
Give a code snippet in #Pascal 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/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#J
J
mu =: 0:`(1 - 2 * 2|#@{.)@.(1: = */@{:)@(2&p:)"0 M =: +/@([: mu 1:+i.)   m1000 =: (M"0) 1+i.1000 zero =: +/ m1000 = 0 cross =: +/ (-.*.1:|]) m1000 ~: 0   echo 'The first 99 Merten numbers are' echo 10 10$ __, 99{.m1000 echo 'M(N) is zero ',(":zero),' times.' echo 'M(N) crosses zero ',(":cross),' times.' exit''
Give a code snippet in #J The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#Wren
Wren
var start = System.clock var n = 250 var m = 30   var p5 = List.filled(n+m+1, 0) var s = 0 while (s < n) { var sq = s * s p5[s] = sq * sq * s s = s + 1 } var max = p5[n-1] while (s < p5.count) { p5[s] = max + 1 s = s + 1 } for (a in 1...n-3) { for (b in a + 1...n-2) { for (c in b + 1...n...
Give a code snippet in #Wren There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Vlang
Vlang
fn is_prime(n int) bool { if n < 2 { return false } else if n%2 == 0 { return n == 2 } else if n%3 == 0 { return n == 3 } else { mut d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d ==...
Give a code snippet in #Vlang Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Kotlin
Kotlin
fun main() { println("First 10 terms of Van Eck's sequence:") vanEck(1, 10) println("") println("Terms 991 to 1000 of Van Eck's sequence:") vanEck(991, 1000) }   private fun vanEck(firstIndex: Int, lastIndex: Int) { val vanEckMap = mutableMapOf<Int, Int>() var last = 0 if (firstIndex == ...
Give a code snippet in #Kotlin The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occure...
christopher/rosetta-code
http://rosettacode.org/wiki/Kronecker_product_based_fractals
Kronecker product based fractals
This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matrix   (filled with 0/1)   we ...
#JavaScript
JavaScript
  // KPF.js 6/23/16 aev // HFJS: Plot any matrix mat (filled with 0,1) function pmat01(mat, color) { // DCLs var cvs = document.getElementById('canvId'); var ctx = cvs.getContext("2d"); var w = cvs.width; var h = cvs.height; var m = mat[0].length; var n = mat.length; // Cleaning canvas and setting plotting...
Give a code snippet in #JavaScript This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#PARI.2FGP
PARI/GP
Mod(1/42,2017)
Give a code snippet in #PARI.2FGP 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#BASIC
BASIC
FOR i = 1 TO 5 FOR j = 1 TO i PRINT "*"; NEXT j PRINT NEXT i
Give a code snippet in #BASIC “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Ring
Ring
  # Project : Jensen's Device   decimals(14) i = 100 see sum(i,1,100,"1/n") + nl   func sum(i,lo,hi,term) temp = 0 for n = lo to hi step 1 eval("num = " + term) temp = temp + num next return temp  
Give a code snippet in #Ring Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGO...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program insertionSort.s */ /* look Pseudocode begin this task */   /************************************/ /* Constantes */ /************************************/ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 ...
Give a code snippet in #ARM_Assembly 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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#LFE
LFE
  > (set encoded (binary ("åäö ð" utf8))) #B(195 165 195 164 195 182 32 195 176)  
Give a code snippet in #LFE As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is y...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_simple
Abbreviations, simple
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 ...
#Wren
Wren
import "/fmt" for Fmt import "/str" for Str   var table = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2...
Give a code snippet in #Wren The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#GAP
GAP
# Built-in Combinations([1 .. n], m);   Combinations([1 .. 5], 3); # [ [ 1, 2, 3 ], [ 1, 2, 4 ], [ 1, 2, 5 ], [ 1, 3, 4 ], [ 1, 3, 5 ], # [ 1, 4, 5 ], [ 2, 3, 4 ], [ 2, 3, 5 ], [ 2, 4, 5 ], [ 3, 4, 5 ] ]
Give a code snippet in #GAP Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and computer science, the Levenshtein ...
#Clojure
Clojure
(defn levenshtein [str1 str2] (let [len1 (count str1) len2 (count str2)] (cond (zero? len1) len2 (zero? len2) len1 :else (let [cost (if (= (first str1) (first str2)) 0 1)] (min (inc (levenshtein (rest str1) str2)) (inc (levenshtein str1 (rest str2...
Give a code snippet in #Clojure This page uses content from Wikipedia. The original article was at Levenshtein distance. 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) In information theory and c...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Raku
Raku
sub make-List ($separator = ') '){ my $count = 1;   sub make-Item ($item) { "{$count++}$separator$item" }   join "\n", <first second third>».&make-Item; }   put make-List('. ');
Give a code snippet in #Raku In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in th...
#D
D
void main() { import std.stdio, std.algorithm, std.range, std.typecons;   const s1 = cartesianProduct(iota(1, 101), iota(1, 101)) .filter!(p => 1 < p[0] && p[0] < p[1] && p[0] + p[1] < 100) .array;   alias P = const Tuple!(int, int); enum add = (P p) => p[0] + p[1]; e...
Give a code snippet in #D Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P kno...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#MATLAB_.2F_Octave
MATLAB / Octave
[m,z] = filter(ones(1,P),P,x);
Give a code snippet in #MATLAB_.2F_Octave Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#Factor
Factor
USING: sequences xml.syntax xml.writer ;   : print-character-remarks ( names remarks -- ) [ [XML <Character name=<-> ><-></Character> XML] ] 2map [XML <CharacterRemarks><-></CharacterRemarks> XML] pprint-xml ;
Give a code snippet in #Factor Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> e...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_outline_at_every_level
Sort an outline at every level
Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure clear. Your code should detec...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Sort_an_outline_at_every_level use warnings;   for my $test ( split /^(?=#)/m, join '', <DATA> ) { my ( $id, $outline ) = $test =~ /(\V*?\n)(.*)/s; my $sorted = validateandsort( $outline, $id =~ /descend/ ); print $test, '=' x 20, " answer:\n$sorted\n...
Give a code snippet in #Perl Task Write and test a function over an indented plain text outline which either: Returns a copy of the outline in which the sub-lists at every level of indentation are sorted, or reports that the indentation characters or widths are not consistent enough to make the outline structure c...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#J
J
ef =: [: (}.~ 0={.) [: (, r2ef)/ 0 1 #: x: r2ef =: (<(<0);0) { ((] , -) >:@:<.&.%)^:((~:<.)@:%)@:{:^:a:
Give a code snippet in #J An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unit...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Quackery
Quackery
$ "input.txt" sharefile drop temp put temp share $ "output.txt" putfile drop  
Give a code snippet in #Quackery File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a fil...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Racket
Racket
#lang racket (require 2htdp/image)   ;; The unsafe fixnum ops are faster than the checked ones, ;; but if you get anything wrong with them, they'll bite. ;; If you experience any problems reactivate the ;; (require racket/fixnum) and instead of the unsafe requirement ;; below...   ;; we have tested this... #;(require r...
Give a code snippet in #Racket Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initi...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#IS-BASIC
IS-BASIC
100 PROGRAM "Pig.bas" 110 RANDOMIZE 120 STRING PLAYER$(1 TO 2)*28 130 NUMERIC POINTS(1 TO 2),VICTORY(1 TO 2) 140 LET WINNINGSCORE=100 150 TEXT 40:PRINT "Let's play Pig!";CHR$(241):PRINT 160 FOR I=1 TO 2 170 PRINT "Player";I 180 INPUT PROMPT "Whats your name? ":PLAYER$(I) 190 LET POINTS(I)=0:LET VICTORY(I)=0:PRI...
Give a code snippet in #IS-BASIC The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Racket
Racket
  #lang racket (define (carpet n) (if (zero? n) '("#") (let* ([prev (carpet (sub1 n))] [spaces (regexp-replace* #rx"#" (car prev) " ")]) (append (map (λ(x) (~a x x x)) prev) (map (λ(x) (~a x spaces x)) prev) (map (λ(x) (~a x x x)) prev))))) (for-each displayln (c...
Give a code snippet in #Racket Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # #...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Haxe
Haxe
var val = 0;   do { val++; Sys.println(val); } while( val % 6 != 0);
Give a code snippet in #Haxe Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Do...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#Python
Python
from __future__ import print_function import numpy as np   def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("t...
Give a code snippet in #Python Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#Nim
Nim
import lenientops, sequtils, stats, strformat   proc polyRegression(x, y: openArray[int]) =   let xm = mean(x) let ym = mean(y) let x2m = mean(x.mapIt(it * it)) let x3m = mean(x.mapIt(it * it * it)) let x4m = mean(x.mapIt(it * it * it * it)) let xym = mean(zip(x, y).mapIt(it[0] * it[1])) let x2ym = mean(z...
Give a code snippet in #Nim Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients a...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Oforth
Oforth
: compose(f, g) #[ g perform f perform ] ;   [ #cos, #sin, #[ 3 pow ] ] [ #acos, #asin, #[ 3 inv powf ] ] zipWith(#compose) map(#[ 0.5 swap perform ]) conform(#[ 0.5 == ]) println  
Give a code snippet in #Oforth A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 #SingleInstance, Force   ; Uncomment if Gdip.ahk is not in your standard library #Include, Gdip.ahk   ; Settings X := 200, Y := 200, Width := 200, Height := 200 ; Location and size of sphere rotation := -30 ; degrees ARGB := 0xFFFF0000 ; Color=Solid Red   If !pToken := Gdip_Startup() ; Start gd...
Give a code snippet in #AutoHotkey Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Fortran
Fortran
program read_file implicit none integer :: n character(:), allocatable :: s   open(unit=10, file="read_file.f90", action="read", & form="unformatted", access="stream") inquire(unit=10, size=n) allocate(character(n) :: s) read(10) s close(10)   print "(A)", s end program
Give a code snippet in #Fortran Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished inc...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#zkl
zkl
const EPSILON=1.0e-15; fact,e,n := 1, 2.0, 2; do{ e0:=e; fact*=n; n+=1; e+=1.0/fact; }while((e - e0).abs() >= EPSILON); println("e = %.15f".fmt(e));
Give a code snippet in #zkl Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
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 .
#PureBasic
PureBasic
Procedure.i lpd(v.i) For i=v/2 To 1 Step -1 If v%i=0 : ProcedureReturn i : EndIf Next ProcedureReturn 1 EndProcedure   If OpenConsole("") For i=1 To 100 Print(RSet(Str(lpd(i)),3)) If i%10=0 : PrintN("") : EndIf Next Input() EndIf
Give a code snippet in #PureBasic Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#DWScript
DWScript
function IsLeapYear(y : Integer) : Boolean; begin Result:= (y mod 4 = 0) and ( ((y mod 100) <> 0) or ((y mod 400) = 0) ); end;   const good : array [0..13] of Integer = [1600,1660,1724,1788,1848,1912,1972,2032,2092,2156,2220,2280,2344,2348]; const bad : array [0..13] of Integer = ...
Give a code snippet in #DWScript Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Xorshift_star
Pseudo-random numbers/Xorshift star
Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary bits of value shifted left or ri...
#Julia
Julia
const mask32 = (0x1 << 32) - 1 const CONST = 0x2545F4914F6CDD1D   mutable struct XorShiftStar state::UInt64 end   XorShiftStar(_seed=0x0) = XorShiftStar(UInt(_seed))   seed(x::XorShiftStar, num) = begin x.state = UInt64(num) end   """return random int between 0 and 2**32""" function next_int(x::XorShiftStar) x...
Give a code snippet in #Julia Some definitions to help in the explanation Floor operation https://en.wikipedia.org/wiki/Floor_and_ceiling_functions Greatest integer less than or equal to a real number. Bitwise Logical shift operators (c-inspired) https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts Binary b...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#GAP
GAP
Balanced := function(L) local c, r; r := 0; for c in L do if c = ']' then r := r - 1; if r < 0 then return false; fi; elif c = '[' then r := r + 1; fi; od; return r = 0; end;   Balanced(""); # true   Balanced("["...
Give a code snippet in #GAP Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nes...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Lingo
Lingo
haystack = ["apples", "oranges", "bananas", "oranges"] needle = "oranges"   pos = haystack.getPos(needle) if pos then put "needle found at index "&pos else put "needle not found in haystack" end if   -- "needle found at index 2"
Give a code snippet in #Lingo Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle th...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#TXR
TXR
(defun hyaku-mai-tobira () (let ((doors (vector 100))) (each ((i (range 0 99))) (each ((j (range i 99 (+ i 1)))) (flip [doors j]))) doors))   (each ((counter (range 1)) (door (hyaku-mai-tobira))) (put-line `door @counter is @(if door "open" "closed")`))
Give a code snippet in #TXR There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...)...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#AntLang
AntLang
/ Create an immutable sequence (array) arr: <1;2;3>   / Get the head an tail part h: head[arr] t: tail[arr]   / Get everything except the last element and the last element nl: first[arr] l: last[arr]   / Get the nth element (index origin = 0) nth:arr[n]
Give a code snippet in #AntLang This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and ret...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#J
J
  names =. 'one';'two';'three';'four';'five';'six';'seven';'eight';'nine';'ten';'eleven';'twelve';'thirteen';'fourteen';'fifteen';'sixteen';'seventeen';'eighteen';'nineteen'   tens =. '';'twenty';'thirty';'forty';'fifty';'sixty';'seventy';'eighty';'ninety'   NB. selects the xth element from list y lookup =: >@{:@{.   N...
Give a code snippet in #J Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of chara...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Groovy
Groovy
/** * Integrates input function K over time * S + (t1 - t0) * (K(t1) + K(t0)) / 2 */ class Integrator { interface Function { double apply(double timeSinceStartInSeconds) }   private final long start private volatile boolean running   private Function func private double t0 private...
Give a code snippet in #Groovy In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such ...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#R
R
stopifnot(a==42)
Give a code snippet in #R Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Ioke
Ioke
System programArguments each(println)
Give a code snippet in #Ioke Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Euphoria
Euphoria
include std\text.e include std\os.e include std\sequence.e include std\console.e   sequence bcData = {0,0} --bull,cow score for the player sequence goalNum = { {0,0,0,0}, {0,0,0,0}, 0} --computer's secret number digits (element 1), marked as bull/cow --indexes in element 2, integer value of it in element 3 sequence cur...
Give a code snippet in #Euphoria Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if t...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Factor
Factor
! built in USING: picomath prettyprint ; 0.1 gamma .  ! 9.513507698668723 2.0 gamma .  ! 1.0 10. gamma .  ! 362880.0
Give a code snippet in #Factor Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/li...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#REXX
REXX
/*REXX program performs a chi─squared test to verify a given distribution is uniform. */ numeric digits length( pi() ) - length(.) /*enough decimal digs for calculations.*/ @.=; @.1= 199809 200665 199607 200270 199649 @.2= 52257...
Give a code snippet in #REXX Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   call :luhn 49927398716 call :luhn 49927398717 call :luhn 1234567812345678 call :luhn 1234567812345670 exit /b 0   :luhn set "input=%1" set "cnt=0" set "s1=0" set "s2=0" :digit_loop set /a "cnt-=1" set /a "isOdd=(-%cnt%)%%2"   if !isodd! equ 1 ( set /a "s1+=!input:~%cnt%,1!" ...
Give a code snippet in #Batch_File The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the ord...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Arendelle
Arendelle
< a , b > ( r , @a ) [ @r != 0 , ( r , @a % @b ) { @r != 0 , ( a , @b ) ( b , @r ) } ] ( return , @b )
Give a code snippet in #Arendelle Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   grea...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#VBA
VBA
Private Function dot_product(x As Variant, y As Variant) As Double dot_product = WorksheetFunction.SumProduct(x, y) End Function   Public Sub main() Debug.Print dot_product([{1,3,-5}], [{4,-2,-1}]) End Sub
Give a code snippet in #VBA Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#Visual_Basic_.NET
Visual Basic .NET
' Recursively iterates (increments) iteration array, returns -1 when out of "digits". Function plusOne(iAry() As Integer, spot As Integer) As Integer Dim spotLim As Integer = If(spot = 0, 1, 2) ' The first "digit" has a lower limit. If iAry(spot) = spotLim Then ' Check if spot has reached limit If spot ...
Give a code snippet in #Visual_Basic_.NET Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a...
christopher/rosetta-code
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#ALGOL_68
ALGOL 68
BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the # # subsequent members are the lowest number coprime to the previous one # # and not coprime to the one before that, that haven't appeared in the # # sequence yet # ...
Give a code snippet in #ALGOL_68 The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Action.21
Action!
DEFINE PTR="CARD"   CHAR FUNC ToLower(CHAR c) IF c>='A AND c<='Z THEN c==+'a-'A FI RETURN (c)   BYTE FUNC CheckExt(CHAR ARRAY file,ext) BYTE i,j CHAR c1,c2   i=file(0) j=ext(0) IF i<j THEN RETURN (0) FI   WHILE j>0 DO c1=ToLower(file(i)) c2=ToLower(ext(j)) IF c1#c2 THEN RETURN (0) FI ...
Give a code snippet in #Action.21 File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Io
Io
keepWins := 0 switchWins := 0 doors := 3 times := 100000 pickDoor := method(excludeA, excludeB, door := excludeA while(door == excludeA or door == excludeB, door = (Random value() * doors) floor ) door ) times repeat( playerChoice := pickDoor() carDoor := pickDoor() shownDoor := pickDoor(carDoor, play...
Give a code snippet in #Io 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 ti...
christopher/rosetta-code
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#Objective-C
Objective-C
@interface Tree<T> : NSObject { T value; Tree<T> *left; Tree<T> *right; }   - (void)replaceAll:(T)v; @end   @implementation Tree - (void)replaceAll:(id)v { value = v; [left replaceAll:v]; [right replaceAll:v]; } @end
Give a code snippet in #Objective-C Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with so...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#PicoLisp
PicoLisp
(load "@lib/math.l")   (let (Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0) Len (length Lst)) (prinl "Arithmetic mean: " (format (/ (apply + Lst) Len) *Scl ) ) (prinl "Geometric mean: " (format (pow (*/ (apply * Lst) (** 1.0 (dec Len))) (/ 1.0 Len)) *Scl ) ) (pr...
Give a code snippet in #PicoLisp Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\...
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...
#True_BASIC
True BASIC
LET i = 0   DO PRINT i LET i = i + 1 LOOP   END
Give a code snippet in #True_BASIC 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 implementatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Rust
Rust
// [dependencies] // image = "0.23"   use image::{GrayImage, Luma};   type Vector = [f64; 3];   fn normalize(v: &mut Vector) { let inv_len = 1.0/dot_product(v, v).sqrt(); v[0] *= inv_len; v[1] *= inv_len; v[2] *= inv_len; }   fn dot_product(v1: &Vector, v2: &Vector) -> f64 { v1.iter().zip(v2.iter())...
Give a code snippet in #Rust Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Dea...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#Ruby
Ruby
require 'prime'   def powerMod(b, p, m) p.to_s(2).each_char.inject(1) do |result, bit| result = (result * result) % m bit=='1' ? (result * b) % m : result end end   def multOrder_(a, p, k) pk = p ** k t = (p - 1) * p ** (k - 1) r = 1 for q, e in t.prime_division x = powerMod(a, t / q**e, pk) ...
Give a code snippet in #Ruby The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is effici...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#REXX
REXX
/*REXX pgm solves the 4-rings puzzle, where letters represent unique (or not) digits). */ arg LO HI unique show . /*the ARG statement capitalizes args.*/ if LO=='' | LO=="," then LO=1 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI=7 ...
Give a code snippet in #REXX 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 algor...
#Phix
Phix
with javascript_semantics function comb_sort(sequence s) integer gap = length(s)-1 while 1 do gap = max(floor(gap/1.3),1) integer swapped = 0 for i=1 to length(s)-gap do object si = s[i] if si>s[i+gap] then s[i] = s[i+gap] s[i+gap] = s...
Give a code snippet in #Phix Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#J
J
vectors =. ((% +/&.:*:"1) _1 1 0,:_1 _1 3) +/@:*"1/~ 2 3 4*=i.3 ' .*o' {~ +/ 1 2 3* (|:"2 -."_ 1~ vectors) ([:*./ 1 = 0 1 I. %.~)"_ 1"_1 _ ]4j21 ,~"0/&:i: 4j41               oooo ooooooooooooo oooooooooooooo.... ...
Give a code snippet in #J Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acc...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#SequenceL
SequenceL
life(Cells(2))[I, J] := let numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] + Cells[I,J-1] +/*current cell*/Cells[I,J+1] + Cells[I+1,J-1] + Cells[I+1,J] + Cells[I+1,J+1]; in 0 when I=1 or J=1 or I=size(Cells) or J=size(Cells[I]) //On Border else 0 when numNeighbors < 2 or numNeighbors...
Give a code snippet in #SequenceL The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dea...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#Phix
Phix
procedure main() ... end procedure main()
Give a code snippet in #Phix Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Picat
Picat
  /* * Multi-line comment */   % Single-line Prolog-style comment  
Give a code snippet in #Picat Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#PowerShell
PowerShell
  function order($as,$bs) { if($as -and $bs) { $a, $as = $as $b, $bs = $bs if($a -eq $b) {order $as $bs} else{$a -lt $b} } elseif ($bs) {$true} else {$false} } "$(order @(1,2,1,3,2) @(1,2,0,4,4,0,0,0))"  
Give a code snippet in #PowerShell sorting 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#C.23
C#
using System; using System.IO; using System.Text;   namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT";   private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt);...
Give a code snippet in #C.23 Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT ...
christopher/rosetta-code
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 ...
#8086_Assembly
8086 Assembly
fib: ; WRITTEN IN C WITH X86-64 CLANG 3.3 AND DOWNGRADED TO 16-BIT X86 ; INPUT: DI = THE NUMBER YOU WISH TO CALC THE FIBONACCI NUMBER FOR. ; OUTPUTS TO AX   push BP push BX push AX mov BX, DI ;COPY INPUT TO BX xor AX, AX ;MOV AX,0 test BX, BX ;...
Give a code snippet in #8086_Assembly 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 solut...
christopher/rosetta-code
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming langua...
#Phix
Phix
--global (if you want to be able to call this from test.exw) function hailstone(atom n) sequence s = {n} while n!=1 do if remainder(n,2)=0 then n /= 2 else n = 3*n+1 end if s &= n end while return s end function   global function hailstone_count(atom n...
Give a code snippet in #Phix The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared objec...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Java
Java
import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random random = new Random(); long from = 1; long to = 100; int randomNumber = random.nextInt(to - from + 1) + from; ...
Give a code snippet in #Java Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hig...
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...
#Standard_ML
Standard ML
signature RADCATFIELD = sig type real val zero : real val one : real val + : real * real -> real val - : real * real -> real val * : real * real -> real val / : real * real -> real val sign : real -> real val sqrt : real -> real end   functor QR(F: RADCATFIELD) = struct structure A = struct local open Array in fun ...
Give a code snippet in #Standard_ML 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/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Python
Python
'''Church numerals'''   from itertools import repeat from functools import reduce     # ----- CHURCH ENCODINGS OF NUMERALS AND OPERATIONS ------   def churchZero(): '''The identity function. No applications of any supplied f to its argument. ''' return lambda f: identity     def churchSucc(cn)...
Give a code snippet in #Python Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#OCaml
OCaml
let heapsort a =   let swap i j = let t = a.(i) in a.(i) <- a.(j); a.(j) <- t in   let sift k l = let rec check x y = if 2*x+1 < l then let ch = if y < l-1 && a.(y) < a.(y+1) then y+1 else y in if a.(x) < a.(ch) then (swap x ch; check ch (2*ch+1)) in check k (2*k+1) in   ...
Give a code snippet in #OCaml 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Erlang
Erlang
  -module( undefined_values ).   -export( [task/0] ).   -record( a_record, {member_1, member_2} ).   task() -> Record = #a_record{member_1=a_value}, io:fwrite( "Record member_1 ~p, member_2 ~p~n", [Record#a_record.member_1, Record#a_record.member_2] ), io:fwrite( "Member_2 is undefined ~p~n", [Record#a_r...
Give a code snippet in #Erlang
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Scheme
Scheme
  (import (scheme base) (scheme write))   (define (repeat proc n) (do ((i 0 (+ 1 i)) (res '() (cons (proc) res))) ((= i n) res)))   ;; example returning an unspecified value (display (repeat (lambda () (display "hi\n")) 4)) (newline)   ;; example returning a number (display (repeat (lambda () (+ 1 ...
Give a code snippet in #Scheme Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code