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/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Cixl
Cixl
  use: cx;   'data.txt' `r fopen lines { let: (time place mag) @@s split ..; let: (m1 m2) $mag @. split &int map ..; $m1 6 >= $m2 0 > and {[$time @@s $place @@s $mag] say} if } for  
Give a code snippet in #Cixl Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines f...
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:...
#Stata
Stata
. dir *.dta 6.3k 6/12/17 14:26 auto.dta 2.3k 8/10/17 7:34 titanium.dta 6.0k 8/12/17 9:28 trend.dta
Give a code snippet in #Stata 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/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Haxe
Haxe
static function fib(steps:Int, handler:Int->Void) { var current = 0; var next = 1;   for (i in 1...steps) { handler(current);   var temp = current + next; current = next; next = temp; } handler(current); }
Give a code snippet in #Haxe The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Oforth
Oforth
: stripComments(s, markers) | firstMarker | markers map(#[ s indexOf ]) reduce(#min) ->firstMarker s firstMarker ifNotNull: [ left(firstMarker 1 - ) ] strip ;
Give a code snippet in #Oforth Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Natural_sorting
Natural sorting
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Racket
Racket
  #lang racket (define (natural-sort l) (define (list<? l1 l2) (cond [(null? l2) #f] [(null? l1) #t] [(number? (car l1)) (cond [(< (car l1) (car l2)) #t] [(< (car l2) (car l1)) #f] [else (list<? (cdr l1) (cdr l2))])] ...
Give a code snippet in #Racket Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Rust
Rust
  fn is_narcissistic(x: u32) -> bool { let digits: Vec<u32> = x .to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .collect();   digits .iter() .map(|d| d.pow(digits.len() as u32)) .sum::<u32>() == x }   fn main() { let mut counter = 0; ...
Give a code snippet in #Rust 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/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#F.23
F#
let fizzbuzz n = match n%3 = 0, n%5 = 0 with | true, false -> "fizz" | false, true -> "buzz" | true, true -> "fizzbuzz" | _ -> string n   let printFizzbuzz() = [1..100] |> List.iter (fizzbuzz >> printfn "%s")
Give a code snippet in #F.23 Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz ...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Delphi
Delphi
  unit Colour_barsDisplay;   interface   uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms;   type TfmColourBar = class(TForm) procedure FormPaint(Sender: TObject); procedure FormResize(Sender: TObject); private { Private declarations } public { Public declarations }...
Give a code snippet in #Delphi Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Delphi
Delphi
program TestSelectionSort;   {$APPTYPE CONSOLE}   {.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array   type TItem = Integer; // declare ordinal type for array item {$IFDEF DYNARRAY} TArray = array of TItem; // dynamic array {$ELSE} TArray = array[0..15] of TItem; // static array {$ENDIF...
Give a code snippet in #Delphi Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Modula-2
Modula-2
MODULE ADP; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE ProperDivisorSum(n : INTEGER) : INTEGER; VAR i,sum : INTEGER; BEGIN sum := 0; IF n<2 THEN RETURN 0 END; FOR i:=1 TO (n DIV 2) DO IF n MOD i = 0 THEN INC(sum,i) ...
Give a code snippet in #Modula-2 These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as defici...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Swift
Swift
func binarySearch<T: Comparable>(xs: [T], x: T) -> Int? { var recurse: ((Int, Int) -> Int?)! recurse = {(low, high) in switch (low + high) / 2 { case _ where high < low: return nil case let mid where xs[mid] > x: return recurse(low, mid - 1) case let mid where xs[mid] < x: return recurse(mid + 1, high) ...
Give a code snippet in #Swift A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret n...
christopher/rosetta-code
http://rosettacode.org/wiki/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) A:=GSL.Matrix(3,3).set(12.0, -51.0, 4.0, 6.0, 167.0, -68.0, 4.0, 24.0, -41.0); Q,R:=A.QRDecomp(); println("Q:\n",Q.format()); println("R:\n",R.format()); println("Q*R:\n",(Q*R).format());
Give a code snippet in #zkl Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , a...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Crystal
Crystal
n = rand(1..10) puts "Guess the number: 1..10" until gets.to_s.to_i == n; puts "Wrong! Guess again: " end puts "Well guessed!"
Give a code snippet in #Crystal Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Clarion
Clarion
  program   map end   MAX_DOOR_NUMBER equate(100) CRLF equate('<13,10>')   Doors byte,dim(MAX_DOOR_NUMBER) Pass byte DoorNumber byte DisplayString cstring(2000)   ResultWindow window('Result'),at(,,133,291),cen...
Give a code snippet in #Clarion There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Ada
Ada
type Lower_Case is new Character range 'a' .. 'z';
Give a code snippet in #Ada Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a re...
christopher/rosetta-code
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then outp...
#Ring
Ring
  # Project : Eertree   str = "eertree" pal = [] for n=1 to len(str) for m=1 to len(str) strrev = "" strpal = substr(str, n, m) if strpal != "" for p=len(strpal) to 1 step -1 strrev = strrev + strpal[p] next if strpal = strrev ad...
Give a code snippet in #Ring An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for t...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Oforth
Oforth
  'ALLOCATING MEMORY FROM DIFFERENT MEMORY SOURCES   sys p     static byte b[0x1000] 'global memory p=@b     function f() local byte b[0x1000] 'stack memory in a procedure p=@b end function     p=getmemory 0x1000 'heap memory ... freememory p 'to disallocate     sub rsp,0x1000 'stack memory direct p=rsp ... rsp=p ...
Give a code snippet in #Oforth Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#ALGOL_68
ALGOL 68
BEGIN # returns s parsed according to delimiter and escape # PROC parse with escapes = ( STRING s, CHAR delimiter, escape )[]STRING: IF ( UPB s - LWB s ) + 1 < 1 THEN # empty string # [ 1 : 0 ]STRING empty a...
Give a code snippet in #ALGOL_68 Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for s...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#D
D
void main() { import std.stdio, std.algorithm, std.range, std.string;   string[] result; size_t maxLen;   foreach (string word; "unixdict.txt".File.lines) { word = word.chomp; immutable len = word.walkLength; if (len < maxLen || !word.isSorted) continue; if (l...
Give a code snippet in #D An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally as...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#PicoLisp
PicoLisp
(DE CAL (YEAR) (PRINL "====== " YEAR " ======") (FOR DAT (RANGE (DATE YEAR 1 1) (DATE YEAR 12 31)) (LET D (DATE DAT) (TAB (3 3 4 8) (WHEN (= 1 (CADDR D)) (GET `(INTERN (PACK (MAPCAR CHAR (42 77 111 110)))) (CADR D)) ) (CADDR D) (DAY DAT `(INTERN (P...
Give a code snippet in #PicoLisp Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Maxima
Maxima
s: ""$   /* check using string contents */ sequal(s, ""); not sequal(s, "");   /* check using string length */ slength(s) = ""; slength(s) # "";
Give a code snippet in #Maxima Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Delphi
Delphi
  program Guess_the_number;   {$APPTYPE CONSOLE}   uses System.SysUtils, system.console;   type TCharSet = set of char;   var PlayerNumber, CPUNumber: word; CPULow: word = 0; CPUHi: word = 1000; PlayerLow: word = 0; PlayerHi: word = 1000; CPUWin, PlayerWin: boolean; CPUGuessList: string = 'Previus g...
Give a code snippet in #Delphi Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <iostream>   const int BMP_SIZE = 600;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create...
Give a code snippet in #C.2B.2B The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Crystal
Crystal
@[Link("c")] # name of library that is passed to linker. Not needed as libc is linked by stdlib. lib LibC fun free(ptr : Void*) : Void fun strdup(ptr : Char*) : Char* end   s1 = "Hello World!" p = LibC.strdup(s1) # returns Char* allocated by LibC s2 = String.new(p) LibC.free p # pointer can be freed as String.new(...
Give a code snippet in #Crystal Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content ca...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Java
Java
--raw-input | -R :: each line of input is converted to a JSON string; --ascii-output | -a :: every non-ASCII character that would otherwise be sent to output is translated to an equivalent ASCII escape sequence; --raw-output | -r :: output strings as raw strings, ...
Give a code snippet in #Java As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#PowerShell
PowerShell
  function Expand-Braces ( [string]$String ) { $Escaped = $False $Stack = New-Object System.Collections.Stack $ClosedBraces = $BracesToParse = $Null   ForEach ( $i in 0..($String.Length-1) ) { Switch ( $String[$i] ) { '\' { $Escaped = -not $Esc...
Give a code snippet in #PowerShell Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hanoi[0, from_, to_, via_] := Null Hanoi[n_Integer, from_, to_, via_] := (Hanoi[n-1, from, via, to];Print["Move disk from pole ", from, " to ", to, "."];Hanoi[n-1, via, to, from])
Give a code snippet in #Mathematica.2FWolfram_Language Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Forth
Forth
: largest-proper-divisor { n -- n } n 1 and 0= if n 2/ exit then 3 begin dup dup * n <= while dup n swap /mod swap 0= if nip exit else drop then 2 + repeat drop 1 ;   : main 101 1 do i largest-proper-divisor 2 .r i 10 mod 0= if cr else space then loop ;   main bye
Give a code snippet in #Forth Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#F.23
F#
  // Tau number. Nigel Galloway: March 9th., 2021 Seq.initInfinite((+)1)|>Seq.filter(fun n->n%(tau n)=0)|>Seq.take 100|>Seq.iter(printf "%d "); printfn ""  
Give a code snippet in #F.23 A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function ...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#RPG
RPG
**FREE Ctl-opt MAIN(Main); Ctl-opt DFTACTGRP(*NO) ACTGRP(*NEW);   dcl-pr QDCXLATE EXTPGM('QDCXLATE'); dataLen packed(5 : 0) CONST; data char(32767) options(*VARSIZE); conversionTable char(10) CONST; end-pr;   dcl-pr Qc3CalculateHash EXTPROC('Qc3CalculateHash'); inputData pointer v...
Give a code snippet in #RPG Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#Fortran
Fortran
PROGRAM NONSQUARES   IMPLICIT NONE   INTEGER :: m, n, nonsqr   DO n = 1, 22 nonsqr = n + FLOOR(0.5 + SQRT(REAL(n))) ! or could use NINT(SQRT(REAL(n))) WRITE(*,*) nonsqr END DO   DO n = 1, 1000000 nonsqr = n + FLOOR(0.5 + SQRT(REAL(n))) m = INT(SQRT(REAL(nonsqr))) IF (m*m == nonsqr) THEN...
Give a code snippet in #Fortran Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Slate
Slate
Method traits define: #Y &builder: [[| :f | [| :x | f applyWith: (x applyWith: x)] applyWith: [| :x | f applyWith: (x applyWith: x)]]].
Give a code snippet in #Slate In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a va...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Run_BASIC
Run BASIC
a$ = timeInfo$() print " UTC:";word$(a$,1,"|") print "Date:";word$(a$,2,"|") print "Time:";word$(a$,3,"|") wait function timeInfo$() utc$ = word$(word$(httpget$("http://tycho.usno.navy.mil/cgi-bin/timer.pl"),1,"UTC"),2,"<BR>") ' Universal time d$ = date$() t$ = time$() timeInfo$ = utc$;"|";d$;"|";t$ end function
Give a code snippet in #Run_BASIC Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#FreeBASIC
FreeBASIC
#include "isprime.bas"   function digsum( n as uinteger ) as uinteger dim as uinteger s while n s+=n mod 10 n\=10 wend return s end function   dim as uinteger s   print "Prime","Digit Sum" for i as uinteger = 2 to 499 if isprime(i) then s = digsum(i) if isprime(s) the...
Give a code snippet in #FreeBASIC Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS en...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Bash
Bash
  #!/bin/bash   is_leap_year () # Define function named is_leap_year {   declare -i year=$1 # declare integer variable "year" and set it to function parm 1   echo -n "$year ($2)-> " # print the year passed in, but do not go to the next line   if (( $year % 4 == 0 )) # if year not dividable by 4, then not a leap y...
Give a code snippet in #Bash Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Prolog
Prolog
csv_html :- L = "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!",   c...
Give a code snippet in #Prolog Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task C...
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#Wren
Wren
import "/str" for Str import "/sort" for Sort import "/fmt" for Fmt   var solve = Fn.new { |states| var dict = {} for (state in states) { var key = Str.lower(state).replace(" ", "") if (!dict[key]) dict[key] = state } var keys = dict.keys.toList Sort.quick(keys) var solutions = [...
Give a code snippet in #Wren Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Make
Make
contents=$(shell cat foo) curdir=`pwd`
Give a code snippet in #Make Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#PHP
PHP
<?php function is_palindrome($string) { return $string == strrev($string); } ?>
Give a code snippet in #PHP A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a...
christopher/rosetta-code
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#ALGOL_68
ALGOL 68
BEGIN # find some magnanimous numbers - numbers where inserting a + between any # # digits ab=nd evaluatinf the sum results in a prime in all cases # # returns the first n magnanimous numbers # # uses global sieve prime which must include 0 and be large en...
Give a code snippet in #ALGOL_68 A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prim...
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...
#Lasso
Lasso
loop(-from=10, -to=0, -by=-1) => {^ loop_count + ' ' ^}
Give a code snippet in #Lasso 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/Increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Erlang
Erlang
  -module(bitwise_operations).   -export([test/0]).   test() -> A = 255, B = 170, io:format("~p band ~p = ~p\n",[A,B,A band B]), io:format("~p bor ~p = ~p\n",[A,B,A bor B]), io:format("~p bxor ~p = ~p\n",[A,B,A bxor B]), io:format("not ~p = ~p\n",[A,bnot A]), io:format("~p bsl ~p = ~p\n",[A,B,A bsl...
Give a code snippet in #Erlang Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d ...
#Kotlin
Kotlin
// version 1.1.3   object Perlin {   private val permutation = intArrayOf( 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 20...
Give a code snippet in #Kotlin The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-rando...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#ERRE
ERRE
  .............. INPUT("Enter the time to sleep in seconds: ";sleep) PRINT("Sleeping...") PAUSE(sleep) PRINT("Awake!") ..............  
Give a code snippet in #ERRE Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#JavaScript
JavaScript
<html><head><title>Donuts</title></head> <body><pre id='x'></pre><script type="application/javascript"> function disp(x) { var e = document.createTextNode(x + '\n'); document.getElementById('x').appendChild(e); }   function pick(n, got, pos, from, show) { var cnt = 0; if (got.length == n) { if (show) disp(got.joi...
Give a code snippet in #JavaScript The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each membe...
christopher/rosetta-code
http://rosettacode.org/wiki/Achilles_numbers
Achilles numbers
This page uses content from Wikipedia. The original article was at Achilles number. 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) An Achilles number is a number that is powerful but imperfect. Na...
#Raku
Raku
use Prime::Factor; use Math::Root;   sub is-square-free (Int \n) { constant @p = ^100 .map: { next unless .is-prime; .² }; for @p -> \p { return False if n %% p } True }   sub powerful (\n, \k = 2) { my @p; p(1, 2*k - 1); sub p (\m, \r) { @p.push(m) and return if r < k; for 1 .. ...
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Achilles number. 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) An Achilles number is a number that...
christopher/rosetta-code
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#VBA
VBA
  Public Function timedelta(Optional weeks As Integer = 0, Optional days As Integer = 0, _ Optional hours As Integer = 0, Optional minutes As Integer = 0, Optional seconds As Integer = 0, _ Optional milliseconds As Integer = 0, Optional microseconds As Integer = 0) As Variant End Function Public Sub main() ...
Give a code snippet in #VBA Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on bei...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#ACL2
ACL2
(defun defarray (name size initial-element) (cons name (compress1 name (cons (list :HEADER :DIMENSIONS (list size) :MAXIMUM-LENGTH (1+ size) :DEFAULT initial-element ...
Give a code snippet in #ACL2 A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret nu...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Crystal
Crystal
require "uri"   puts URI.decode "http%3A%2F%2Ffoo%20bar%2F" puts URI.decode "google.com/search?q=%60Abdu%27l-Bah%C3%A1"
Give a code snippet in #Crystal This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencode...
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#Ruby
Ruby
TABLE = [ [0,3,1,7,5,9,8,6,4,2], [7,0,9,2,1,5,4,8,6,3], [4,2,0,6,8,7,1,3,5,9], [1,7,5,0,9,8,3,4,2,6], [6,1,2,3,0,4,5,9,7,8], [3,6,7,4,2,0,9,5,8,1], [5,8,6,9,7,2,0,1,3,4], [8,9,4,5,3,6,2,0,1,7], [9,4,3,8,6,1,7,2,0,5], [2,5,8,1,4,3,6,7,9,0] ]   def damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| ...
Give a code snippet in #Ruby The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#LOLCODE
LOLCODE
HAI 1.3   I HAS A object ITZ A BUKKIT I HAS A name, I HAS A value   IM IN YR interface VISIBLE "R U WANTIN 2 (A)DD A VAR OR (P)RINT 1? "! I HAS A option, GIMMEH option   option, WTF? OMG "A" VISIBLE "NAME: "!, GIMMEH name VISIBLE "VALUE: "!, GIMMEH value object HAS A SRS name ITZ...
Give a code snippet in #LOLCODE Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Meta...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#Lua
Lua
#!/usr/bin/lua   local list1 = [[ Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOW...
Give a code snippet in #Lua This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlica...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#Raku
Raku
my %prec = '^' => 4, '*' => 3, '/' => 3, '+' => 2, '-' => 2, '(' => 1;   my %assoc = '^' => 'right', '*' => 'left', '/' => 'left', '+' => 'left', '-' => 'left';   sub shunting-yard ($prog) { my @inp = $prog.words; my @ops; my @res;   sub report($op) { printf "...
Give a code snippet in #Raku Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens represent...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Julia
Julia
using Primes   function factors(n) f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end return length(f) == 1 ? [one(n), n] : sort!(f) end   const examples = [28, 45, 53, 64, 6435789435768]   for n in examples @time println("The factors of $n are: $(factors(...
Give a code snippet in #Julia Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRED BY "prelude_permutations.a68" MODE PERMDATA = ~; PROVIDES: # PERMDATA*=~* # # perm*=~ list* # END COMMENT   MODE PERMDATALIST = REF[]PERMDATA; MODE PERMDATALISTYIELD = PROC(PERMDATALIST)VOID;   # Generate permutations of the input data list of data list # PROC perm gen per...
Give a code snippet in #ALGOL_68 Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   g...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Octave
Octave
# not a function file: 1; function fun = foo(init) currentSum = init; fun = @(add) currentSum = currentSum + add; currentSum; endfunction   x = foo(1); x(5); foo(3); disp(x(2.3));
Give a code snippet in #Octave A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#JavaScript
JavaScript
(() => { 'use strict';   // populationCount :: Int -> Int const populationCount = n => // The number of non-zero bits in the binary // representation of the integer n. sum(unfoldr( x => 0 < x ? ( Just(Tuple(x % 2)(Math.floor(x / 2))) ) : Nothin...
Give a code snippet in #JavaScript Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, base...
#Erlang
Erlang
  #! /usr/bin/env escript   -compile({no_auto_import,[date/0]}).   main( ["add", Tag | Descriptions] ) -> add( date(), Tag, Descriptions ); main( ["add_date", Date, Tag | Descriptions] ) -> add( date_internal(string:tokens(Date, "-")), Tag, Descriptions ); main( ["print_latest"] ) -> print_latest( contents() ); main( [...
Give a code snippet in #Erlang Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could b...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Maple
Maple
combinat:-permute(3); [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]   combinat:-permute([a,b,c]); [[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]]
Give a code snippet in #Maple Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   gene...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Dart
Dart
  arrLength(arr) { return arr.length; }   main() { var fruits = ['apple', 'orange']; print(arrLength(fruits)); }    
Give a code snippet in #Dart Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter freque...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Elena
Elena
USE: brainf***   "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainf***
Give a code snippet in #Elena Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implem...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Elixir
Elixir
defmodule RC do def is_perfect(1), do: false def is_perfect(n) when n > 1 do Enum.sum(factor(n, 2, [1])) == n end   defp factor(n, i, factors) when n < i*i , do: factors defp factor(n, i, factors) when n == i*i , do: [i | factors] defp factor(n, i, factors) when rem(n,i)==0, do: factor(n, i+1, [i, ...
Give a code snippet in #Elixir Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itsel...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Delphi
Delphi
uses SysUtils, StrUtils;   function IsPalindrome(const aSrcString: string): Boolean; begin Result := SameText(aSrcString, ReverseString(aSrcString)); end;
Give a code snippet in #Delphi A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Kotlin
Kotlin
// version 1.1   data class Employee(val name: String, var category: String) : Comparable<Employee> { override fun compareTo(other: Employee) = this.name.compareTo(other.name) }   fun main(args: Array<String>) { val employees = arrayOf( Employee("David", "Manager"), Employee("Alice", "Sales"), ...
Give a code snippet in #Kotlin Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Excel
Excel
PASCAL =LAMBDA(n, BINCOEFF(n - 1)( SEQUENCE(1, n, 0, 1) ) )     BINCOEFF =LAMBDA(n, LAMBDA(k, QUOTIENT(FACT(n), FACT(k) * FACT(n - k)) ) )
Give a code snippet in #Excel Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#PowerShell
PowerShell
# Create Event Log object $EventLog=new-object System.Diagnostics.EventLog("Application") #Declare Event Source; must be 'registered' with Windows $EventLog.Source="Application" # It is possible to register a new source (see Note2) # Setup the Event Types; you don't have to use them all, but I'm including all the possi...
Give a code snippet in #PowerShell Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#CLU
CLU
ucase = proc (s: string) returns (string) rslt: array[char] := array[char]$predict(1,string$size(s)) for c: char in string$chars(s) do if c>='a' & c<='z' then c := char$i2c(char$c2i(c) - 32) end array[char]$addh(rslt,c) end return(string$ac2s(rslt)) end ucase   abc...
Give a code snippet in #CLU ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet ...
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...
#Common_Lisp
Common Lisp
  ;; Using the LTK library...   (defun gui-test () "the main window for the input test" (ltk:with-ltk () (ltk:wm-title ltk:*tk* "GUI Test") (ltk:bind ltk:*tk* "<Alt-q>" (lambda (evt) (declare (ignore evt)) (setf ltk:*exit-mainloop* t))) (let* (;; Initializing random generator (*random-...
Give a code snippet in #Common_Lisp 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#BQN
BQN
SumDgt ← +´•Fmt-'0'˙ Niven ← 0=SumDgt|⊢ nivens ← Niven¨⊸/↕1100 ⟨20↑nivens, ⊑(⊢>1000˙)⊸/nivens⟩
Give a code snippet in #BQN The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#C.2B.2B
C++
#include <cmath> #include <iostream> #include <string>   using namespace std;   // Use a struct as the monad struct LoggingMonad { double Value; string Log; };   // Use the >> operator as the bind function auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingM...
Give a code snippet in #C.2B.2B The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application....
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...
#Seed7
Seed7
  $ include "seed7_05.s7i"; include "float.s7i";   var integer: i is 0;   const func float: sum (inout integer: i, in integer: lo, in integer: hi, ref func float: term) is func result var float: sum is 0.0 begin for i range lo to hi do sum +:= term; end for; end func;   const proc: main is...
Give a code snippet in #Seed7 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 ALG...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#ZPL
ZPL
program Life;   config var n : integer = 100;   region BigR = [0 .. n+1, 0 .. n+1]; R = [1 .. n, 1 .. n ];   direction nw = [-1, -1]; north = [-1, 0]; ne = [-1, 1]; west = [ 0, -1]; east = [ 0, 1]; sw = [ 1, -1]; south = [ 1, 0]; se = [ 1, 1];   var TW...
Give a code snippet in #ZPL The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#APL
APL
h←⊥∘⌽
Give a code snippet in #APL A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#ALGOL_W
ALGOL W
begin  % display the character code of "a" (97 in ASCII)  % write( decode( "a" ) );  % display the character corresponding to 97 ("a" in ASCII)  % write( code( 97 ) ); end.
Give a code snippet in #ALGOL_W Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#C.2B.2B
C++
#include <algorithm> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits>   using namespace std;   const double epsilon = numeric_limits<float>().epsilon(); const numeric_limits<double> DOUBLE; const double MIN = DOUBLE.min(); const double MAX = DOUBLE.max();   struct Point { const double x, y; }...
Give a code snippet in #C.2B.2B This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, ch...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#BASIC
BASIC
y = 1 for i = 0 to 100 t = i / 10   if t = int(t) then actual = ((t ^ 2 + 4) ^ 2) / 16 print "y("; int(t); ") = "; left(string(y), 13), "Error = "; left(string(actual - y), 13) end if   k1 = t * sqr(y) k2 = (t + 0.05) * sqr(y + 0.05 * k1) k3 = (t + 0.05) * sqr(y + 0.05 * k2) k4 = (t + 0.10...
Give a code snippet in #BASIC Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This eq...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#Python
Python
import os; if os.listdir(raw_input("directory")): print "not empty" else: print "empty"  
Give a code snippet in #Python Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an e...
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...
#Java
Java
public class CountSubstring { public static int countSubstring(String subStr, String str){ return (str.length() - str.replace(subStr, "").length()) / subStr.length(); }   public static void main(String[] args){ System.out.println(countSubstring("th", "the three truths")); System.out.println(countSubstring("aba...
Give a code snippet in #Java 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. I...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Toka
Toka
needs sdl 800 600 sdl_setup
Give a code snippet in #Toka Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) n := integer(!A) | 3 write("Magic number: ",n*(n*n+1)/2) sq := buildSquare(n) showSquare(sq) end   procedure buildSquare(n) sq := [: |list(n)\n :] r := 0 c := n/2 every i := !(n*n) do { /sq[r+1,c+1] := i nr := (n+r-1)%n nc := (c+1)%n if /...
Give a code snippet in #Icon_and_Unicon A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). T...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only...
#D
D
import std.stdio, std.range, std.file, std.algorithm, std.string;   /// Create all patterns of a row or col that match given runs. auto genRow(in int w, in int[] s) pure nothrow @safe { static int[][] genSeg(in int[][] o, in int sp) pure nothrow @safe { if (o.empty) return [[2].replicate(sp)];  ...
Give a code snippet in #D A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of...
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Nim
Nim
proc print(xs: varargs[string, `$`]) = for x in xs: echo x
Give a code snippet in #Nim Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Rel...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Elixir
Elixir
defmodule RC do def lastFriday(year) do Enum.map(1..12, fn month -> lastday = :calendar.last_day_of_the_month(year, month) daynum = :calendar.day_of_the_week(year, month, lastday) friday = lastday - rem(daynum + 2, 7) {year, month, friday} end) end end   y = String.to_integer(hd(Syst...
Give a code snippet in #Elixir Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 201...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Run_BASIC
Run BASIC
text$ =" <<'FOO' Now is the time for all good mem to come to the aid of their country." print text$
Give a code snippet in #Run_BASIC A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) fol...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Scala
Scala
import org.rosettacode.ArithmeticComplex._ import java.awt.Color   object Mandelbrot { def generate(width:Int =600, height:Int =400)={ val bm=new RgbBitmap(width, height)   val maxIter=1000 val xMin = -2.0 val xMax = 1.0 val yMin = -1.0 val yMax = 1.0   val cx=(xMax-xMin)/...
Give a code snippet in #Scala Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
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...
#Pascal
Pascal
sub A { my $a = 0; $a += $_ for @_; return $a / @_; } sub G { my $p = 1; $p *= $_ for @_; return $p**(1/@_); # power of 1/n == root of n } sub H { my $h = 0; $h += 1/$_ for @_; return @_/$h; } my @ints = (1..10);   my $a = A(@ints); my $g = G(@int...
Give a code snippet in #Pascal 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/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#VBScript
VBScript
Function mtf_encode(s) 'create the array list and populate it with the initial symbol position Set symbol_table = CreateObject("System.Collections.ArrayList") For j = 97 To 122 'a to z in decimal. symbol_table.Add Chr(j) Next output = "" For i = 1 To Len(s) char = Mid(s,i,1) If i = Len(s) Then output = o...
Give a code snippet in #VBScript Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is use...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type IntFunc As Function(As Integer, As Integer) As Integer   Function reduce(a() As Integer, f As IntFunc) As Integer '' if array is empty or function pointer is null, return 0 say If UBound(a) = -1 OrElse f = 0 Then Return 0 Dim result As Integer = a(LBound(a)) For i As Integer = LB...
Give a code snippet in #FreeBASIC Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#ooRexx
ooRexx
.error~lineout("Goodbye, World!")
Give a code snippet in #ooRexx Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Kotlin
Kotlin
// version 1.0.5-2   fun main(args: Array<String>) { val n = (1 + java.util.Random().nextInt(10)).toString() println("Guess which number I've chosen in the range 1 to 10\n") do { print(" Your guess : ") } while (n != readLine()) println("\nWell guessed!") }
Give a code snippet in #Kotlin Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Leonardo_numbers
Leonardo numbers
Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) = L(n-1) + L(n-2) + 1 ...
#Lua
Lua
function leoNums (n, L0, L1, add) local L0, L1, add = L0 or 1, L1 or 1, add or 1 local lNums, nextNum = {L0, L1} while #lNums < n do nextNum = lNums[#lNums] + lNums[#lNums - 1] + add table.insert(lNums, nextNum) end return lNums end   function show (msg, t) print(msg .. ":") for i, x in ipairs(t) ...
Give a code snippet in #Lua Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) = L...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#FreeBASIC
FreeBASIC
' version 28-01-2019 ' compile with: fbc -s console   #Include "string.bi"   Function frmt(num As Double) As String   Dim As String temp = Format(num, "#######.#############") Dim As Integer i = Len(temp) -1   If temp[i] = Asc(".") Then temp[i] = 32 If InStr(temp, ".") = 0 Then Return Right(Spac...
Give a code snippet in #FreeBASIC Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the rang...
christopher/rosetta-code
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Factor
Factor
( scratchpad ) USING: sets sets.private ; ( scratchpad ) { 1 2 3 } { 1 2 4 } sequence/tester count . 2
Give a code snippet in #Factor Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool ...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#OCaml
OCaml
Sys.remove "input.txt";; Sys.remove "/input.txt";;
Give a code snippet in #OCaml Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#ERRE
ERRE
  PROGRAM COMPLEX_ARITH   TYPE COMPLEX=(REAL#,IMAG#)   DIM X:COMPLEX,Y:COMPLEX,Z:COMPLEX   ! ! complex arithmetic routines ! DIM A:COMPLEX,B:COMPLEX,C:COMPLEX   PROCEDURE ADD(A.,B.->C.) C.REAL#=A.REAL#+B.REAL# C.IMAG#=A.IMAG#+B.IMAG# END PROCEDURE   PROCEDURE INV(A.->B.) LOCAL DENOM# DENOM#=A.REAL#^2+A.IM...
Give a code snippet in #ERRE A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Phix
Phix
without js -- (file i/o) procedure check(string name) bool bExists = file_exists(name), bDir = get_file_type(name)=FILETYPE_DIRECTORY string exists = iff(bExists?"exists":"does not exist"), dfs = iff(bExists?iff(bDir?"directory ":"file "):"") printf(1,"%s%s %s.\n",{dfs,name,exists}) end ...
Give a code snippet in #Phix Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with...
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Perl
Perl
use utf8; package ErrVar; use strict;   # helper function, apply f to pairs (a, b) from listX and listY sub zip(&$$) { my ($f, $x, $y) = @_; my $l = $#$x; if ($l < $#$y) { $l = $#$y };   my @out; for (0 .. $l) { local $a = $x->[$_]; local $b = $y->[$_]; push @out, $f->(); } \@out }   use overload '""' => ...
Give a code snippet in #Perl If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   ...
christopher/rosetta-code
http://rosettacode.org/wiki/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: ...
#Lambdatalk
Lambdatalk
  1) loop over 3 sentences of equal length and returning 3 sentences   {def A a b c} -> A {def B A B C} -> B {def C 1 2 3} -> C   {S.map {lambda {:i} {br}{S.get :i {A}} {S.get :i {B}} {S.get :i {C}} } {S.serie 0 {- {S.length {A}} 1}}} -> a A 1 b B 2 c C 3   2) ...
Give a code snippet in #Lambdatalk 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#Shale
Shale
  #!/usr/local/bin/shale   // This is an implementation of the old game called Hunt the Wumpus. // // You can read about it here: https://en.wikipedia.org/wiki/Hunt_the_Wumpus // // Here's a quick summary: // // You are in a maze of 20 rooms, numbered 1 through 20. Each room is connected to // 3 other rooms. There is n...
Give a code snippet in #Shale This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Red
Red
  >> parse s: "apples, pears ; and bananas" [to [any space ";"] remove thru end] == true >> s == "apples, pears"  
Give a code snippet in #Red Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whi...
christopher/rosetta-code