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/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation ...
#Ring
Ring
  see "working..." + nl see "First 19 circular numbers are:" + nl n = 0 row = 0 Primes = []   while row < 19 n++ flag = 1 nStr = string(n) lenStr = len(nStr) for m = 1 to lenStr leftStr = left(nStr,m) rightStr = right(nStr,lenStr-m) strOk = rightStr + leftSt...
Give a code snippet in #Ring Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Action.21
Action!
DEFINE PTR="CARD"   PROC Append(CHAR ARRAY text,suffix) BYTE POINTER srcPtr,dstPtr BYTE len   len=suffix(0) IF text(0)+len>255 THEN len=255-text(0) FI IF len THEN srcPtr=suffix+1 dstPtr=text+text(0)+1 MoveBlock(dstPtr,srcPtr,len) text(0)==+suffix(0) FI RETURN   PROC Quibble(PTR ARRAY i...
Give a code snippet in #Action.21 Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". A...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT first,last) INT i   Put('[) FOR i=first TO last DO IF i>first THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC Process(INT ARRAY a INT size) INT i,j,beg,end INT sum,best   beg=0 end=-1 best=0 FOR i=0 TO size-1 DO sum=0 FOR j=i TO size-1 ...
Give a code snippet in #Action.21 Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements ...
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...
#MIPS_Assembly
MIPS Assembly
  .data even_str: .asciiz "Even" odd_str: .asciiz "Odd"   .text #set syscall to get integer from user li $v0,5 syscall   #perform bitwise AND and store in $a0 and $a0,$v0,1   #set syscall to print dytomh li $v0,4   #jump to odd if the result of the AND operation beq $a0,1,odd even: #load even_str message, ...
Give a code snippet in #MIPS_Assembly 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 od...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Whitespace
Whitespace
@each &x!console.log x !*&x?{%%x 15 "FizzBuzz" %%x 5 "Buzz" %%x 3 "Fizz" x} @to 100
Give a code snippet in #Whitespace Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   Fiz...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Bracmat
Bracmat
(λx.x)y
Give a code snippet in #Bracmat In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a ...
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...
#Excel
Excel
  =LOWER(A1)  
Give a code snippet in #Excel 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/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#EchoLisp
EchoLisp
  (require 'struct) (decimals 4) (string-delimiter "") (struct pt (x y))   (define-syntax-id _.x (struct-get _ #:pt.x)) (define-syntax-id _.y (struct-get _ #:pt.y))   (define (E-zero) (pt Infinity Infinity)) (define (E-zero? p) (= (abs p.x) Infinity)) (define (E-neg p) (pt p.x (- p.y)))   ;; magic formulae from "C" ...
Give a code snippet in #EchoLisp Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT PRINT/ERROR "hello world" text="goodbye world" PRINT/ERROR text  
Give a code snippet in #TUSCRIPT Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard o...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#REBOL
REBOL
forever [x: load input print x/1 + x/2]
Give a code snippet in #REBOL A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. 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 befo...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Main() Dim siList As Short[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]   Print siList.Count   End
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Kotlin
Kotlin
// version 1.1.2   import java.math.BigInteger   val big2 = BigInteger.valueOf(2) val big3 = BigInteger.valueOf(3) val big5 = BigInteger.valueOf(5) val big15 = big3 * big5   fun sum35(n: Int) = (3 until n).filter { it % 3 == 0 || it % 5 == 0}.sum()   fun sum35(n: BigInteger): BigInteger { val nn = n - BigInte...
Give a code snippet in #Kotlin Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
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...
#Picat
Picat
go => N = 0, do N := N+1, println(N) while (N mod 6 != 0).
Give a code snippet in #Picat 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/D...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Julia
Julia
f(x, y) = x * sqrt(y) theoric(t) = (t ^ 2 + 4.0) ^ 2 / 16.0   rk4(f) = (t, y, δt) -> # 1st (result) lambda ((δy1) -> # 2nd lambda ((δy2) -> # 3rd lambda ((δy3) -> # 4th lambda ((δy4) -> ( δy1 + 2δy2 + 2δy3 + δy4 ) / 6 # 5th and deepest lambda: calc y_{n+1} )(...
Give a code snippet in #Julia Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This eq...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_wheel
Color wheel
Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understand how color wheels work and ...
#M2000_Interpreter
M2000 Interpreter
  Module Check { \\ we use an internal object for Math functions (here for Atan2) Declare Math Math Const tau=2*Pi, Center=2 \\ change console size, and center it ( using ;) to current monitor Window 12, 800*twipsX,600*twipsY; \\ actual size maybe less (so can fit text exactly...
Give a code snippet in #M2000_Interpreter Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does hel...
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Ruby
Ruby
require 'pstore' require 'set'   Address = Struct.new :id, :street, :city, :state, :zip   db = PStore.new("addresses.pstore") db.transaction do db[:next] ||= 0 # Next available Address#id db[:ids] ||= Set[] # Set of all ids in db end
Give a code snippet in #Ruby Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state cod...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Delphi
Delphi
  (define-syntax-rule (deg->radian deg) (* deg 1/180 PI)) (define-syntax-rule (radian->deg rad) (* 180 (/ PI) rad))   (define (mean-angles angles) (radian->deg (angle (for/sum ((a angles)) (make-polar 1 (deg->radian a))))))   (mean-angles '( 350 10)) → -0 (mean-angles '[90 180 270 360]) → -9...
Give a code snippet in #Delphi When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#BBC_BASIC
BBC BASIC
DIM matrix(2,3) matrix() = 1, 2, -1, -4, \ \ 2, 3, -1, -11, \ \ -2, 0, -3, 22 PROCrref(matrix()) FOR row% = 0 TO 2 FOR col% = 0 TO 3 PRINT matrix(row%,col%); NEXT PRINT NEXT row% END   DEF PROCrref(m()) LOCAL ...
Give a code snippet in #BBC_BASIC Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is conve...
christopher/rosetta-code
http://rosettacode.org/wiki/History_variables
History variables
Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables are variables in a programming la...
#Clojure
Clojure
  (def a (ref 0)) (def a-history (atom [@a])) ; define a history vector to act as a stack for changes on variable a (add-watch a :hist (fn [key ref old new] (swap! a-history conj new)))  
Give a code snippet in #Clojure Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging. History variables ...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Fortran
Fortran
program population_count implicit none   integer, parameter :: i64 = selected_int_kind(18) integer(i64) :: x integer :: i, n   x = 1 write(*, "(a8)", advance = "no") "3**i :" do i = 1, 30 write(*, "(i3)", advance = "no") popcnt(x) x = x * 3 end do   write(*,*) write(*, "(a8)", advance = "no"...
Give a code snippet in #Fortran Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop cou...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Common_Lisp
Common Lisp
(defun nonempty (seq) (position-if (lambda (x) (declare (ignore x)) t) seq))   (defun split (delim seq) "Splits seq on delim into a list of subsequences. Trailing empty subsequences are removed." (labels ((f (seq &aux (pos (position delim seq))) (if pos (cons (subseq seq ...
Give a code snippet in #Common_Lisp Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be eith...
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#REXX
REXX
/*REXX program converts a mm/dd/yyyy Gregorian date ───► a Discordian date. */ @day.1= 'Sweetness' /*define the 1st day─of─Discordian─week*/ @day.2= 'Boomtime' /* " " 2nd " " " " */ @day.3= 'Pungenday' ...
Give a code snippet in #REXX Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#C
C
  #include<stdlib.h> #include<string.h> #include<stdio.h>   int flag = 1;   void heapPermute(int n, int arr[],int arrLen){ int temp; int i;   if(n==1){ printf("\n[");   for(i=0;i<arrLen;i++) printf("%d,",arr[i]); printf("\b] Sign : %d",flag);   flag*=-1; } else{ for(i=0;i<n-1;i++){ heapPermute(n-1,...
Give a code snippet in #C Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#min
min
(5 2 1 3 4) '> sort print
Give a code snippet in #min 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/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Swift
Swift
let hex = 0x2F // Hexadecimal let bin = 0b101111 // Binary let oct = 0o57 // Octal
Give a code snippet in #Swift Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Scilab
Scilab
error("Goodbye, World!")
Give a code snippet in #Scilab Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#langur
langur
val .countingSort = f(.array) { val .min, .max = minmax(.array) var .count = arr .max-.min+1, 0 for .i in .array { .count[.i-.min+1] += 1 } for .i of .count { _for ~= arr .count[.i], .i+.min-1 } }   val .data = [7, 234, -234, 9, 43, 123, 14]   writeln "Original: ", .data writeln "Sorted  : ", .countingS...
Give a code snippet in #langur 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/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Action.21
Action!
PROC Main() INT ARRAY xs=[249 200 96 80 175] BYTE ARRAY ys=[82 176 159 55 7] INT x,y BYTE i,CH=$02FC,COLOR1=$02C5,COLOR2=$02C6   Graphics(8+16) Color=1 COLOR1=$0C COLOR2=$02   x=160+Rand(30) y=96+Rand(30) DO i=Rand(5) x=x+(xs(i)-x)*62/100 y=y+(ys(i)-y)*62/100 Plot(x,y) UNTIL CH#$FF ...
Give a code snippet in #Action.21 Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#F.23
F#
  //Floyd's algorithm: Nigel Galloway August 5th 2018 let Floyd (n:'a[]) (g:Map<('a*'a),int>)= //nodes graph(Map of adjacency list) let ix n g=Seq.init (pown g n) (fun x->List.unfold(fun (a,b)->if a=0 then None else Some(b%g,(a-1,b/g)))(n,x)) let fN w (i,j,k)=match Map.tryFind(i,j) w,Map.tryFind(i,k) w,Map.tryFind(...
Give a code snippet in #F.23 The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already bee...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#Arturo
Arturo
i: new 0 next: new 1 MAX: 15 while [next =< MAX][ if next = size factors i [ prints ~"|i| " inc 'next ] inc 'i ] print ""
Give a code snippet in #Arturo Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#JavaScript
JavaScript
for (let i of [...Array(5000).keys()] .filter(n => n == n.toString().split('') .reduce((a, b) => a+Math.pow(parseInt(b),parseInt(b)), 0))) console.log(i);
Give a code snippet in #JavaScript A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also ...
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...
#ALGOL_68
ALGOL 68
PROC make list = ( STRING separator )STRING: BEGIN INT counter := 0; PROC make item = ( STRING item )STRING: BEGIN counter +:= 1; whole( counter, 0 ) + separator + item + REPR 10 END; # make item # make item( "first" ) + make item( "...
Give a code snippet in #ALGOL_68 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 ...
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...
#R
R
hello <- "hello" paste(hello, "literal") # "hello literal" hl <- paste(hello, "literal") #saves concatenates string to a new variable paste("no", "spaces", "between", "words", sep="") # "nospacesbetweenwords"
Give a code snippet in #R 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#PL.2FI
PL/I
  tp: procedure options (main); declare primes(1000000) bit (1); declare max_primes fixed binary (31); declare (i, k) fixed binary (31);   max_primes = hbound(primes, 1); call sieve;   /* Now search for primes that are right-truncatable. */ call right_truncatable;   /* Now search for primes...
Give a code snippet in #PL.2FI A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncata...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#langur
langur
writeln "yo, peeps"
Give a code snippet in #langur Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Rust
Rust
fn main() { for i in 1..=100 { match (i % 3, i % 5) { (0, 0) => println!("fizzbuzz"), (0, _) => println!("fizz"), (_, 0) => println!("buzz"), (_, _) => println!("{}", i), } } }
Give a code snippet in #Rust Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Chef
Chef
Sum and Product of Numbers as a Piece of Cake.   This recipe sums N given numbers.   Ingredients. 1 N 0 sum 1 product 1 number   Method. Put sum into 1st mixing bowl. Put product into 2nd mixing bowl. Take N from refrigerator. Chop N. Take number from refrigerator. Add number into 1st mixing bowl. Combine number into 2...
Give a code snippet in #Chef Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Maple
Maple
  Map:=proc(a1,a2,b1,b2,s); return (b1+((s-a1)*(b2-b1)/(a2-a1))); end proc;   for i from 0 to 10 do printf("%a maps to ",i); printf("%a\n",Map(0,10,-1,0,i)); end do;  
Give a code snippet in #Maple Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly m...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#FALSE
FALSE
[^$1+][$32|$$'z>'a@>|$[\%]?~[13\'m>[_]?+]?,]#%
Give a code snippet in #FALSE Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Lua
Lua
local matrix = require "matrix" -- https://github.com/davidm/lua-matrix   local function cramer(mat, vec) -- Check if matrix is quadratic assert(#mat == #mat[1], "Matrix is not square!") -- Check if vector has the same size of the matrix assert(#mat == #vec, "Vector has not the same size of the matrix!")   lo...
Give a code snippet in #Lua linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Sidef
Sidef
require('Time::Local')   for year in (2008 .. 2121) { var time = %S<Time::Local>.timelocal(0,0,0,25,11,year) var wd = Time(time).local.wday if (wd == 0) { say "25 Dec #{year} is Sunday" } }
Give a code snippet in #Sidef A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between ...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
showbool a b:  !.( a b or a b and a b xor a b not a )   for a in [ false true ]: for b in [ false true ]: showbool a b
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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...
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...
#Scala
Scala
import scala.io.Source   object parseCSV extends App {   val rawData = """|C1,C2,C3,C4,C5 |1,5,9,13,17 |2,6,10,14,18 |3,7,11,15,19 |20,21,22,23,24""".stripMargin   val data = Seq((Source.fromString(rawData).getLines()).map(_.split(",")).toSeq: _*)   val output = ((data.take(1)....
Give a code snippet in #Scala 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, chan...
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
flip[a_] := Block[{a1 = First@a}, If[a1 == Length@a, Reverse[a], Join[Reverse[a[[;; a1]]], a[[a1 + 1 ;;]]]]] swaps[a_] := Length@FixedPointList[flip, a] - 2 Print[#, ": ", Max[swaps /@ Permutations[Range@#]]] & /@ Range[10];
Give a code snippet in #Mathematica.2FWolfram_Language Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card ...
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...
#Haskell
Haskell
import Data.List import Data.Array import Control.Monad import Control.Arrow import Matrix.LU   ppoly p x = map (x**) p   polyfit d ry = elems $ solve mat vec where mat = listArray ((1,1), (d,d)) $ liftM2 concatMap ppoly id [0..fromIntegral $ pred d] vec = listArray (1,d) $ take d ry
Give a code snippet in #Haskell 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 coefficien...
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 ...
#Modula-2
Modula-2
MODULE LevenshteinDistance; FROM InOut IMPORT WriteString, WriteCard, WriteLn; FROM Strings IMPORT Length;   PROCEDURE levenshtein(s, t: ARRAY OF CHAR): CARDINAL; CONST MaxLen = 15; VAR d: ARRAY [0..MaxLen],[0..MaxLen] OF CARDINAL; lenS, lenT, i, j: CARDINAL;   PROCEDURE min(a, b: CARDINAL): CARDINA...
Give a code snippet in #Modula-2 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#HolyC
HolyC
main //Bits aka Booleans. b $= bit()   b $= true print(b)   b $= false print(b)   //Non-zero values are true. b $= bit(1) print(b)   b $= -1 print(b)   //Zero values are false b $= 0 print(b) }
Give a code snippet in #HolyC Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#D
D
T sumSquares(T)(T[] a) pure nothrow @safe @nogc { T sum = 0; foreach (e; a) sum += e ^^ 2; return sum; }   void main() { import std.stdio: writeln;   [3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln; }
Give a code snippet in #D Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#C.23
C#
using System; using System.Linq; using System.Text; using System.Text.RegularExpressions;   namespace MadLibs_RosettaCode { class Program { static void Main(string[] args) { string madLibs = @"Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The...
Give a code snippet in #C.23 This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#CoffeeScript
CoffeeScript
  # This is one of many ways to create a table. CoffeeScript plays nice # with any templating solution built for JavaScript, and of course you # can build tables in the browser using DOM APIs. This approach is just # brute force string manipulation.   table = (header_row, rows) -> """ <table> #{header_row} #{...
Give a code snippet in #CoffeeScript Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is fil...
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...
#Clojure
Clojure
(def ! (memoize #(apply * (range 1 (inc %)))))   (defn catalan-numbers-direct [] (map #(/ (! (* 2 %)) (* (! (inc %)) (! %))) (range)))   (def catalan-numbers-recursive #(->> [1 1] ; [c0 n1] (iterate (fn [[c n]] [(* 2 (dec (* 2 n)) (/ (inc n)) c) (inc n)]) ,) (map first ,)))   user> (take 15 (...
Give a code snippet in #Clojure 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/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
5000 CLS 5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f 5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT" 5010 LET la=LEN a$ 5011 LET i=1: LET u=0 5020 LET d=0: LET p=(u=0)-(u=1) 5021 LET l=(i AND u=0)+(la-i+u AND u=1) 5030 IF u=0 THEN IF a$(l+1)>=a$(l) THEN GO TO 5050 5031 IF u=1 THEN IF a$(l-1)<...
Give a code snippet in #ZX_Spectrum_Basic Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Scheme
Scheme
(import (scheme base) (scheme write) (srfi 1) ; list library (srfi 27)) ; random numbers   (random-source-randomize! default-random-source)   ;; Random integer in [start, end) (define (random-between start end) (let ((len (- end start 1))) (if (< len 2) start (+ start (random-integ...
Give a code snippet in #Scheme Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#JavaScript
JavaScript
//using object literal syntax var point = {x : 1, y : 2};   //using constructor var Point = function (x, y) { this.x = x; this.y = y; }; point = new Point(1, 2);   //using ES6 class syntax class Point { constructor(x, y) { this.x = x; this.y = y; } } point = new Point(1, 2);
Give a code snippet in #JavaScript 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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values....
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Java
Java
public class ModularArithmetic { private interface Ring<T> { Ring<T> plus(Ring<T> rhs);   Ring<T> times(Ring<T> rhs);   int value();   Ring<T> one();   default Ring<T> pow(int p) { if (p < 0) { throw new IllegalArgumentException("p must be zero or ...
Give a code snippet in #Java Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, tw...
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.
#Oz
Oz
declare Lst = [1 2 3 4 5] LstEven = {Filter Lst IsEven}
Give a code snippet in #Oz 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/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Perl
Perl
use ntheory ":all"; my $i = 0; for (1..1e6) { my $n = pn_primorial($_); if (is_prime($n-1) || is_prime($n+1)) { print "$_\n"; last if ++$i >= 20; } }
Give a code snippet in #Perl The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off bei...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Logtalk
Logtalk
  :- object(error_message).   % the initialization/1 directive argument is automatically executed % when the object is compiled and loaded into memory: :- initialization(write(user_error, 'Goodbye, World!\n')).   :- end_object.  
Give a code snippet in #Logtalk Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard ou...
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...
#Ruby
Ruby
cube = proc{|x| x ** 3} croot = proc{|x| x ** (1.quo 3)} compose = proc {|f,g| proc {|x| f[g[x]]}} funclist = [Math.method(:sin), Math.method(:cos), cube] invlist = [Math.method(:asin), Math.method(:acos), croot]   puts funclist.zip(invlist).map {|f, invf| compose[invf, f][0.5]}
Give a code snippet in #Ruby 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 fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;   class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 12...
Give a code snippet in #C.23 Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Clojure
Clojure
(defn luhn? [cc] (let [sum (->> cc (map #(Character/digit ^char % 10)) reverse (map * (cycle [1 2])) (map #(+ (quot % 10) (mod % 10))) (reduce +))] (zero? (mod sum 10))))   (defn is-valid-isin? [isin] (and (re-matches #"^[A-Z]{...
Give a code snippet in #Clojure An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the corre...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Racket
Racket
  #lang racket   (require net/url)   (define (get-lines url-string) (define port (get-pure-port (string->url url-string))) (for/list ([l (in-lines port)]) l))   (define (hash-words words) (for/fold ([ws-hash (hash)]) ([w words]) (hash-update ws-hash (list->string (sort (string->list...
Give a code snippet in #Racket When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#AWK
AWK
{ scram = best_shuffle($0) print $0 " -> " scram " (" unchanged($0, scram) ")" }   function best_shuffle(s, c, i, j, len, r, t) { len = split(s, t, "")   # Swap elements of t[] to get a best shuffle. for (i = 1; i <= len; i++) { for (j = 1; j <= len; j++) { # Swap t[i] and t[j] if they will not match # ...
Give a code snippet in #AWK Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is...
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
#Brat
Brat
include :subprocess   p subprocess.run :ls #Lists files in directory
Give a code snippet in #Brat 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/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#E
E
Give a code snippet in #E Task Create the simplest possible program that is still considered "correct."
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 ...
#Pharo
Pharo
'123' reversed
Give a code snippet in #Pharo 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#Bracmat
Bracmat
( ( hidato = Line solve lowest Ncells row column rpad , Board colWidth maxDigits start curCol curRow , range head line cellN solution output tail . out$!arg & @(!arg:? ((%@:>" ") ?:?arg)) & 0:?row:?column & :?Board & ( Line = token . whl ...
Give a code snippet in #Bracmat The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always conn...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Perl
Perl
package T; sub new { my $cls = shift; bless [ @_ ], $cls }   sub set_data { my $self = shift; @$self = @_; }   sub copy { my $self = shift; bless [ @$self ], ref $self; }   sub manifest { my $self = shift; print "type T, content: @$self\n\n"; }   package S...
Give a code snippet in #Perl An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory 'is_prime';   sub magnanimous { my($n) = @_; my $last; for my $c (1 .. length($n) - 1) { ++$last and last unless is_prime substr($n,0,$c) + substr($n,$c) } not $last; }   my @M; for ( my $i = 0, my $count = 0; $count < 400; $i++ ) { ...
Give a code snippet in #Perl A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. ...
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...
#Wortel
Wortel
; Recursive @var rec &[a v l h] [ @if < h l @return null @var m @/ +h l 2 @? { > `m a v @!rec[a v l -m 1] < `m a v @!rec[a v +1 m h] m } ]   ; Iterative @var itr &[a v] [ @vars{l 0 h #-a} @while <= l h [ @var m @/ +l h 2 @iff { > `m a v :h -m 1 < `m a v :l +m 1 @return ...
Give a code snippet in #Wortel 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 ...
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...
#EchoLisp
EchoLisp
  (version) → EchoLisp - 2.50.3 📗 local-db: db.version: 3   (when (< (version) 2.6) (writeln "Please reload EchoLisp : CTRL-F5, CMD-R or other...") (exit))   (if (and (bound? 'bloop) (bound? 'abs) (procedure? abs)) (abs bloop) 'NOT-HERE) → NOT-HERE   (define bloop -777) → bloop (if (and (bound? 'bloo...
Give a code snippet in #EchoLisp 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 ...
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...
#Forth
Forth
s" hello" pad place pad count type s" there!" pad +place \ +place is called "append" on some Forths pad count type
Give a code snippet in #Forth 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 lit...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Factor
Factor
11 <iota> <reversed> [ . ] each
Give a code snippet in #Factor Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incre...
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 ...
#Plain_TeX
Plain TeX
\def\gobtoA#1\revA{}\def\gobtoB#1\revB{} \def\reverse#1{\reversei{}#1\revA\revB\revB\revB\revB\revB\revB\revB\revB\revA} \def\reversei#1#2#3#4#5#6#7#8#9{\gobtoB#9\revend\revB\reversei{#9#8#7#6#5#4#3#2#1}} \def\revend\revB\reversei#1#2\revA{\gobtoA#1} \reverse{Rosetta} \bye
Give a code snippet in #Plain_TeX 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 E...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Lasso
Lasso
sys_process('/usr/bin/osascript', (: '-e', 'display dialog "Goodbye, World!"'))->wait
Give a code snippet in #Lasso Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Haskell
Haskell
import Data.Map hiding (map, filter) import Graphics.Gloss import Control.Monad.Random   data Ball = Ball { position :: (Int, Int), turns :: [Int] }   type World = ( Int -- number of rows of pins , [Ball] -- sequence of balls , Map Int Int ) -- counting bins   updateWorld :: W...
Give a code snippet in #Haskell Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A num...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Swift
Swift
func angleDifference(a1: Double, a2: Double) -> Double { let diff = (a2 - a1).truncatingRemainder(dividingBy: 360)   if diff < -180.0 { return 360.0 + diff } else if diff > 180.0 { return -360.0 + diff } else { return diff } }   let testCases = [ (20.0, 45.0), (-45, 45), (-85, 90), (-95, 9...
Give a code snippet in #Swift Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#HicEst
HicEst
CHARACTER in*1000, out*100   READ(ClipBoard) in EDIT(Text=in, SPR='"', Right='<Student', Right='Name=', Word=1, WordEnd, APpendTo=out, DO)
Give a code snippet in #HicEst Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender...
christopher/rosetta-code
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val boxW = 41 // Galton box width. val boxH = 37 // Galton box height. val pinsBaseW = 19 // Pins triangle base. val nMaxBalls = 55 // Number of balls.   val centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1 val rand = Random()   enum class Cell(val c: ...
Give a code snippet in #Kotlin Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Julia
Julia
using Random   shufflerows(mat) = mat[shuffle(1:end), :] shufflecols(mat) = mat[:, shuffle(1:end)]   function addatdiagonal(mat) n = size(mat)[1] + 1 newmat = similar(mat, size(mat) .+ 1) for j in 1:n, i in 1:n newmat[i, j] = (i == n && j < n) ? mat[1, j] : (i == j) ? n - 1 : (i < j) ? m...
Give a code snippet in #Julia A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Rust
Rust
use std::collections::HashMap; use std::fs::File; use std::io::{BufRead,BufReader}; use std::borrow::ToOwned;   extern crate unicode_segmentation; use unicode_segmentation::{UnicodeSegmentation};   fn main () { let file = BufReader::new(File::open("unixdict.txt").unwrap()); let mut map = HashMap::new(); for...
Give a code snippet in #Rust When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in th...
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...
#Julia
Julia
using Plots   function yellowstone(N) a = [1, 2, 3] b = Dict(1 => 1, 2 => 1, 3 => 1) start = 4 while length(a) < N inseries = true for i in start:typemax(Int) if haskey(b, i) if inseries start += 1 end else ...
Give a code snippet in #Julia 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...
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...
#Ruby
Ruby
def zero(f) return lambda {|x| x} end Zero = lambda { |f| zero(f) }   def succ(n) return lambda { |f| lambda { |x| f.(n.(f).(x)) } } end   Three = succ(succ(succ(Zero)))   def add(n, m) return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } } end   def mult(n, m) return lambda { |f| lambda { |x| m.(n.(f)).(x) } }...
Give a code snippet in #Ruby 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Elixir
Elixir
# current directory IO.inspect File.ls!   dir = "/users/public" IO.inspect File.ls!(dir)
Give a code snippet in #Elixir Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory,...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#K
K
$ k -e "\`0: \"hello\\n\""
Give a code snippet in #K Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Emacs_Lisp
Emacs Lisp
; === Graphical Julia set display in Emacs =====================   (setq julia-size (cons 300 200)) (setq xmin -1.5) (setq xmax 1.5) (setq ymin -1) (setq ymax 1) (setq julia0 (cons -0.512511498387847167 0.521295573094847167)) (setq max-iter 100)   (defun julia-iter-point (x y) "Run the actual iteration for each point...
Give a code snippet in #Emacs_Lisp Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#APL
APL
dec31weekday ← {7|(⍵+⌊(⍵÷4)+⌊(⍵÷400)-⌊⍵÷100)} isolongyear ← {(4 = dec31weekday ⍵) ∨ (3 = dec31weekday (⍵ - 1))}
Give a code snippet in #APL Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#F.23
F#
> String.replicate 5 "ha";; val it : string = "hahahahaha"
Give a code snippet in #F.23 Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#Delphi
Delphi
  program Factorions;   {$APPTYPE CONSOLE}   uses System.SysUtils;   begin var fact: TArray<UInt64>; SetLength(fact, 12);   fact[0] := 0; for var n := 1 to 11 do fact[n] := fact[n - 1] * n;   for var b := 9 to 12 do begin writeln('The factorions for base ', b, ' are:'); for var i := 1 to 14999...
Give a code snippet in #Delphi Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1...
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) ...
#F.23
F#
  open System.Drawing   let (|F1|F2|F3|F4|) r = if r < 0.01 then F1 else if r < 0.08 then F3 else if r < 0.15 then F4 else F2   let barnsleyFernFunction (x, y) = function | F1 -> (0.0, 0.16*y) | F2 -> ((0.85*x + 0.04*y), (-0.04*x + 0.85*y + 1.6)) | F3 -> ((0.2*x - 0.26*y), (0.23*x + 0.22*y +...
Give a code snippet in #F.23 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 ...
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...
#EDSAC_order_code
EDSAC order code
[ Even or odd ===========   A program for the EDSAC   Determines whether the number stored at address 15@ is even or odd, and prints 'E' or 'O' accordingly   Works with Initial Orders 2 ]   T56K [ load point ] GK [ base address ]   O11@ [ print letter shift ] T10@ [ cle...
Give a code snippet in #EDSAC_order_code 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#C.2B.2B
C++
  #include <iostream> #include <boost/filesystem.hpp>   using namespace boost::filesystem;   int main(int argc, char *argv[]) { for (int i = 1; i < argc; ++i) { path p(argv[i]);   if (exists(p) && is_directory(p)) std::cout << "'" << argv[i] << "' is" << (!is_empty(p) ? " not" : "") << "...
Give a code snippet in #C.2B.2B Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an ...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Erlang
Erlang
  -module(continued). -compile([export_all]).   pi_a (0) -> 3; pi_a (_N) -> 6.   pi_b (N) -> (2*N-1)*(2*N-1).   sqrt2_a (0) -> 1; sqrt2_a (_N) -> 2.   sqrt2_b (_N) -> 1.   nappier_a (0) -> 2; nappier_a (N) -> N.   nappier_b (1) -> 1; nappier_b (N) -> N-1.   continued_fraction(FA,_FB,0) -...
Give a code snippet in #Erlang continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#XBS
XBS
func printChars(from,to,st){ set arr=[]; for(c=from;to;1){ arr->push(string.byte(c)); } log(st," ",arr); del arr; }   printChars(0x61,0x7a,"lowercase"); printChars(0x41,0x5a,"UPPERCASE");
Give a code snippet in #XBS Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task re...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Fortran
Fortran
program test_sleep   implicit none integer :: iostat integer :: seconds character (32) :: argument   if (iargc () == 1) then call getarg (1, argument) read (argument, *, iostat = iostat) seconds if (iostat == 0) then write (*, '(a)') 'Sleeping...' call sleep (seconds) write (*, '...
Give a code snippet in #Fortran Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thre...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#zkl
zkl
fcn ceToChineseZodiac(ce_year){ // --> list of strings # encoding: utf-8 var [const] pinyin=SD( // create some static variables, SD is small fixed dictionary "甲","jiă", "乙","yĭ", "丙","bĭng", "丁","dīng", "戊","wù", "己","jĭ", "庚","gēng", "辛","xīn", "壬","rén", "癸","gŭi",   "子","zĭ", "丑","chŏu", "寅...
Give a code snippet in #zkl Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results ...
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Haskell
Haskell
data Error a = Error {value :: a, uncertainty :: a} deriving (Eq, Show)   instance (Floating a) => Num (Error a) where Error a ua + Error b ub = Error (a + b) (sqrt (ua ^ 2 + ub ^ 2)) negate (Error a ua) = Error (negate a) ua Error a ua * Error b ub = Error (a * b) (abs (a * b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) ...
Give a code snippet in #Haskell If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then...
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,...
#ACL2
ACL2
;; Create an array and store it in array-example (assign array-example (compress1 'array-example (list '(:header :dimensions (10) :maximum-length 11))))   ;; Set a[5] to 22 (assign array-example (aset1 'array-example (@ array-example) ...
Give a code snippet in #ACL2 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 retrie...
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 ...
#Perl
Perl
# 20201101 added Perl programming solution   use strict; use warnings;   use Data::Monad::Maybe;   sub safeReciprocal { ( $_[0] == 0 ) ? nothing : just( 1 / $_[0] ) }   sub safeRoot { ( $_[0] < 0 ) ? nothing : just( sqrt( $_[0] ) ) }   sub safeLog { ( $_[0] <= 0 ) ? nothing : just( log ( $_[0] ) ) }  ...
Give a code snippet in #Perl 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/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Verilog
Verilog
  module main; integer i, n;   initial begin n = 45;   $write(n, " =>"); for(i = 1; i <= n / 2; i = i + 1) if(n % i == 0) $write(i); $display(n); $finish ; end endmodule  
Give a code snippet in #Verilog 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