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/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 ≤...
#EasyLang
EasyLang
a$ = input while i < len a$ and substr a$ i 1 <> " " i += 1 . a = number substr a$ 0 i b = number substr a$ i -1 print a + b  
Give a code snippet in #EasyLang 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, separ...
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...
#Zoea
Zoea
  program: rot13 case: 1 input: abc output: nop case: 2 input: nop output: abc case: 3 input: 'ABC' output: 'NOP' case: 4 input: 'NOP' output: 'ABC'  
Give a code snippet in #Zoea 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/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#PicoLisp
PicoLisp
(de guessTheNumber () (use (Low High Guess) (until (and (prin "Enter low limit : ") (setq Low (read)) (prin "Enter high limit: ") (setq High (read)) (> High Low) ) ) (seed (time)) (let Number (rand Low High) (loop ...
Give a code snippet in #PicoLisp Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#ooRexx
ooRexx
/* Rexx */   -- MathLoadFuncs & MathDropFuncs are no longer needed and are effectively NOPs -- but MathLoadFuncs does return its copyright statement when given a string argument RxMathCopyright = MathLoadFuncs('') say RxMathCopyright   numeric digits 16   x = 2.5 y = 3 pad = 40 digs = digits() say say 'Working with pre...
Give a code snippet in #ooRexx Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Transd
Transd
#lang transd   mainModule : { func2: (lambda i Int() (if (!= i 13) (textout "OK " i "\n") (throw "fail\n"))),   func1: (lambda (textout "before try\n") (try (textout "before while\n") (with n 10 (while (< n 15) (+= n 1) (func2 n) ) ) (te...
Give a code snippet in #Transd Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exception...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#Maple
Maple
attractivenumbers := proc(n::posint) local an, i; an :=[]: for i from 1 to n do if isprime(NumberTheory:-NumberOfPrimeFactors(i)) then an := [op(an), i]: end if: end do: end proc: attractivenumbers(120);
Give a code snippet in #Maple A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task S...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#FreeBASIC
FreeBASIC
  Function Filtrar(cadorigen As String) As String Dim As String letra Dim As String filtrado = "" For i As Integer = 1 To Len(cadorigen) letra = Ucase(Mid(cadorigen, i, 1)) If Instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", letra) Then filtrado += letra Next i Return filtrado End Function   Fun...
Give a code snippet in #FreeBASIC Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note o...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#XLISP
XLISP
(defun guessing-game (a b) ; minimum and maximum, to be supplied by the user (defun prompt () (display "What is your guess? ") (define guess (read)) (if (eq guess n) ; EQ, unlike =, won't blow up ; if GUESS isn't a number (display "Well guessed!") ...
Give a code snippet in #XLISP Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hi...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
SetOptions[EvaluationNotebook[], NotebookEventActions -> {{"KeyDown", "t"} :> Print["You pressed \"t\""]}]
Give a code snippet in #Mathematica.2FWolfram_Language Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Go
Go
package main   import "fmt"   func narc(n int) []int { power := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} limit := 10 result := make([]int, 0, n) for x := 0; len(result) < n; x++ { if x >= limit { for i := range power { power[i] *= i // i^m } limit *= 10 } sum := 0 for xx := x; xx > 0; xx /= 10 { ...
Give a code snippet in #Go A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m} ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Common_Lisp
Common Lisp
(defmacro concatenatef (s &rest strs) "Append additional strings to the first string in-place." `(setf ,s (concatenate 'string ,s ,@strs))) (defvar *str* "foo") (concatenatef *str* "bar") (format T "~a~%" *str*) (concatenatef *str* "baz" "abc" "def") (format T "~a~%" *str*)
Give a code snippet in #Common_Lisp 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Ada
Ada
with Ada.Text_IO; procedure Numbers is package Int_IO is new Ada.Text_IO.Integer_IO (Integer); package Float_IO is new Ada.Text_IO.Float_IO (Float); begin Int_IO.Put (Integer'Value ("16#ABCF123#")); Ada.Text_IO.New_Line; Int_IO.Put (Integer'Value ("8#7651#")); Ada.Text_IO.New_Line; Int_IO.Put (Inte...
Give a code snippet in #Ada It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of su...
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...
#Beads
Beads
beads 1 program 'Caesar cipher' calc main_init var str = "The five boxing wizards (🤖) jump quickly." log "Plain: {str}" str = Encrypt(str, 3) log "Encrypted: {str}" str = Decrypt(str, 3) log "Decrypted: {str}"   // encrypt a string by shifting the letters over by a number of slots // pass through any character...
Give a code snippet in #Beads 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Ursala
Ursala
#import nat #import flo   pop_stats("mu","sigma") = plus/*"mu"+ times/*"sigma"+ Z*+ iota   sample_stats("mu","sigma") = plus^*D(minus/"mu"+ mean,~&)+ vid^*D(div\"sigma"+ stdev,~&)+ Z*+ iota   #cast %eWL   test =   ^(mean,stdev)* < pop_stats(1.,0.5) 1000, sample_stats(1.,0.5) 1000>
Give a code snippet in #Ursala Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Relate...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#PARI.2FGP
PARI/GP
externstr("time/t")
Give a code snippet in #PARI.2FGP Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Bracmat
Bracmat
( root = sum persistence n d .  !arg:(~>9.?) |  !arg:(?n.?persistence) & 0:?sum & ( @( !n  :  ? (#%@?d&!d+!sum:?sum&~)  ? ) | root$(!sum.!persistence+1) ) ) & ( 627615 39390 588225 393900588225 10 199 ...
Give a code snippet in #Bracmat The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Icon_and_Unicon
Icon and Unicon
record mutable(value) # record wrapper to provide mutable access to immutable types   procedure main() A := mutable() write( sum(A, 1, 100, create 1.0/A.value) ) end   procedure sum(A, lo, hi, term) temp := 0 every A.value := lo to hi do temp +:= @^term return temp end
Give a code snippet in #Icon_and_Unicon Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studyi...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Nim
Nim
import macros   proc newIfElse(c, t, e: NimNode): NimNode {.compiletime.} = result = newIfStmt((c, t)) result.add(newNimNode(nnkElse).add(e))   macro if2(x, y: bool; z: untyped): untyped = var parts: array[4, NimNode] for i in parts.low .. parts.high: parts[i] = newNimNode(nnkDiscardStmt).add(NimNode(nil)) ...
Give a code snippet in #Nim Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. b...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#C.2B.2B
C++
#include <iostream> #include <fstream> #include <string>   using namespace std;   int main() { string line; ifstream input ( "input.txt" ); ofstream output ("output.txt");   if (output.is_open()) { if (input.is_open()){ while (getline (input,line)) { output << line <<...
Give a code snippet in #C.2B.2B File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Maple
Maple
  readinput:=proc(filename) local line,file; file:=""; line:=readline(filename); while line<>0 do line:=readline(filename); file:=cat(file,line); end do; end proc;  
Give a code snippet in #Maple Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Ring
Ring
  # Project: SHA-256   load "stdlib.ring" str = "Rosetta code" see "String: " + str + nl see "SHA-256: " see sha256(str) + nl  
Give a code snippet in #Ring SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.23
C#
using System; using System.Collections.Generic; using System.Text;   public class HeapSortClass { public static void HeapSort<T>(T[] array) { HeapSort<T>(array, 0, array.Length, Comparer<T>.Default); }   public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer) ...
Give a code snippet in #C.23 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/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Forth
Forth
: ** ( n m -- n^m ) 1 swap 0 ?do over * loop nip ;
Give a code snippet in #Forth Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Raku
Raku
if $problem { exit $error-code }
Give a code snippet in #Raku Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#Vlang
Vlang
fn partition(mut arr []int, low int, high int) int { pivot := arr[high] mut i := (low - 1) for j in low .. high { if arr[j] < pivot { i++ temp := arr[i] arr[i] = arr[j] arr[j] = temp } } temp := arr[i + 1] arr[i + 1] = arr[high] arr[high] = temp return i + 1 }   fn quick_sort(mut arr []int, low ...
Give a code snippet in #Vlang Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Racket
Racket
  #lang racket (require math/number-theory)   (define (truncate-right n) (quotient n 10))   (define (truncate-left n) (define s (number->string n)) (string->number (substring s 1 (string-length s))))   (define (contains-zero? n) (member #\0 (string->list (number->string n))))   (define (truncatable? truncate n)...
Give a code snippet in #Racket 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/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#zonnon
zonnon
  module Assertions; var a: integer; begin a := 40; assert(a = 42,100) end Assertions.  
Give a code snippet in #zonnon Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Swift
Swift
import Darwin   func ethiopian(var #int1:Int, var #int2:Int) -> Int { var lhs = [int1], rhs = [int2]   func isEven(#n:Int) -> Bool {return n % 2 == 0} func double(#n:Int) -> Int {return n * 2} func halve(#n:Int) -> Int {return n / 2}   while int1 != 1 { lhs.append(halve(n: int1)) rhs.append(double(n: ...
Give a code snippet in #Swift 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 w...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
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 |...
#PARI.2FGP
PARI/GP
a=input(); b=input(); if(a<b, print(a" < "b)); if(a==b, print(a" = "b)); if(a>b, print(a" > "b));
Give a code snippet in #PARI.2FGP 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#PARI.2FGP
PARI/GP
shellSort(v)={ my(inc=#v\2); while(inc, for(i=inc+1,#v, my(t=v[i],j=i); while(j>inc && v[j-inc]>t, v[j]=v[j-=inc] ); v[j]=t ); inc \= 2.2 ); v };
Give a code snippet in #PARI.2FGP 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 | Quic...
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...
#Objective-C
Objective-C
NSMutableArray *stack = [NSMutableArray array]; // creating   [stack addObject:value]; // pushing   id value = [stack lastObject]; [stack removeLastObject]; // popping   [stack count] == 0 // is empty?
Give a code snippet in #Objective-C 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...
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 ...
#Quackery
Quackery
$ "rosetta/unixdict.txt" sharefile drop nest$ [] swap witheach [ dup sort nested swap nested join nested join ] sortwith [ 0 peek swap 0 peek $< ] dup [ dup [] ' [ [ ] ] rot witheach [ tuck 0 peek swap 0 peek = if [ tuck nested join swap ] ] drop dup [] !=...
Give a code snippet in #Quackery 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#MATLAB_.2F_Octave
MATLAB / Octave
function twentyfour() N = 4; n = ceil(rand(1,N)*9); printf('Generate a equation with the numbers %i, %i, %i, %i and +, -, *, /, () operators ! \n',n); s = input(': ','s'); t = s; for k = 1:N, [x,t] = strtok(t,'+-*/() \t'); if length(x)~=1, error('invalid sign %s\n',x); end; y = ...
Give a code snippet in #MATLAB_.2F_Octave The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#Idris
Idris
quicksort : Ord elem => List elem -> List elem quicksort [] = [] quicksort (x :: xs) = let lesser = filter (< x) xs greater = filter(>= x) xs in (quicksort lesser) ++ [x] ++ (quicksort greater)
Give a code snippet in #Idris Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Erlang
Erlang
  -module( first_class_functions ).   -export( [task/0] ).   task() -> As = [fun math:sin/1, fun math:cos/1, fun cube/1], Bs = [fun math:asin/1, fun math:acos/1, fun square_inverse/1], [io:fwrite( "Value: 1.5 Result: ~p~n", [functional_composition([A, B], 1.5)]) || {A, B} <- lists:zip(As, Bs)].       functional_comp...
Give a code snippet in #Erlang A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#Arturo
Arturo
fivenum: function [lst][ lst: sort lst m: (size lst)/2 lowerEnd: (odd? size lst)? -> m -> m-1   return @[ first lst median slice lst 0 lowerEnd median slice lst 0 dec size lst median slice lst m dec size lst last lst ] ]   lists: @[ @[15.0, 6.0, 42.0, 41.0...
Give a code snippet in #Arturo Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local...
#Elixir
Elixir
defmodule Echo.Server do def start(port) do tcp_options = [:binary, {:packet, 0}, {:active, false}] {:ok, socket} = :gen_tcp.listen(port, tcp_options) listen(socket) end defp listen(socket) do {:ok, conn} = :gen_tcp.accept(socket) spawn(fn -> recv(conn) end) listen(socket) end defp r...
Give a code snippet in #Elixir Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary t...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#J
J
require 'files strings'   notes=: monad define if. #y do. now=. LF ,~ 6!:0 'hh:mm:ss DD/MM/YYYY' 'notes.txt' fappend~ now, LF ,~ TAB, ' ' joinstring y elseif. -. _1 -: txt=. fread 'notes.txt' do. smoutput txt end. )   notes 2}.ARGV exit 0
Give a code snippet in #J Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT fol...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#R
R
?RNG help.search("Distribution", package="stats")
Give a code snippet in #R The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm us...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Racket
Racket
#lang racket (require racket/stream) (define first stream-first) (define rest stream-rest)   (define (merge s1 s2) (define x1 (first s1)) (define x2 (first s2)) (cond [(= x1 x2) (merge s1 (rest s2))] [(< x1 x2) (stream-cons x1 (merge (rest s1) s2))] [else (stream-cons x2 (merge s1 (rest s2))...
Give a code snippet in #Racket Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming num...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Nim
Nim
import gintro/[glib, gobject, gtk, gio, cairo]   const Width = 640 Height = 480   #---------------------------------------------------------------------------------------------------   proc draw(area: DrawingArea; context: Context) = ## Draw the greyscale bars.   const Black = 0.0 White = 1.0   var y ...
Give a code snippet in #Nim The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we hav...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#Ada
Ada
with Ada.Text_IO;   procedure Digits_Squaring is   function Is_89 (Number : in Positive) return Boolean is Squares : constant array (0 .. 9) of Natural := (0, 1, 4, 9, 16, 25, 36, 49, 64, 81);   Sum : Natural := Number; Acc : Natural; begin loop Acc := Sum; Su...
Give a code snippet in #Ada If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambd...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#Ruby
Ruby
class Card # class constants SUITS = %i[ Clubs Hearts Spades Diamonds ] PIPS = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ]   # class variables (private) @@suit_value = Hash[ SUITS.each_with_index.to_a ] @@pip_value = Hash[ PIPS.each_with_index.to_a ]   attr_reader :pip, :suit   def initialize(pip,sui...
Give a code snippet in #Ruby Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current co...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#BASIC
BASIC
RANDOMIZE TIMER 'seeds random number generator with the system time pi = 3.141592653589793# DIM a(1 TO 1000) AS DOUBLE CLS FOR i = 1 TO 1000 a(i) = 1 + SQR(-2 * LOG(RND)) * COS(2 * pi * RND) NEXT i
Give a code snippet in #BASIC Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related...
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 ...
#Clojure
Clojure
  (doseq [[k v] {:a 1, :b 2, :c 3}] (println k "=" v))   (doseq [k (keys {:a 1, :b 2, :c 3})] (println k))   (doseq [v (vals {:a 1, :b 2, :c 3})] (println v))  
Give a code snippet in #Clojure 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#Smalltalk
Smalltalk
|top input vh incButton rndButton|   vh := ValueHolder with:0.   top := StandardSystemView label:'Rosetta GUI interaction'. top extent:300@100. top add:((Label label:'Value:') origin: 0 @ 10 corner: 100 @ 40). top add:(input := EditField origin: 102 @ 10 corner: 1.0 @ 40). input model:(TypeConverter onNumberValue:vh). ...
Give a code snippet in #Smalltalk Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and che...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#PL.2FI
PL/I
/* From Rosetta Fortran */ test: procedure options (main);   declare i fixed binary;   on underflow ;   put skip list ('Lanczos', 'Builtin' ); do i = 1 to 10; put skip list (lanczos_gamma(i/3.0q0), gamma(i/3.0q0) ); end;     lanczos_gamma: procedure (a) returns (float (18)) recursive; declare a float...
Give a code snippet in #PL.2FI Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/li...
christopher/rosetta-code
http://rosettacode.org/wiki/Object_serialization
Object serialization
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o...
#EchoLisp
EchoLisp
  (define (person->string self) (format "%a : person." (person-name self))) (define (writer->string self) (format "%a: writer of %a." (person-name self) (writer-books self))) (define (father->string self) (format "%a: father of %a." (person-name self) (map person-name (father-children self))))   ; 'clas...
Give a code snippet in #EchoLisp Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write eac...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#FunL
FunL
def mersenne( p ) = if p == 2 then return true   var s = 4 var M = 2^p - 1   repeat p - 2 s = (s*s - 2) mod M   s == 0   import integers.primes   for p <- primes().filter( mersenne ).take( 20 ) println( 'M' + p )
Give a code snippet in #FunL Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#BBC_BASIC
BBC BASIC
SYS "SystemFunction036", ^random%, 4 PRINT ~random%
Give a code snippet in #BBC_BASIC Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Cowgol
Cowgol
include "cowgol.coh";   sub countSubstring(str: [uint8], match: [uint8]): (count: uint8) is count := 0;   while [str] != 0 loop var find := match; var loc := str; while [loc] == [find] loop find := @next find; loc := @next loc; end loop; if [find] ...
Give a code snippet in #Cowgol Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#PureBasic
PureBasic
Structure point_f x.f y.f EndStructure   Procedure isInside(*p.point_f, *cp1.point_f, *cp2.point_f) If (*cp2\x - *cp1\x) * (*p\y - *cp1\y) > (*cp2\y - *cp1\y) * (*p\x - *cp1\x) ProcedureReturn 1 EndIf EndProcedure   Procedure intersection(*cp1.point_f, *cp2.point_f, *s.point_f, *e.point_f, *newPoint.poin...
Give a code snippet in #PureBasic The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#PicoLisp
PicoLisp
(load "@lib/math.l")   (for N (range 2 10) (let Angle 0.0 (prin N ": ") (for I N (let Ipart (sin Angle) (prin (round (cos Angle) 4) (if (lt0 Ipart) "-" "+") "j" (round (abs Ipart) 4) " " ) ) (inc 'An...
Give a code snippet in #PicoLisp The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Nim
Nim
import times, strutils   proc doWork(x: int) = var n = x for i in 0..10000000: n += i   template time(statement: untyped): float = let t0 = cpuTime() statement cpuTime() - t0   echo "Time = ", time(doWork(100)).formatFloat(ffDecimal, precision = 3), " s"
Give a code snippet in #Nim Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between s...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#FreeBASIC
FreeBASIC
DIM C AS STRING = "Hello World! ", SIZE AS USHORT = LEN(C) DIM DIRECTION AS BYTE = 0 DIM AS INTEGER X, Y, BTNS DIM HELD AS BYTE = 0   SCREEN 19   DO LOCATE 1, 1 PRINT C   GETMOUSE X, Y, , BTNS   IF BTNS <> 0 AND HELD = 0 THEN 'remember if it was pressed, to not react every frame HELD = 1 IF X >= 0 AND X < SIZ...
Give a code snippet in #FreeBASIC Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Pascal
Pascal
#!/usr/bin/perl do "include.pl"; # Utilize source from another file sayhello();
Give a code snippet in #Pascal Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. 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 Bioin...
#Nim
Nim
import strformat   for i in 0..15: for j in countup(32 + i, 127, step = 16): let k = case j of 32: "Spc" of 127: "Del" else: $chr(j) write(stdout, fmt"{j:3d} : {k:<6s}") write(stdout, "\n")
Give a code snippet in #Nim Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. 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 b...
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...
#Clojure
Clojure
(doseq [x (range 10 -1 -1)] (println x))
Give a code snippet in #Clojure 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/Incr...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#PL.2FI
PL/I
is_prime: procedure (n) returns (bit(1)); declare n fixed (15); declare i fixed (10);   if n < 2 then return ('0'b); if n = 2 then return ('1'b); if mod(n, 2) = 0 then return ('0'b);   do i = 3 to sqrt(n) by 2; if mod(n, i) = 0 then return ('0'b); end; return ('1'b); end is_prime;
Give a code snippet in #PL.2FI Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loop...
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 ...
#Arturo
Arturo
wordset: map read.lines relative "unixdict.txt" => strip   anagrams: #[]   loop wordset 'word [ anagram: sort to [:char] word unless key? anagrams anagram -> anagrams\[anagram]: new []   anagrams\[anagram]: anagrams\[anagram] ++ word ]   loop select values anagrams 'x [5 =< size x] 'words -> pri...
Give a code snippet in #Arturo 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/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 ...
#zkl
zkl
a:=L(4,5,2,6); a.sort(); a.println() //--> L(2,4,5,6)
Give a code snippet in #zkl 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/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#Visual_Basic
Visual Basic
Option Explicit Dim seed As Long Sub Main() Dim i As Integer seed = 675248 For i = 1 To 5 Debug.Print Rand Next i End Sub Function Rand() As Variant Dim s As String s = CStr(seed ^ 2) Do While Len(s) <> 12 s = "0" + s Loop seed = Val(Mid(s, 4, 6)) Rand = seed End ...
Give a code snippet in #Visual_Basic Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Lua
Lua
print( tonumber("123") ) print( tonumber("a5b0", 16) ) print( tonumber("011101", 2) ) print( tonumber("za3r", 36) )
Give a code snippet in #Lua It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of su...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#REXX
REXX
/*REXX program calculates Carmichael 3─strong pseudoprimes (up to and including N). */ numeric digits 18 /*handle big dig #s (9 is the default).*/ parse arg N .; if N=='' | N=="," then N=61 /*allow user to specify for the search.*/ tell= N>0; N= abs(N) ...
Give a code snippet in #REXX A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to invest...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Standard_ML
Standard ML
fun mean_reals [] = 0.0 | mean_reals xs = foldl op+ 0.0 xs / real (length xs);   val mean_ints = mean_reals o (map real);
Give a code snippet in #Standard_ML Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has a...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_convolution
Image convolution
One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine...
#J
J
NB. pad the edges of an array with border pixels NB. (increasing the first two dimensions by 1 less than the kernel size) pad=: adverb define 'a b'=. (<. ,. >.) 0.5 0.5 p. $m a"_`(0 , ] - 1:)`(# 1:)}~&# # b"_`(0 , ] - 1:)`(# 1:)}~&(1 { $) #"1 ] )   kernel_filter=: adverb define ($m)+/ .*&(,m)&(,/);._3 m pad )
Give a code snippet in #J One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#Ruby
Ruby
def stream_merge(*files) fio = files.map{|fname| open(fname)} merge(fio.map{|io| [io, io.gets]}) end   def merge(fdata) until fdata.empty? io, min = fdata.min_by{|_,data| data} puts min if (next_data = io.gets).nil? io.close fdata.delete([io, min]) else i = fdata.index{|x,_| x ==...
Give a code snippet in #Ruby 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which ...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#D
D
import std.stdio, std.array, std.algorithm, std.bigint, std.range;   immutable tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; immutable small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "el...
Give a code snippet in #D Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive...
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 ...
#LFE
LFE
(defun dot-product (a b) (: lists foldl #'+/2 0 (: lists zipwith #'*/2 a b)))  
Give a code snippet in #LFE Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] ...
christopher/rosetta-code
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. 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 Burrows–Wheeler transform (BWT, also called block-s...
#Swift
Swift
import Foundation   private let stx = "\u{2}" private let etx = "\u{3}"   func bwt(_ str: String) -> String? { guard !str.contains(stx), !str.contains(etx) else { return nil }   let ss = stx + str + etx let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted()   return String(table.map...
Give a code snippet in #Swift This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. 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 Burrows–Wheeler tran...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Vlang
Vlang
import os   fn main() { contents := os.ls('.')? println(contents) }
Give a code snippet in #Vlang Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Atari_BASIC
Atari BASIC
100 REM RPG character generator 110 DIM AT(5) 120 DIM AT$(18) 130 AT$="StrDexConIntWisCha" 140 PT=0:SA=0 150 PRINT CHR$(125);CHR$(29);CHR$(31);"Rolling..." 160 FOR AI=0 TO 5 170 DT=0:MI=6:REM dice total, min die 180 FOR I=0 TO 3 190 D=INT(RND(1)*6)+1 200 DT=DT+D 210 IF D<MI THEN MI=D 220 NEXT I 230 DT=DT-MI 240 AT(AI)=...
Give a code snippet in #Atari_BASIC RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#LiveCode
LiveCode
command loopArrays local lowA, uppA, nums, z put "a,b,c" into lowA put "A,B,C" into uppA put "1,2,3" into nums   split lowA by comma split uppA by comma split nums by comma   repeat with n = 1 to the number of elements of lowA put lowA[n] & uppA[n] & nums[n] & return after z ...
Give a code snippet in #LiveCode Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this e...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#ALGOL_68
ALGOL 68
# operator to turn two boolean values into an integer - name inspired by the COBOL sample # PRIO ALSO = 1; OP ALSO = ( BOOL a, b )INT: IF a AND b THEN 1 ELIF a THEN 2 ELIF b THEN 3 ELSE 4 FI;   # using the above operator, we can use the standard CASE construct to provide the # # required construct, e.g.: ...
Give a code snippet in #ALGOL_68 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e...
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 ≤...
#Agena
Agena
scope local f := trim( io.read() ) split " "; # read a line and split into fields local a := tonumber( f[ 1 ] ); local b := tonumber( f[ 2 ] ); print( a + b ) epocs
Give a code snippet in #Agena 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/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#LSL
LSL
default { state_entry() { llListen(PUBLIC_CHANNEL, "", llGetOwner(), ""); llOwnerSay("Please Enter a Dimension for an Identity Matrix."); } listen(integer iChannel, string sName, key kId, string sMessage) { llOwnerSay("You entered "+sMessage+"."); list lMatrix = []; integer x = 0; integer n = (integer)sM...
Give a code snippet in #LSL Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#Factor
Factor
USING: arrays assocs combinators command-line continuations io kernel math math.parser multiline namespaces peg.ebnf prettyprint random sequences ; FROM: sets => without ; IN: rosetta-code.password-generator   STRING: usage password-generator generates random passwords.   Commands: -l [int>=4] Set password length ...
Give a code snippet in #Factor Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-....
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake 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 ...
#11l
11l
V tutor = 1B   F pancakesort(&data) I data.len <= 1 R I :tutor print() L(size) (data.len .< 1).step(-1) V maxindex = max(0 .< size, key' x -> @data[x]) I maxindex + 1 != size I maxindex != 0 I :tutor print(‘With: #. doflip #.’.format(data.map(x -> St...
Give a code snippet in #11l 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/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#PowerShell
PowerShell
$data = @(1,1,1,2,3,4,5,5,6,7,7,7) $groups = $data | group-object | sort-object count -Descending $groups | ? {$_.Count -eq $groups[0].Count}
Give a code snippet in #PowerShell Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#REXX
REXX
/*REXX program writes a PPM formatted image file, also known as a P6 (binary) file. */ green = 00ff00 /*define a pixel with the color green. */ parse arg oFN width height color . /*obtain optional arguments from the CL*/ if oFN=='' | oFN=="," then oFN='IMAGE...
Give a code snippet in #REXX Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
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...
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Utility.NString; // contains method Concat()   module Stringcat { Main() : void { def text1 = "This string has"; def cat1 = Concat( " ", [text, "been concatenated"]); def cat2 = text1 + " also been concatenated"; Write($"$cat1\n...
Give a code snippet in #Nemerle 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 l...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#Prolog
Prolog
dialog('GUI_Interaction', [ object := GUI_Interaction, parts := [ GUI_Interaction := dialog('Rosetta Code'), Name := label(name, 'Value :'), Input_field := text_item(input_field, '0'), Increment := button(increment), Decremen...
Give a code snippet in #Prolog In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI comp...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Fortran
Fortran
program game_24 implicit none real :: vector(4), reals(11), result, a, b, c, d integer :: numbers(4), ascii(11), i character(len=11) :: expression character :: syntax(11) ! patterns: character, parameter :: one(11) = (/ '(','(','1','x','1',')','x','1',')','x','1' /) ...
Give a code snippet in #Fortran The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#C.23
C#
public static void Sort<T>(List<T> list) where T : IComparable { if (list.Count > 1) { StoogeSort(list, 0, list.Count - 1); } } private static void StoogeSort<T>(List<T> L, int i, int j) where T : IComparable { if (L[j].CompareTo(L[i])<0) { T tmp = L[i]; ...
Give a code snippet in #C.23 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/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Wart
Wart
def (queue seq) (tag queue (list seq lastcons.seq len.seq))   def (enq x q) do1 x let (l last len) rep.q rep.q.2 <- (len + 1) if no.l rep.q.1 <- (rep.q.0 <- list.x) rep.q.1 <- (cdr.last <- list.x)   def (deq q) let (l last len) rep.q ret ans car.l unless zero?.len ...
Give a code snippet in #Wart 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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the or...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Delphi
Delphi
program ProgramName;   {$APPTYPE CONSOLE}   begin Writeln('Program name: ' + ParamStr(0)); Writeln('Command line: ' + CmdLine); end.
Give a code snippet in #Delphi The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#C.2B.2B
C++
  #include <windows.h> #include <iostream>   //-------------------------------------------------------------------------------------------------- using namespace std;     //-------------------------------------------------------------------------------------------------- class calender { public: void drawCalender( ...
Give a code snippet in #C.2B.2B Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#C.23
C#
using System; using System.Linq;   namespace PerniciousNumbers { class Program { public static int PopulationCount(long n) { int cnt = 0; do { if ((n & 1) != 0) { cnt++; } } while...
Give a code snippet in #C.23 A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#Elixir
Elixir
defmodule Means do def arithmetic(list) do Enum.sum(list) / length(list) end def geometric(list) do  :math.pow(Enum.reduce(list, &(*/2)), 1 / length(list)) end def harmonic(list) do 1 / arithmetic(Enum.map(list, &(1 / &1))) end end   list = Enum.to_list(1..10) IO.puts "Arithmetic mean: #{am = ...
Give a code snippet in #Elixir Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ld...
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 ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Swap(Of T)(ByRef a As T, ByRef b As T) Dim c = a a = b b = c End Sub   Sub Sort(Of T As IComparable(Of T))(ByRef a As T, ByRef b As T, ByRef c As T) If a.CompareTo(b) > 0 Then Swap(a, b) End If If a.CompareTo(c) > 0 Then ...
Give a code snippet in #Visual_Basic_.NET 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/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Forth
Forth
0 enum baker \ enumeration of all tenants enum cooper enum fletcher enum miller constant smith   create names \ names of all the tenants ," Baker" ," Cooper" ," Fletcher" ," Miller" ," Smith" \ get name, type it does> s...
Give a code snippet in #Forth Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are a...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#R
R
x <- c(0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,-0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578)   fivenum(x)
Give a code snippet in #R Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algor...
#Sidef
Sidef
func comb_sort(arr) { var gap = arr.len; var swaps = true; while (gap > 1 || swaps) { gap.div!(1.25).int! if (gap > 1); swaps = false; for i in ^(arr.len - gap) { if (arr[i] > arr[i+gap]) { arr[i, i+gap] = arr[i+gap, i]; swaps = true; ...
Give a code snippet in #Sidef Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare s...
christopher/rosetta-code
http://rosettacode.org/wiki/Motzkin_numbers
Motzkin numbers
Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numbers or, if your language does not...
#Yabasic
Yabasic
dim M(41) M(0) = 1 : M(1) = 1 print str$(M(0), "%19g") print str$(M(1), "%19g") for n = 2 to 41 M(n) = M(n-1) for i = 0 to n-2 M(n) = M(n) + M(i)*M(n-2-i) next i print str$(M(n), "%19.0f"), if isPrime(M(n)) then print "is a prime" else print : fi next n end   sub isPrime(v) if v < 2 then...
Give a code snippet in #Yabasic Definition The nth Motzkin number (denoted by M[n]) is the number of different ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). By convention M[0] = 1. Task Compute and show on this page the first 42 Motzkin numb...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Factor
Factor
"input.txt" binary file-contents "output.txt" binary set-file-contents
Give a code snippet in #Factor File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file ...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#Wren
Wren
import "/dynamic" for Tuple   var Solution = Tuple.create("Solution", ["p", "tests", "swaps"])   // Holes A=0, B=1, …, H=7 // With connections: var conn = " A B /|\\ /|\\ / | X | \\ / |/ \\| \\ C - D - E - F \\ |\\ /| / \\ | X | / \\|/ \\|/ G H "   var connections ...
Give a code snippet in #Wren You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ ...
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...
#Raku
Raku
class EarthPoint { has $.lat; # latitude has $.lon; # longitude   has $earth_radius = 6371; # mean earth radius has $radian_ratio = pi / 180;   # accessors for radians method latR { $.lat * $radian_ratio } method lonR { $.lon * $radian_ratio }   method hav...
Give a code snippet in #Raku 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 equat...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#REXX
REXX
/* Simple ARexx program to open a port after checking if it's already open */ IF Show('PORTS','ROSETTA') THEN DO /* Port is already open; exit */ SAY 'This program may only be run in a single instance at a time.' EXIT 5 /* Exit with a mild warning */ END ...
Give a code snippet in #REXX This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#C
C
/* ===> INCLUDES <============================================================*/ #include <stdlib.h> #include <stdio.h> #include <string.h>   /* ===> CONSTANTS <===========================================================*/ #define N_DECKS 7 const int kDecks[N_DECKS] = { 8, 24, 52, 100, 1020, 1024, 10000 };   /* ===> FU...
Give a code snippet in #C A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠...
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 ...
#FreeBASIC
FreeBASIC
  ' FB 1.05.0 Win64   Function QuadraticMean(array() As Double) As Double Dim length As Integer = Ubound(array) - Lbound(array) + 1 Dim As Double sum = 0.0 For i As Integer = LBound(array) To UBound(array) sum += array(i) * array(i) Next Return Sqr(sum/length) End Function   Dim vector(1 To 10) As Double ...
Give a code snippet in #FreeBASIC 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 ...
christopher/rosetta-code