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/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#ERRE
ERRE
  PROGRAM MAGIC_SQUARE   !$INTEGER   PROCEDURE Magicsq(size,filename$)   LOCAL DIM sq[25,25] ! array to hold square   IF (size AND 1)=0 OR size<3 THEN PRINT PRINT(CHR$(7)) ! beep PRINT("error: size is not odd or size is smaller then 3") PAUSE(3) EXIT PROCEDURE END IF   ! filename$ <> "" then save ma...
Give a code snippet in #ERRE A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers ...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!. map @++ [ 1 4 8 ]   #implemented roughly like this: #map f lst: # ] # for i in lst: # f i # [
Give a code snippet in #D.C3.A9j.C3.A0_Vu Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#FreeBASIC
FreeBASIC
Function revn(n As ULongInt, nd As ULongInt) As ULongInt Dim As ULongInt r For i As UInteger = 1 To nd r = r * 10 + n Mod 10 n = n \ 10 Next i Return r End Function   Dim As UInteger nd = 2, count, lim = 90, n = 20   Do n += 1 Dim As ULongInt r = revn(n,nd) If r < n Then ...
Give a code snippet in #FreeBASIC Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must b...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#Liberty_BASIC
Liberty BASIC
data "It is certain","It is decidedly so","Without a doubt","Yes - definitely",_ "You may rely on it","As I see it, yes","Most likely","Outlook good","Yes",_ "Signs point to yes","Reply hazy, try again","Ask again later","Better not tell you now",_ "Cannot predict now","Concentrate and ask again","Don't count on it","M...
Give a code snippet in #Liberty_BASIC Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bi...
christopher/rosetta-code
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#Lua
Lua
  function penny_game() local player, computer = "", "" function player_choose() io.write( "Enter your sequence of three H and/or T: " ) local t = io.read():upper() if #t > 3 then t = t:sub( 1, 3 ) elseif #t < 3 then return "" end   for i = 1, 3 do c =...
Give a code snippet in #Lua Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#PostScript
PostScript
  % over keys and values <</a 1 /b 2 /c 3>> {= =} forall % just keys <</a 1 /b 2 /c 3>> {= } forall % just values <</a 1 /b 2 /c 3>> {pop =} forall  
Give a code snippet in #PostScript Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Go
Go
package main import "fmt"   func func1(f func(string) string) string { return f("a string") } func func2(s string) string { return "func2 called with " + s } func main() { fmt.Println(func1(func2)) }
Give a code snippet in #Go Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Common_Lisp
Common Lisp
(with-output-to-string (stream) (extensions:run-program "ls" nil :output stream))
Give a code snippet in #Common_Lisp Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#C.2B.2B
C++
#include <iostream>   std::string middleThreeDigits(int n) { auto number = std::to_string(std::abs(n)); auto length = number.size();   if (length < 3) { return "less than three digits"; } else if (length % 2 == 0) { return "even number of digits"; } else { return number.subst...
Give a code snippet in #C.2B.2B Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#PARI.2FGP
PARI/GP
use English; # enables use of long variable names $. $INPUT_LINE_NUMBER # sequence number $, $OUTPUT_FIELD_SEPARATOR # output field separator $; $SUBSCRIPT_SEPARATOR # subscript separator for multidimensional array emulation $_ $ARG # topic/current...
Give a code snippet in #PARI.2FGP Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#D
D
import std.process; import std.stdio;   void main() { auto cmd = executeShell(`EventCreate /t INFORMATION /id 123 /l APPLICATION /so Dlang /d "Rosetta Code Example"`);   if (cmd.status == 0) { writeln("Output: ", cmd.output); } else { writeln("Failed to execute command, status=", cmd.status)...
Give a code snippet in #D Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#C.23
C#
using System;   namespace FeigenbaumConstant { class Program { static void Main(string[] args) { var maxIt = 13; var maxItJ = 10; var a1 = 1.0; var a2 = 0.0; var d1 = 3.2; Console.WriteLine(" i d"); for (int i = 2; i <...
Give a code snippet in #C.23 Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Visual_Basic_.NET
Visual Basic .NET
Sub bar2() Dim x = 0 GoTo label x = 5 label: Console.WriteLine(x) End Sub
Give a code snippet in #Visual_Basic_.NET Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto ...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. 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) The haversine formula is an equation important in navigation, g...
#Go
Go
package main   import ( "fmt" "math" )   func haversine(θ float64) float64 { return .5 * (1 - math.Cos(θ)) }   type pos struct { φ float64 // latitude, radians ψ float64 // longitude, radians }   func degPos(lat, lon float64) pos { return pos{lat * math.Pi / 180, lon * math.Pi / 180} }   const r...
Give a code snippet in #Go This page uses content from Wikipedia. The original article was at Haversine formula. 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) The haversine formula is an equatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#AppleScript
AppleScript
use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later — for these 'use' commands! -- This script uses a customisable AppleScript sort available at <https://macscripter.net/viewtopic.php?pid=194430#p194430>. -- It's assumed that scripters will know how and where to install it as a library. use sorter : scrip...
Give a code snippet in #AppleScript The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of ...
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 ...
#Sather
Sather
class MAIN is main is x ::= #VEC(|1.0, 3.0, -5.0|); y ::= #VEC(|4.0, -2.0, -1.0|); #OUT + x.dot(y) + "\n"; end; end;
Give a code snippet in #Sather 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, -...
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...
#FreeBASIC
FreeBASIC
' FB 1.05. 0 Win64   Dim i As Integer = 0 Do i += 1 Print i; " "; Loop While i Mod 6 <> 0 Print Sleep
Give a code snippet in #FreeBASIC 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   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#GAP
GAP
Walk := function(name, op) local dir, file, e; dir := Directory(name); for e in SortedList(DirectoryContents(name)) do file := Filename(dir, e); if IsDirectoryPath(file) then if not (e in [".", ".."]) then Walk(file, op); fi; else op(file); fi; od; end;   # This will print filenames Walk(".", D...
Give a code snippet in #GAP Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#X86_Assembly
X86 Assembly
  %include "io.inc"   section .text global CMAIN CMAIN: mov ebx, 7 ;size call mloop ret   mloop: mov edx, 0 ;edx stands for the nth line looping: push ebx push edx call line pop edx pop ebx inc edx cmp edx, ebx jl looping xor eax, eax ret   line: mov ecx, 0 ;ecx stands for the nth character in each line ...
Give a code snippet in #X86_Assembly Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is...
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 .
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;   procedure Main is subtype param_type is Integer range 1 .. 100; function lpd (n : in param_type) return param_type is result : param_type := 1; begin for divisor in reverse 1 .. n / 2 loop if n ...
Give a code snippet in #Ada Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Dyalect
Dyalect
func Array.Filter(pred) { var arr = [] for x in this when pred(x) { arr.Add(x) } arr }   var arr = [1..20].Filter(x => x % 2 == 0) print(arr)
Give a code snippet in #Dyalect Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#IS-BASIC
IS-BASIC
100 PROGRAM "SuChiper.bas" 110 STRING ST$(1 TO 2)*52,K$*1 120 LET ST$(1)="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 130 LET ST$(2)="VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN" 140 CLEAR SCREEN:PRINT "1 - encode, 2 - decode" 150 DO 160 LET K$=INKEY$ 170 LOOP UNTIL K$="1" OR K$="2" 180 IF K$="1" T...
Give a code snippet in #IS-BASIC Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Applesoft_BASIC
Applesoft BASIC
0 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256 100 : 110 REM CREATE AN INTEGER OBJECT 120 : 130 I$ = CHR$ (42) 140 POKE 236, PEEK (131) 150 POKE 237, PEEK (132) 160 PRINT "HERE IS AN INTEGER  : " ASC (I$) 200 : 210 REM PRINT THE MACHINE ADDRESS OF THE OBJECT 220 : 230 PRINT "ITS ADDRESS IS ...
Give a code snippet in #Applesoft_BASIC Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String O...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#11l
11l
F order_words(words) DefaultDict[Char, Set[String]] byfirst L(word) words byfirst[word[0]].add(word) R byfirst   F linkfirst(&byfirst; sofar) assert(!sofar.empty) V chmatch = sofar.last.last V options = byfirst[chmatch] - Set(sofar)   I options.empty R sofar E V alternatives = ...
Give a code snippet in #11l A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the cate...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Sidef
Sidef
say expmod( 2988348162058574136915891421498819466320163312926952423791023078876139, 2351399303373464486466122544523690094744975233415544072992656881240319, 10**40)
Give a code snippet in #Sidef Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 23513993033734...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Elena
Elena
import system'collections; import extensions;   const int maxNumber = 100000;   Hailstone(int n,Map<int,int> lengths) { if (n == 1) { ^ 1 };   while (true) { if (lengths.containsKey(n)) { ^ lengths[n] } else { if (n.isEven()) ...
Give a code snippet in #Elena The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jacobi_symbol
Jacobi symbol
The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) (a | p) ≡   1 ...
#Sidef
Sidef
func jacobi(n, k) {   assert(k > 0, "#{k} must be positive") assert(k.is_odd, "#{k} must be odd")   var t = 1 while (n %= k) { var v = n.valuation(2) t *= (-1)**v if (k%8 ~~ [3,5]) n >>= v (n,k) = (k,n) t = -t if ([n%4, k%4] == [3,3]) }   k==1 ? t : 0 }...
Give a code snippet in #Sidef The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have m...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
LongestAscendingSequence/@{{3,2,6,4,5,1},{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}}
Give a code snippet in #Mathematica.2FWolfram_Language Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,...
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 ...
#6502_Assembly
6502 Assembly
LDA #0 STA $F0  ; LOWER NUMBER LDA #1 STA $F1  ; HIGHER NUMBER LDX #0 LOOP: LDA $F1 STA $0F1B,X STA $F2  ; OLD HIGHER NUMBER ADC $F0 STA $F1  ; NEW HIGHER NUMBER LDA $F2 STA $F0  ; NEW LOWER NUMBER INX ...
Give a code snippet in #6502_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/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...
#Prolog
Prolog
% A quaternion is represented as a complex term qx/4 add(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(R,I,J,K)) :- !, R is R0+R1, I is I0+I1, J is J0+J1, K is K0+K1. add(qx(R0,I,J,K), F, qx(R,I,J,K)) :- number(F), !, R is R0 + F. add(F, qx(R0,I,J,K), Qx) :- add(qx(R0,I,J,K), F, Qx). mul(qx(R0,I0,J0,K0), qx(R1,I1,J1,K1), qx(...
Give a code snippet in #Prolog 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Sidef
Sidef
func forprimes(a, b, callback) { for (var p = a.dec.next_prime; p <= b; p.next_prime!) { callback(p) } }   func is_emirp(p) { var str = Str(p) var rev = str.reverse (str != rev) && is_prime(Num(rev)) }   func emirp_list(count) { var i = 13 var inc = (100 + 10*count) var n = [] ...
Give a code snippet in #Sidef An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   ...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#BBC_BASIC
BBC BASIC
INPUT LINE "Enter a string: " string$ INPUT "Enter a number: " number   PRINT "String = """ string$ """" PRINT "Number = " ; number
Give a code snippet in #BBC_BASIC User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Common_Lisp
Common Lisp
  (defun recurse () (recurse)) (trace recurse) (recurse)  
Give a code snippet in #Common_Lisp Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Oforth
Oforth
String method: isPalindrome self reverse self == ;
Give a code snippet in #Oforth A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly a...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Arturo
Arturo
tokenize: function [s sep esc][ escaping: 0   loop 0..(size s)-1 [i][ chr: get split s i   if? escaping=1 [ prints chr escaping: 0 ] else [ case [chr] when? [=sep] [print ""] when? [=esc] [escaping: 1] else [prints chr] ] ] print "" ]   str: "one^|uno||three^^^^|four^^^|^cuatro|" tok...
Give a code snippet in #Arturo Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for spl...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#Erlang
Erlang
  -module(solution). -import(lists,[delete/2,max/1]). -compile(export_all). selection_sort([],Sort)-> Sort; selection_sort(Ar,Sort)-> M=max(Ar), Ad=delete(M,Ar), selection_sort(Ad,[M|Sort]). print_array([])->ok; print_array([H|T])-> io:format("~p~n",[H]), print_array(T).   main()-> Ans=selection_sort([1,5,7,8,4,...
Give a code snippet in #Erlang 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/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 ...
#newLISP
newLISP
(define (dot-product x y) (apply + (map * x y)))   (println (dot-product '(1 3 -5) '(4 -2 -1)))
Give a code snippet in #newLISP 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, ...
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...
#PARI.2FGP
PARI/GP
  efrac(f)=my(v=List());while(f,my(x=numerator(f),y=denominator(f));listput(v,ceil(y/x));f=(-y)%x/y/v[#v]);Vec(v); show(f)=my(n=f\1,v=efrac(f-n)); print1(f" = ["n"; "v[1]); for(i=2,#v,print1(", "v[i])); print("]"); best(n)=my(denom,denomAt,term,termAt,v); for(a=1,n-1,for(b=a+1,n, v=efrac(a/b); if(#v>term, termAt=a/b; t...
Give a code snippet in #PARI.2FGP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
opts = Tuples[{{"May"}, {15, 16, 19}}]~Join~Tuples[{{"June"}, {17, 18}}]~Join~Tuples[{{"July"}, {14, 16}}]~Join~Tuples[{{"August"}, {14, 15, 17}}]; monthsdelete = Select[GatherBy[opts, Last], Length /* EqualTo[1]][[All, 1, 1]]; opts = DeleteCases[opts, {Alternatives @@ monthsdelete, _}] removedates = Catenate@Select[Ga...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, Au...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Microsoft_Small_Basic
Microsoft Small Basic
' Babbage problem ' The quote (') means a comment ' The equals sign (=) means assign n = 500 ' 500 is stored in variable n*n ' 500 because 500*500=250000 less than 269696   ' The nitty-gritty is in the 3 lines between "While" and "EndWhile". ' So, we start with 500, n is being incremented by 1 at each round ' while its...
Give a code snippet in #Microsoft_Small_Basic Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill,...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Processing
Processing
  size(1000,1000);  
Give a code snippet in #Processing Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#11l
11l
print(os:getenv(‘HOME’))
Give a code snippet in #11l Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#jq
jq
jq -n -M -r -f plot.jq | R CMD BATCH plot.R
Give a code snippet in #jq Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Elena
Elena
import extensions;   public program() { var s := "little"; console.printLineFormatted("Mary had a {0} lamb.",s).readChar() }
Give a code snippet in #Elena Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Natural_sorting
Natural 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 Shell Sort ...
#Perl
Perl
  use feature 'fc'; use Unicode::Normalize;   sub natural_sort { my @items = map { my $str = fc(NFKD($_)); $str =~ s/\s+/ /; $str =~ s/|^(?:the|a|an) \b|\p{Nonspacing_Mark}| $//g; my @fields = $str =~ /(?!\z) ([^0-9]*+) ([0-9]*+)/gx; [$_, \@fields] } @_; return map { ...
Give a code snippet in #Perl 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/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Common_Lisp
Common Lisp
(use-package :ftp)   (with-ftp-connection (conn :hostname "ftp.hq.nasa.gov" :passive-ftp-p t) (send-cwd-command conn "/pub/issoutreach/Living in Space Stories (MP3 Files)") (send-list-command conn t) (let ((filename "Gravity in the Brain.mp3")) (retrieve-file conn filename filename...
Give a code snippet in #Common_Lisp Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#GAP
GAP
CaesarCipher := function(s, n) local r, c, i, lower, upper; lower := "abcdefghijklmnopqrstuvwxyz"; upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; r := ""; for c in s do i := Position(lower, c); if i <> fail then Add(r, lower[RemInt(i + n - 1, 26) + 1]); else i := Position(upper, c); if i <> fail then Ad...
Give a code snippet in #GAP Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Delphi
Delphi
  function IsNumericString(const inStr: string): Boolean; var i: extended; begin Result := TryStrToFloat(inStr,i); end;  
Give a code snippet in #Delphi Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
funcs = {Sin, Cos, #^3 &}; funcsi = {ArcSin, ArcCos, #^(1/3) &}; compositefuncs = Composition @@@ Transpose[{funcs, funcsi}]; Table[i[0.666], {i, compositefuncs}]
Give a code snippet in #Mathematica_.2F_Wolfram_Language 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 functi...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Julia
Julia
using Primes   function primediffseqs(maxnum = 1_000_000) mprimes = primes(maxnum) diffs = map(p -> mprimes[p[1] + 1] - p[2], enumerate(@view mprimes[begin:end-1])) incstart, decstart, bestinclength, bestdeclength = 1, 1, 0, 0 for i in 1:length(diffs)-1 foundinc, founddec = false, false ...
Give a code snippet in #Julia Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for prim...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#beeswax
beeswax
instruction: _f gstack: UInt64[0]• (at the beginning of a program lstack is initialized to [0 0 0]
Give a code snippet in #beeswax Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Locomotive_Basic
Locomotive Basic
|say,"This is an example of speech synthesis."
Give a code snippet in #Locomotive_Basic Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Test_integerness
Test integerness
Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Given a rational, real, or co...
#PicoLisp
PicoLisp
  (de int? (N) (= N (* 1.0 (/ N 1.0)))) #returns T or NIL   (de integer? (N) (and (= N (* 1.0 (/ N 1.0))) N)) #returns value of N or NIL   (scl 4) #-> 4 # *Scl the global which holds 1.0 #-> 10000 (int? 1.0) #-> T (int? 1) #-> NIL # 1 with a scale of 4 is same as 0.0001 which is not an Integer (int? -1.0) #-> T (i...
Give a code snippet in #PicoLisp Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[e...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Logo
Logo
show logoversion  ; 5.6 if logoversion < 6.0 [print [too old!]]   if and [name? "a] [number? :a] [ print ifelse procedure? "abs [abs :a] [ifelse :a < 0 [minus :a] [:a]] ]
Give a code snippet in #Logo Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Ursa
Ursa
# # csv data manipulation #   # declare a string stream to hold lines decl string<> lines   # open the file specified on the command line, halting # execution if they didn't enter one. it will be created if # it doesn't exist yet decl file f if (< (size args) 2) out "error: please specify a csv file" endl conso...
Give a code snippet in #Ursa CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, chang...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Common_Lisp
Common Lisp
  (defun mfac (n m) (reduce #'* (loop for i from n downto 1 by m collect i)))   (loop for i from 1 to 10 do (format t "~2@a: ~{~a~^ ~}~%" i (loop for j from 1 to 10 collect (mfac j i))))  
Give a code snippet in #Common_Lisp The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#E
E
pragma.enable("accumulator")   def leftRect(f, x, h) { return f(x) }   def midRect(f, x, h) { return f(x + h/2) }   def rightRect(f, x, h) { return f(x + h) }   def trapezium(f, x, h) { return (f(x) + f(x+h)) / 2 }   def simpson(f, x, h) { return (f(x) + 4 * f(x + h / 2) + f(x+h)) / 6 }   def integrate(f, a, ...
Give a code snippet in #E Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make i...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#C.23
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text;   namespace HilbertCurve { class Program { static void Swap<T>(ref T a, ref T b) { var c = a; a = b; b = c; }   struct Point { public int x, y;   ...
Give a code snippet in #C.23 Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Smalltalk
Smalltalk
OperatingSystem getHostName
Give a code snippet in #Smalltalk Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Opa
Opa
server = one_page_server("Hello", -> <>Goodbye, world</>)
Give a code snippet in #Opa The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note t...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#APL
APL
fromRoman←{ rmn←(⎕A,⎕A,'*')[(⎕A,⎕UCS 96+⍳26)⍳⍵] ⍝ make input uppercase dgt←↑'IVXLCDM' (1 5 10 50 100 500 1000) ⍝ values of roman digits ~rmn∧.∊⊂dgt[1;]:⎕SIGNAL 11 ⍝ domain error if non-roman input map←dgt[2;dgt[1;]⍳rmn] ⍝ map digits to values +/map×1-2×(2</map),0 ...
Give a code snippet in #APL Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, star...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Euphoria
Euphoria
constant X = 1, Y = 2, Z = 3   function dot_product(sequence a, sequence b) return a[X]*b[X] + a[Y]*b[Y] + a[Z]*b[Z] end function   function cross_product(sequence a, sequence b) return { a[Y]*b[Z] - a[Z]*b[Y], a[Z]*b[X] - a[X]*b[Z], a[X]*b[Y] - a[Y]*b[X] } end function   function scal...
Give a code snippet in #Euphoria A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Component_Pascal
Component Pascal
  MODULE StringConcatenation; IMPORT StdLog;   PROCEDURE Do*; VAR str1,str2: ARRAY 128 OF CHAR; BEGIN str1 := "Hello"; str2 := str1 + " world"; StdLog.String(":> " + str2);StdLog.Ln END Do;   END StringConcatenation.  
Give a code snippet in #Component_Pascal String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#UNIX_Shell
UNIX Shell
function urlencode { typeset decoded=$1 encoded= rest= c= typeset rest2= bug='rest2=${rest}'   if [[ -z ${BASH_VERSION} ]]; then # bug /usr/bin/sh HP-UX 11.00 typeset _decoded='xyz%26xyz' rest="${_decoded#?}" c="${_decoded%%${rest}}" if (( ${#c} != 1 )); then typeset qm='????????????????????????????????...
Give a code snippet in #UNIX_Shell Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character enc...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#Python
Python
from itertools import product   minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)), ((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)), ((13184...
Give a code snippet in #Python A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Raku
Raku
my $triangle = q| 55 94 48 95 30 96 77 71 26 67 97 13 76 38 45 07 36 79 16 37 68 48 07 09 18 70 26 06 18 72 79 46 59 79 29 90 20 76 87 11 32 07 07 49 18 ...
Give a code snippet in #Raku Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such w...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program strNumber.s */   /* Constantes */ .equ STDIN, 0 @ Linux input console .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 @ Linux...
Give a code snippet in #ARM_Assembly Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Met...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Ruby
Ruby
require 'cgi' puts CGI.unescape("http%3A%2F%2Ffoo%20bar%2F") # => "http://foo bar/"
Give a code snippet in #Ruby This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded f...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#Factor
Factor
USING: kernel lists lists.lazy math sequences sequences.extras ;   ! Compute the nth pentagonal number. : penta ( n -- m ) [ sq 3 * ] [ - 2/ ] bi ;   ! An infinite lazy list of indices to add and subtract in the ! sequence of partitions to find the next P. : seq ( -- list ) 1 lfrom [ penta 1 - ] <lazy-map> 1 lfrom ...
Give a code snippet in #Factor The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Sin[1] Cos[1] Tan[1] ArcSin[1] ArcCos[1] ArcTan[1] Sin[90 Degree] Cos[90 Degree] Tan[90 Degree]
Give a code snippet in #Mathematica.2FWolfram_Language Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should...
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: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Fennel
Fennel
(fn in-carpet? [x y] (if (or (= 0 x) (= 0 y)) true (and (= 1 (% x 3)) (= 1 (% y 3))) false (in-carpet? (// x 3) (// y 3))))   (fn make-carpet [size] (for [y 0 (- (^ 3 size) 1)] (for [x 0 (- (^ 3 size) 1)] (if (in-carpet? x y) (io.write "#") (io.write " "))) (io.write "\n"))...
Give a code snippet in #Fennel 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/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Robotic
Robotic
  input string "First value" set "local1" to "input" input string "Second value" set "local2" to "input"   . ">>> is an arithmetic shift; >> is a logical shift" [ "a AND b = ('local1' a 'local2')" [ "a OR b = ('local1' o 'local2')" [ "a XOR b = ('local1' x 'local2')" [ "NOT a = (~'local1')" [ "a << b = ('local1' << 'lo...
Give a code snippet in #Robotic Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#MiniScript
MiniScript
phrase = "rosetta code phrase reversal"   // general sequence reversal function reverse = function(seq) out = [] for i in range(seq.len-1, 0) out.push seq[i] end for if seq isa string then return out.join("") return out end function   // 1. Reverse the characters of the string. print reverse...
Give a code snippet in #MiniScript Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order o...
christopher/rosetta-code
http://rosettacode.org/wiki/Simulate_input/Mouse
Simulate input/Mouse
#Wren
Wren
/* simulate_input_mouse.wren */   var KeyPressMask = 1 << 0 var ButtonPressMask = 1 << 2 var Button1Mask = 1 << 8 var ExposureMask = 1 << 15 var Button1 = 1 var KeyPress = 2 var ButtonPress = 4 var Expose = 12 var ClientMessage = 33   var XK_a = 0x0061 var XK_q ...
Give a code snippet in #Wren
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Red
Red
str: "Hello,How,Are,You,Today" >> tokens: split str "," >> probe tokens ["Hello" "How" "Are" "You" "Today"]   >> periods: replace/all form tokens " " "."  ;The word FORM converts the list series to a string removing quotes. >> print periods  ;then REPLACE/ALL spaces with...
Give a code snippet in #Red Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rela...
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#Phix
Phix
-- -- demo\rosetta\Wireworld.exw -- ========================== -- -- Invoke with file to read, or let it read the one below (if compiled assumes source is in the same directory) -- -- Note that tabs in description files are not supported - where necessary spaces can be replaced with _ chars. -- (tab chars in text fi...
Give a code snippet in #Phix Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell t...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Pascal
Pascal
if ($s eq "") { # Test for empty string print "The string is empty"; } if ($s ne "") { # Test for non empty string print "The string is not empty"; }
Give a code snippet in #Pascal Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/P-Adic_numbers,_basic
P-Adic numbers, basic
Conversion and addition of p-adic Numbers. Task. Convert two rationals to p-adic numbers and add them up. Rational reconstruction is needed to interpret the result. p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions (a series of digits 0 ≤ d < p times p-power weights) are finite-tailed and tend ...
#Go
Go
package main   import "fmt"   // constants const EMX = 64 // exponent maximum (if indexing starts at -EMX) const DMX = 100000 // approximation loop maximum const AMX = 1048576 // argument maximum const PMAX = 32749 // prime maximum   // global variables var p1 = 0 var p = 7 // default prime var k = 11 // precis...
Give a code snippet in #Go Conversion and addition of p-adic Numbers. Task. Convert two rationals to p-adic numbers and add them up. Rational reconstruction is needed to interpret the result. p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions (a series of digits 0 ≤ d < p times p-power weights)...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#PARI.2FGP
PARI/GP
use strict; use 5.10.0;   use threads 'yield'; use threads::shared;   my @a :shared = (100) x 10; my $stop :shared = 0;   sub pick2 { my $i = int(rand(10)); my $j; $j = int(rand(10)) until $j != $i; ($i, $j) }   sub even { lock @a; my ($i, $j) = pick2; my $sum = $a[$i] + $a[$j]; $a[$i] = int($sum / 2); $a[$j] ...
Give a code snippet in #PARI.2FGP Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of al...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#zkl
zkl
foreach line in (File("foo.zkl")){print(line)}
Give a code snippet in #zkl Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
next-num: 0 while over: over * dup % swap 10 + swap floor / swap 10 swap drop swap   is-happy happies n: if has happies n: return happies! n local :seq set{ n } n while /= 1 dup: next-num if has seq dup: drop set-to happies n false return false if has happies dup: set-to happies n dup...
Give a code snippet in #D.C3.A9j.C3.A0_Vu From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#OCaml
OCaml
let () = let cls = Array.init 10 (fun i -> (function () -> i * i)) in Random.self_init (); for i = 1 to 6 do let x = Random.int 9 in Printf.printf " fun.(%d) = %d\n" x (cls.(x) ()); done
Give a code snippet in #OCaml Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#PowerShell
PowerShell
  function BinarySearch-Iterative ([int[]]$Array, [int]$Value) { [int]$low = 0 [int]$high = $Array.Count - 1   while ($low -le $high) { [int]$mid = ($low + $high) / 2   if ($Array[$mid] -gt $Value) { $high = $mid - 1 } elseif ($Array[$mid] -lt $Value) ...
Give a code snippet in #PowerShell A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a sec...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Wren
Wren
import "/fmt" for Fmt   var mf = Fn.new { |n, d| var prod = 1 while (n > 1) { prod = prod * n n = n - d } return prod }   for (d in 1..5) { System.write("degree %(d): ") for (n in 1..10) System.write(Fmt.d(8, mf.call(n, d))) System.print() }
Give a code snippet in #Wren The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Plain_TeX
Plain TeX
\input tikz.tex \usetikzlibrary{lindenmayersystems}   \pgfdeclarelindenmayersystem{Dragon curve}{ \symbol{S}{\pgflsystemdrawforward} \rule{F -> F+S} \rule{S -> F-S} } \tikzpicture \draw [lindenmayer system={Dragon curve, step=10pt, axiom=F, order=8}] lindenmayer system; \endtikzpicture \bye
Give a code snippet in #Plain_TeX Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#CLU
CLU
% Sort three variables. % The variables must all be of the same type, and the type % must implement the less-than comparator. sort_three = proc [T: type] (x,y,z: T) returns (T,T,T) where T has lt: proctype (T,T) returns (bool) if y<x then x,y := y,x end if z<y then y,z := z,y end if y<x then x,...
Give a code snippet in #CLU Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#EasyLang
EasyLang
func fib n . res . if n < 2 res = n . prev = 0 val = 1 for _ range n - 1 res = prev + val prev = val val = res . . call fib 36 r print r
Give a code snippet in #EasyLang 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Nim
Nim
import unicode   proc reverse(s: var string) = for i in 0 .. s.high div 2: swap(s[i], s[s.high - i])   proc reversed(s: string): string = result = newString(s.len) for i,c in s: result[s.high - i] = c   proc uniReversed(s: string): string = result = newStringOfCap(s.len) var tmp: seq[Rune] = @[] for...
Give a code snippet in #Nim Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty s...
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) ...
#TMG
TMG
program: readint(n) [n>0] readint(seed) loop: parse(render) [--n>0?]/done loop; render: random(i, 15) [i = (i+1)*2] loop2 = { 1 * }; loop2: random(b, 2) ( [b&1?] ={<[>} | ={<]>} ) [--i>0?]/done loop2 = { 2 1 }; done:  ;   /* Reads decimal integer */ readint: proc(n;i) string(spaces) [n=0] inta int1: [...
Give a code snippet in #TMG 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/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Erlang
Erlang
-module(beersong). -export([sing/0]). -define(TEMPLATE_0, "~s of beer on the wall, ~s of beer.~nGo to the store and buy some more, 99 bottles of beer on the wall.~n"). -define(TEMPLATE_N, "~s of beer on the wall, ~s of beer.~nTake one down and pass it around, ~s of beer on the wall.~n~n").   create_verse(0) -> {0,...
Give a code snippet in #Erlang Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 9...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#XLISP
XLISP
(defun quadratic-mean (xs) (sqrt (/ (apply + (mapcar (lambda (x) (expt x 2)) xs)) (length xs))))   ; define a RANGE function, for testing purposes   (defun range (x y) (if (< x y) (cons x (range (+ x 1) y))))   ; test QUADRATIC-MEAN   (print (quadratic-mea...
Give a code snippet in #XLISP Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 ...
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...
#Racket
Racket
  #lang racket   (define (pig-the-dice #:print? [print? #t] . players) (define prn (if print? (λ xs (apply printf xs) (flush-output)) void)) (define names (for/list ([p players] [n (in-naturals 1)]) n)) (define points (for/list ([p players]) (box 0))) (with-handlers ([(negate exn?) identity]) (for ([nm (in-...
Give a code snippet in #Racket 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Swift
Swift
func catalan(_ n: Int) -> Int { switch n { case 0: return 1 case _: return catalan(n - 1) * 2 * (2 * n - 1) / (n + 1) } }   for i in 1..<16 { print("catalan(\(i)) => \(catalan(i))") }  
Give a code snippet in #Swift Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Racket
Racket
  #lang racket (require math/number-theory)   (define (tot n) (match n [1 0] [n (define t (totient n)) (+ t (tot t))]))   (define (perfect? n) (= n (tot n)))   (define-values (ns i) (for/fold ([ns '()] [i 0]) ([n (in-naturals 1)] #:break (= i 20) #:when (perfec...
Give a code snippet in #Racket Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO;   with AWS.Client; with AWS.Response;   procedure HTTP_Request is begin Put_Line (AWS.Response.Message_Body (AWS.Client.Get (URL => "http://www.rosettacode.org"))); end HTTP_Request;  
Give a code snippet in #Ada Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#ATS
ATS
; Create an associative array obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00) enum := obj._NewEnum() While enum[key, value] t .= key "=" value "`n" MsgBox % t
Give a code snippet in #ATS Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compo...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П1 П2 <-> П0 ИП0 1 - x#0 29 ИП1 2 * П1 ИП0 2 / [x] П0 2 / {x} x#0 04 ИП2 ИП1 + П2 БП 04 ИП2 С/П
Give a code snippet in #.D0.9C.D0.9A-61.2F52 Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any re...
christopher/rosetta-code
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on thi...
#Rust
Rust
// [dependencies] // rug = "1.13.0"   use rug::Integer;   fn generate_primes(limit: usize) -> Vec<usize> { let mut sieve = vec![true; limit >> 1]; let mut p = 3; let mut sq = p * p; while sq < limit { if sieve[p >> 1] { let mut q = sq; while q < limit { si...
Give a code snippet in #Rust Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#GAP
GAP
MersenneSmallFactor := function(n) local k, m, d; if IsPrime(n) then d := 2*n; m := 1; for k in [1 .. 1000000] do m := m + d; if PowerModInt(2, n, m) = 1 then return m; fi; od; fi; return fail; end;     # If n is not pri...
Give a code snippet in #GAP A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#FreeBASIC
FreeBASIC
' version 10-10-2016 ' compile with: fbc -s console   Sub barnsley(height As UInteger)   Dim As Double x, y, xn, yn Dim As Double f = height / 10.6 Dim As UInteger offset_x = height \ 4 - height \ 40 Dim As UInteger n, r   ScreenRes height \ 2, height, 32   For n = 1 To height * 50   r = Int(Rnd * 100) ...
Give a code snippet in #FreeBASIC A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 ...
christopher/rosetta-code