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/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#Python
Python
import re   string = "This is a string"   if re.search('string$', string): print("Ends with string.")   string = re.sub(" a ", " another ", string) print(string)
Give a code snippet in #Python Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#J
J
NB. Dynamically generate convenience functions ('`',,;:^:_1: N=:{.Employees) =:, (_&{"1)`'' ([^:(_ -: ])L:0)"0 _~ i.# E =: {: Employees   NB. Show top six ranked employees in each dept N , (<@:>"1@:|:@:((6 <. #) {. ] \: SALARY)/.~ DEPT) |: <"1&> E
Give a code snippet in #J Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Sala...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest ...
#D
D
ulong[] decompose(ulong n) pure nothrow { typeof(return) result; for (ulong i = 2; n >= i * i; i++) for (; n % i == 0; n /= i) result ~= i; if (n != 1) result ~= n; return result; }   void main() { import std.stdio, std.algorithm, std.parallelism, std.typecons;   immu...
Give a code snippet in #D Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to fin...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Lua
Lua
local seconds = os.clock   local integrator = { new = function(self, fn) return setmetatable({fn=fn,t0=seconds(),v0=0,sum=0,nup=0},self) end, update = function(self) self.t1 = seconds() self.v1 = self.fn(self.t1) self.sum = self.sum + (self.v0 + self.v1) * (self.t1 - self.t0) / 2 self.t0, self...
Give a code snippet in #Lua In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such met...
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Julia
Julia
  using PortAudio, LibSndFile   stream = PortAudioStream("Microphone (USB Microphone)", 1, 0) # 44100 samples/sec buf = read(stream, 441000) save("recorded10sec.wav", buf)  
Give a code snippet in #Julia Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate....
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Wren
Wren
import "io" for File   var lines = File.read("input.txt").replace("\r", "").split("\n") if (lines.count < 7) { System.print("There are only %(lines.count) lines in the file") } else { var line7 = lines[6].trim() if (line7 == "") { System.print("The seventh line is empty") } else { System...
Give a code snippet in #Wren Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. 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 b...
#PHP
PHP
<?php foreach (range(2, 8, 2) as $i) echo "$i, "; echo "who do we appreciate?\n"; ?>
Give a code snippet in #PHP Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Scheme
Scheme
; Return the n'th Bernoulli number.   (define bernoulli (lambda (n) (let ((a (make-vector (1+ n)))) (do ((m 0 (1+ m))) ((> m n)) (vector-set! a m (/ 1 (1+ m))) (do ((j m (1- j))) ((< j 1)) (vector-set! a (1- j) (* j (- (vector-ref a (1- j)) (vector-ref a j))))...
Give a code snippet in #Scheme Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as p...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#PL.2FI
PL/I
  trap: procedure options (main); /* 17 December 2021 */ declare n fixed binary; get (n); put ('The order of the matrix is ' || trim(n)); begin; declare A (n,n) fixed binary; declare sum fixed binary; declare (i, j) fixed binary;   get (A); sum = 0; do i = 2 to n; ...
Give a code snippet in #PL.2FI Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
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...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PROC trim comment = (STRING line, CHAR marker)STRING:( INT index := UPB line+1; char in string(marker, index, line); FOR i FROM index-1 BY -1 TO LWB line WHILE line[i]=" " DO index := i OD; line[:index-1] );   CHAR q = """";   print(( q, trim comment("apples, pears # and b...
Give a code snippet in #ALGOL_68 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/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...
#Robotic
Robotic
  set "index" to 0 set "$array&index&" to "apple" inc "index" by 1 set "$array&index&" to "orange" * "Array length: ('index' + 1)"  
Give a code snippet in #Robotic 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 fre...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Raku
Raku
use NativeCall;   sub crc32(int32 $crc, Buf $buf, int32 $len --> int32) is native('z') { * }   my $buf = 'The quick brown fox jumps over the lazy dog'.encode; say crc32(0, $buf, $buf.bytes).fmt('%08x');
Give a code snippet in #Raku Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#REXX
REXX
  /* REXX */ Call mk_a "It is certain", "It is decidedly so", "Without a doubt",, "Yes, definitely", "You may rely on it", "As I see it, yes",, "Most likely", "Outlook good", "Signs point to yes", "Yes",, "Reply hazy, try again", "Ask again later",, "Better not tell you now", "Ca...
Give a code snippet in #REXX Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformat...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Q
Q
x where 0=x mod 2
Give a code snippet in #Q Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Pop11
Pop11
vars itemrep; incharitem(charin) -> itemrep; ;;; Read sizes vars n1 = itemrep(), n2= itemrep(); ;;; Create 0 based array vars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0); ;;; Set element value 15 -> ar(0, 0); ;;; Print element value ar(0,0) => ;;; Make sure array is unreferenced 0 -> ar;
Give a code snippet in #Pop11 Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Wren
Wren
import "dome" for Window import "graphics" for Canvas, Color import "random" for Random   class Game { static init() { Window.title = "Image Noise" __w = 320 __h = 240 Window.resize(__w, __h) Canvas.resize(__w, __h) __r = Random.new() __t = System.clock } ...
Give a code snippet in #Wren Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var file: lp is STD_NULL; begin lp := open("/dev/lp0", "w"); writeln(lp, "Hello world!"); close(lp); end func;
Give a code snippet in #Seed7 Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main() { @autoreleasepool { int num1, num2; scanf("%d %d", &num1, &num2);   NSLog(@"%d %d", num1, num2);   NSMutableArray *arr = [NSMutableArray arrayWithCapacity: (num1*num2)]; // initialize it with 0s for(int i=0; i < (num1*num2); i++) [arr addObject: ...
Give a code snippet in #Objective-C Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by thos...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Cowgol
Cowgol
include "cowgol.coh";   # In order to pass functions around, you must first define an interface. # This is similar to a delegate in C#; it becomes a function pointer type. # This interface takes two integers and returns one. interface Dyadic(x: int32, y: int32): (r: int32);   # For a function to be able to be passed ar...
Give a code snippet in #Cowgol Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Tailspin
Tailspin
  templates foo when <=0> do 'zero' -> !OUT::write when <..0> do 'negative ' -> !OUT::write -$ -> # when <?($ mod 2 <=0>)> do 'even' -> !OUT::write otherwise 'odd' -> !OUT::write end foo  
Give a code snippet in #Tailspin Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Comm...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Modula-2
Modula-2
MODULE A005179; FROM InOut IMPORT WriteCard, WriteLn;   CONST Amount = 15; VAR found, i, ndivs: CARDINAL; A: ARRAY [1..Amount] OF CARDINAL;   PROCEDURE divisors(n: CARDINAL): CARDINAL; VAR count, i: CARDINAL; BEGIN count := 0; i := 1; WHILE i*i <= n DO IF n MOD i = 0 THEN INC(cou...
Give a code snippet in #Modula-2 Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Genie
Genie
[indent=4] /* Arrays, in Genie   valac --pkg=gee-0.8 arrays.gs ./arrays */   uses Gee   init /* allocate a fixed array */ var arr = new array of int[10]   /* initialized array of strings */ initialized:array of string = {"This", "is", "Genie"}   /* length is an array property */ s...
Give a code snippet in #Genie This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retri...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_dates
Palindrome dates
Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program which calculates and shows th...
#BASIC
BASIC
  dateTest$ = "" total = 0   PRINT "Siguientes 15 fechas palindr¢micas al 2020-02-02:" FOR anno = 2021 TO 9999 dateTest$ = LTRIM$(STR$(anno)) FOR mes = 1 TO 12 IF mes < 10 THEN dateTest$ = dateTest$ + "0" dateTest$ = dateTest$ + LTRIM$(STR$(mes)) FOR dia = 1 TO 31 IF mes = 2 ...
Give a code snippet in #BASIC Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a progra...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Scheme
Scheme
(define maximum 5) (define minimum -5) (define number (+ (random (- (+ maximum 1) minimum)) minimum))   (display "Pick a number from ") (display minimum) (display " through ") (display maximum) (display ".\n> ") (do ((guess (read) (read))) ((eq? guess number)) (if (or (>= guess maximum) (< guess minimum)) ...
Give a code snippet in #Scheme Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: h...
christopher/rosetta-code
http://rosettacode.org/wiki/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q...
#Python
Python
from __future__ import division import sys   def pminf(array): x = 1 pmin_list = [] N = len(array) for index in range(N): if array[index] < x: pmin_list.insert(index, array[index]) else: pmin_list.insert(index, x) return pmin_list #end function   def cumminf(a...
Give a code snippet in #Python Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted ...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#E
E
def makeQueue() { def [var head, var tail] := Ref.promise()   def writer { to enqueue(value) { def [nh, nt] := Ref.promise() tail.resolve([value, nh]) tail := nt } }   def reader { to empty() { return !Ref.isResolved(head) }   to dequeue(whenEmpty) { if (Ref.isResolved(he...
Give a code snippet in #E Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each ot...
#Raku
Raku
use Math::Primesieve; my $sieve = Math::Primesieve.new;   my $max = 1_000_035; my @primes = $sieve.primes($max);   my $filter = @primes.Set; my $primes = @primes.categorize: &sexy;   say "Total primes less than {comma $max}: ", comma +@primes;   for <pair 2 triplet 3 quadruplet 4 quintuplet 5> -> $sexy, $cnt { say ...
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#XSLT
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" />   <xsl:template name="sum-prod"> <xsl:param name="values" /> <xsl:param name="sum" select="0" /> <xsl:param name="prod" select="1" /> <xsl:choose> <xsl:when test="not($values)"> ...
Give a code snippet in #XSLT Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Raku
Raku
constant n = 10; for ^n -> \k { say cis(k*τ/n); }
Give a code snippet in #Raku The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#R
R
  ## Stern-Brocot sequence ## 12/19/16 aev SternBrocot <- function(n){ V <- 1; k <- n/2; for (i in 1:k) { V[2*i] = V[i]; V[2*i+1] = V[i] + V[i+1];} return(V); }   ## Required tests: require(pracma); { cat(" *** The first 15:",SternBrocot(15),"\n"); cat(" *** The first i@n:","\n"); V=SternBrocot(40); for (i in...
Give a code snippet in #R For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Lambdatalk
Lambdatalk
  In lambdatalk every expression is a word or an S-expression, so:   {b hello world} // means "boldify the words hello and world" -> < b>hello world< /b> // HTML expression   {+ hello world} // means "add the words hello and world" -> NaN // can't do the job and returns Not a Number   {+ 123 1}...
Give a code snippet in #Lambdatalk Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#NewLISP
NewLISP
; file: html-table.lsp ; url: http://rosettacode.org/wiki/Create_an_HTML_table ; author: oofoe 2012-01-29   (seed (time-of-day)) ; Initialize random number generator.   ; The "tab" variable tracks the HTML indent. "pad" composes a line ; with the appropriate indent and a terminal newline.   (setq tab 0) (define (p...
Give a code snippet in #NewLISP Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled w...
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...
#Batch_File
Batch File
@echo off for /l %%D in (10,-1,0) do echo %%D
Give a code snippet in #Batch_File 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/I...
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...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program loopdownward.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   /*********************************/ /* Initialized data */ /*********************************/ .data s...
Give a code snippet in #ARM_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Nial
Nial
primes is sublist [ each (2 = sum eachright (0 = mod) [pass,count]), pass ] rest count
Give a code snippet in #Nial This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   al...
christopher/rosetta-code
http://rosettacode.org/wiki/Metronome
Metronome
The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an ext...
#Nim
Nim
import os   proc metronome(tempo, pattern: Positive) = let delay = 60_000 div tempo # In milliseconds. var beats = 0 while true: stdout.write if beats mod pattern == 0: "\nTICK" else: " tick" stdout.flushFile inc beats sleep(delay)   metronome(72, 4)
Give a code snippet in #Nim The task is to implement a   metronome. The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable. For the purpose of this task, it is acceptable to play sound files for production ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#jq
jq
def anagrams: (reduce .[] as $word ( {table: {}, max: 0}; # state ($word | explode | sort | implode) as $hash | .table[$hash] += [ $word ] | .max = ([ .max, ( .table[$hash] | length) ] | max ) )) | .max as $max | .table | .[] | select(length == $max) ;   # The task: split("\n") | anagr...
Give a code snippet in #jq When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Mozart.2FOz
Mozart/Oz
all: test   test: scriptname ./scriptname   scriptname: scriptname.oz ozc -x scriptname.oz   clean: -rm scriptname -rm *.exe
Give a code snippet in #Mozart.2FOz The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the s...
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...
#D
D
import std.stdio, std.math, std.string, std.typecons, std.traits;   const struct Imprecise { private const double value, delta;   this(in double v, in double d) pure nothrow { this.value = v; this.delta = abs(d); }   enum IsImprecise(T) = is(Unqual!T == Unqual!(typeof(this)));   I re...
Give a code snippet in #D 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Java
Java
public class Life{ public static void main(String[] args) throws Exception{ String start= "_###_##_#_#_#_#__#__"; int numGens = 10; for(int i= 0; i < numGens; i++){ System.out.println("Generation " + i + ": " + start); start= life(start); } }   public static String life(String lastGen){ String newGen...
Give a code snippet in #Java Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current ...
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#R
R
game21<-function(first = c("player","ai","random"),sleep=.5){ state = 0 finished = F turn = 1 if(length(first)==1 && startsWith(tolower(first),"r")){ first = rbinom(1,1,.5) }else{ first = (length(first)>1 || startsWith(tolower(first),"p")) } while(!finished){ if(turn>1 || first){ cat("Th...
Give a code snippet in #R 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the runn...
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...
#MATLAB
MATLAB
  inputString = fileread(csvFileName); % using multiple regular expressions to clear up special chars htmlFriendly = regexprep(regexprep(regexprep(regexprep(inputString,... '&','&amp;'),... '"','&quot;'),... '<','&lt;'),... '>','&gt;'); % split string into cell array tableValues = regexp(r...
Give a code snippet in #MATLAB 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/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Arbre
Arbre
main(): uppercase('alphaBETA') + '\n' + lowercase('alphaBETA') + '\n' -> io
Give a code snippet in #Arbre Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not r...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Euphoria
Euphoria
function gcd(integer m, integer n) integer tmp while m do tmp = m m = remainder(n,m) n = tmp end while return n end function   function lcm(integer m, integer n) return m / gcd(m, n) * n end function
Give a code snippet in #Euphoria Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#E
E
? def constList := [1,2,3,4,5] # value: [1, 2, 3, 4, 5]   ? constList.with(6) # value: [1, 2, 3, 4, 5, 6]   ? def flexList := constList.diverge() # value: [1, 2, 3, 4, 5].diverge()   ? flexList.push(6) ? flexList # value: [1, 2, 3, 4, 5, 6].diverge()   ? constList # value: [1, 2, 3, 4, 5]   ? def constMap := [1 => 2, 3...
Give a code snippet in #E This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#AutoHotkey
AutoHotkey
FileMove, oldname, newname
Give a code snippet in #AutoHotkey Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has t...
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Racket
Racket
  #lang racket (define (record n) (with-input-from-file "/dev/dsp" ( () (read-bytes n)))) (define (play bs) (display-to-file bs "/dev/dsp" #:exists 'append)) (play (record 65536))  
Give a code snippet in #Racket Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate...
christopher/rosetta-code
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#C.2B.2B
C++
  #include <time.h> #include <iostream> #include <string>   using namespace std;   class penney { public: penney() { pW = cW = 0; } void gameLoop() { string a; while( true ) { playerChoice = computerChoice = ""; if( rand() % 2 ) { computer(); player(); } else { player(); co...
Give a code snippet in #C.2B.2B Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads,...
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...
#C
C
#include <complex.h> #include <stdio.h>   void cprint(double complex c) { printf("%f%+fI", creal(c), cimag(c)); } void complex_operations() { double complex a = 1.0 + 1.0I; double complex b = 3.14159 + 1.2I;   double complex c;   printf("\na="); cprint(a); printf("\nb="); cprint(b);   // addition c = a ...
Give a code snippet in #C 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#FreeBASIC
FreeBASIC
' version 01-11-2016 ' compile with: fbc -s console   ' translation from Bitmap/Bresenham's line algorithm C entry Sub Br_line(x0 As Integer, y0 As Integer, x1 As Integer, y1 As Integer, _ Col As UInteger = &HFFFFFF)   Dim As Integer dx = Abs(x1 - x0), dy = Abs(y1 - y0) ...
Give a code snippet in #FreeBASIC Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Dyalect
Dyalect
func Integer.SumSeries() { var ret = 0   for i in 1..this { ret += 1 / pow(Float(i), 2) }   ret }   var x = 1000 print(x.SumSeries())
Give a code snippet in #Dyalect Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k =...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#Action.21
Action!
SET EndProg=*
Give a code snippet in #Action.21 Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data ...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#VBA
VBA
Public Sub Proper_Divisor() Dim t() As Long, i As Long, l As Long, j As Long, c As Long For i = 1 To 10 Debug.Print "Proper divisor of " & i & " : " & Join(S(i), ", ") Next For i = 2 To 20000 l = UBound(S(i)) + 1 If l > c Then c = l: j = i Next Debug.Print "Number in the rang...
Give a code snippet in #VBA The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisor...
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...
#Objeck
Objeck
  class Horner { function : Main(args : String[]) ~ Nil { coeffs := Collection.FloatVector->New(); coeffs->AddBack(-19.0); coeffs->AddBack(7.0); coeffs->AddBack(-4.0); coeffs->AddBack(6.0); PolyEval(coeffs, 3)->PrintLine(); }   function : PolyEval(coefficients : Collection.FloatVector , ...
Give a code snippet in #Objeck 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 ) {...
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...
#Scala
Scala
package rosetta   import scala.annotation.tailrec   object MoveToFront { /** * Default radix */ private val R = 256   /** * Default symbol table */ private def symbolTable = (0 until R).map(_.toChar).mkString   /** * Apply move-to-front encoding using default symbol table. */ def enco...
Give a code snippet in #Scala 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]]; mark = 0.1; gap = 0.125; (* gap should be equal to mark. But longer gap makes audio code easier to decode *) shortgap = 3*gap; medgap = 7*gap; longmark = 3*mark; MorseDictionary = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", ".."...
Give a code snippet in #Mathematica.2FWolfram_Language Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characte...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Julia
Julia
using HttpServer server = Server() do req, res "Goodbye, World!" end run(server, 8080)  
Give a code snippet in #Julia The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Commodore_BASIC
Commodore BASIC
10 print chr$(147);chr$(14);:REM 147=clear screen, 14=switch to lowercase mode 20 print "Hello world!" 30 end  
Give a code snippet in #Commodore_BASIC Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Pop11
Pop11
lvars val = 0; while true do val + 1 -> val; printf(val, '%p\n'); quitif(val rem 6 = 0); endwhile;
Give a code snippet in #Pop11 Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/D...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Euphoria
Euphoria
function selection_sort(sequence s) object tmp integer m for i = 1 to length(s) do m = i for j = i+1 to length(s) do if compare(s[j],s[m]) < 0 then m = j end if end for tmp = s[i] s[i] = s[m] s[m] = tmp end for r...
Give a code snippet in #Euphoria 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Forth
Forth
: get ( key len table -- data ) \ 0 if not present search-wordlist if >body @ else 0 then ;   : put ( data key len table -- ) >r 2dup r@ search-wordlist if r> drop nip nip >body ! else r> get-current >r set-current \ switch definition word lists nextname create , r> set-current ...
Give a code snippet in #Forth Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have m...
#Arturo
Arturo
lis: function [d][ l: new [[]] loop d 'num [ x: [] loop l 'seq [ if positive? size seq [ if and? num > last seq (size seq) > size x -> x: seq ] ] 'l ++ @[x ++ @[num]] ] result: [] loop...
Give a code snippet in #Arturo Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Nim
Nim
type   Node[T] = ref object value: T next: Node[T]   Queue*[T] = object head, tail: Node[T] length: Natural   func initQueue*[T](): Queue[T] = Queue[T]()   func len*(queue: Queue): Natural = queue.length   func isEmpty*(queue: Queue): bool {.inline.} = queue.len == 0   func push*[T](queue: var Q...
Give a code snippet in #Nim Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the ord...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#OCaml
OCaml
let one_of_n n = let rec aux i r = if i >= n then r else if Random.int (i + 1) = 0 then aux (succ i) i else aux (succ i) r in aux 1 0   let test ~n ~trials = let ar = Array.make n 0 in for i = 1 to trials do let d = one_of_n n in ar.(d) <- succ ar.(d) done; Array.iter (Printf...
Give a code snippet in #OCaml A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second lin...
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Quackery
Quackery
[ $ "" swap witheach [ nested quackery join ] ] is expand ( $ --> $ )   [ $ "ABA" ] is A ( $ --> $ )   [ $ "BBB" ] is B ( $ --> $ )   [ char A = iff [ char q ] else space swap of echo$ ] is draw ( n c --> $ )   81 $ "A" 5 ...
Give a code snippet in #Quackery Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#REXX
REXX
/* REXX ********************************************************************************** * Test frame for computing Christian (Roman Catholic) holidays, related to Easter * 16.04.2013 Walter Pachl * 08.03.2021 -"- extended range of years and indicate Roman Catholic use ***********************************************...
Give a code snippet in #REXX Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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) Task Write a function to compute the arithmetic-geomet...
#Raven
Raven
define agm use $a, $g, $errlim # $errlim $g $a "%d %g %d\n" print $a 1.0 + as $t repeat $a 1.0 * $g - abs -15 exp10 $a * > while $a $g + 2 / as $t $a $g * sqrt as $g $t as $a $g $a $t "t: %g a: %g g: %g\n" print $a     16 1 2 sqrt / 1 agm "agm: %.15g\n...
Give a code snippet in #Raven This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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) Task Write a function t...
christopher/rosetta-code
http://rosettacode.org/wiki/Jacobi_symbol
Jacobi symbol
The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) (a | p) ≡   1 ...
#jq
jq
  def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; def rpad($len): tostring | ($len - length) as $l | . + (" " * $l)[:$l];   def jacobi(a; n): {a: (a % n), n: n, result: 1} | until(.a == 0; until( .a % 2 != 0; .a /= 2 | if (.n % 8) | IN(3, 5) then ....
Give a code snippet in #jq The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#VBA
VBA
  Option Explicit   Sub Main_Munchausen_numbers() Dim i&   For i = 1 To 5000 If IsMunchausen(i) Then Debug.Print i & " is a munchausen number." Next i End Sub   Function IsMunchausen(Number As Long) As Boolean Dim Digits, i As Byte, Tot As Long   Digits = Split(StrConv(Number, vbUnicode), Chr(0)) ...
Give a code snippet in #VBA A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see T...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#CLU
CLU
kelvin = proc (k: real) returns (real) return(k) end kelvin   celsius = proc (k: real) returns (real) return(k - 273.15) end celsius   rankine = proc (k: real) returns (real) return(k * 9./5.) end rankine   fahrenheit = proc (k: real) returns (real) return(rankine(k) - 459.67) end fahrenheit   conv =...
Give a code snippet in #CLU There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 ke...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_dates
Palindrome dates
Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a program which calculates and shows th...
#C.2B.2B
C++
#include <iostream> #include <string> #include <boost/date_time/gregorian/gregorian.hpp>   bool is_palindrome(const std::string& str) { for (size_t i = 0, j = str.size(); i + 1 < j; ++i, --j) { if (str[i] != str[j - 1]) return false; } return true; }   int main() { using boost::grego...
Give a code snippet in #C.2B.2B Today   (2020-02-02,   at the time of this writing)   happens to be a palindrome,   without the hyphens,   not only for those countries which express their dates in the   yyyy-mm-dd   format but,   unusually,   also for countries which use the   dd-mm-yyyy   format. Task Write a prog...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Oforth
Oforth
: leftFact | i | 0 1 rot loop: i [ tuck + swap i * ] drop ;
Give a code snippet in #Oforth Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed)....
#Phix
Phix
with javascript_semantics constant LIMIT = 100 constant starts = {2, 5, 7, 9, 10} sequence ekg = {} string fmt = "EKG(%2d): ["&join(repeat("%d",min(LIMIT,30))," ")&"]\n" for s=1 to length(starts) do ekg = append(ekg,{1,starts[s]}&repeat(0,LIMIT-2)) for n=3 to LIMIT do -- a potential sequence member cann...
Give a code snippet in #Phix The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an el...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#Ruby
Ruby
numbers = ARGV.map(&:to_i) if numbers.length == 0 puts puts("usage: #{File.basename(__FILE__)} number...") exit end   def maya_print(number) digits5s1s = number.to_s(20).chars.map { |ch| ch.to_i(20) }.map { |dig| dig.divmod(5) } puts(('+----' * digits5s1s.length) + '+') 3.downto(0) do |row| digits5s1s.e...
Give a code snippet in #Ruby Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─t...
christopher/rosetta-code
http://rosettacode.org/wiki/Formal_power_series
Formal power series
A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ...
#Ruby
Ruby
# Class implementing the Formal Power Series type.   class Fps   # Initialize the FPS instance. # When nothing specified, all coefficients are 0. # When const: specifies n, all coefficients are n. # When delta: specifies n, a[0] = n, then all higher coefficients are zero. # When iota: specifies n, coefficient...
Give a code snippet in #Ruby A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#APL
APL
array←m n ⍴ 0 ⍝ array of zeros with shape of m by n.   array[1;1]←73 ⍝ assign a value to location 1;1.   array[1;1] ⍝ read the value back out   ⎕ex 'array' ⍝ erase the array  
Give a code snippet in #APL Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those number...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int K, N; [N:= 0; repeat K:= KeyHit; \counts up until a key is pressed IntOut(0, N); ChOut(0, ^ ); N:= N+1; until K; ]
Give a code snippet in #XPL0 Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#EDSAC_order_code
EDSAC order code
  [EDSAC program, Initial Orders 2. Calculates digits of pi by spigot algorithm. Easily edited to calculate digits of e (see "if pi" and "if e" in comments). Based on http://pi314.net/eng/goutte.php See also https://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml   Uses 17-bit values throughout. Arra...
Give a code snippet in #EDSAC_order_code Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a d...
christopher/rosetta-code
http://rosettacode.org/wiki/The_sieve_of_Sundaram
The sieve of Sundaram
The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integers, mark every third starting a...
#Wren
Wren
import "/fmt" for Fmt import "/seq" for Lst   var sos = Fn.new { |n| if (n < 3) return [] var primes = [] var k = ((n-3)/2).floor + 1 var marked = List.filled(k, true) var limit = ((n.sqrt.floor - 3)/2).floor + 1 limit = limit.max(0) for (i in 0...limit) { var p = 2*i + 3 var...
Give a code snippet in #Wren The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integer...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Ring
Ring
  # Project : Bulls and cows/Player   secret = "" while len(secret) != 4 c = char(48 + random(9)) if substr(secret, c) = 0 secret = secret + c ok end see "secret = " + secret + nl   possible = "" for i = 1234 to 9876 possible = possible + string(i) next   see "guess a four-digi...
Give a code snippet in #Ring Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those ...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#AppleScript
AppleScript
use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation"   on firstDateonWebPage(URLText) set |⌘| to current application set pageURL to |⌘|'s class "NSURL"'s URLWithString:(URLText) -- Fetch the page HTML as data. -- The Xcode documentation advises against using dataWit...
Give a code snippet in #AppleScript Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Teco
Teco
^AHello world!^A$$
Give a code snippet in #Teco Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#C
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h>   #include <execinfo.h>   #define MAX_BT 200   void print_stack_trace() { void *buffer[MAX_BT]; int n;   n = backtrace(buffer, MAX_BT); fprintf(stderr, "--- (depth %d) ---\n", n); backtrace_symbols_fd(buffer, n, STDERR_FILENO); }     void inner(int k)...
Give a code snippet in #C Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platfo...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#MiniScript
MiniScript
caesar = function(s, key) chars = s.values for i in chars.indexes c = chars[i] if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+key)%26) if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+key)%26) end for return chars.join("") end function   print caesar...
Give a code snippet in #MiniScript Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping...
christopher/rosetta-code
http://rosettacode.org/wiki/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Free_Pascal
Free Pascal
  Program ProperDivisors;   Uses fgl;   Type TIntegerList = Specialize TfpgList<longint>;   Var list : TintegerList;   Function GetProperDivisors(x : longint): longint; {this function will return the number of proper divisors and put them in the list}   Var i : longint; Begin list.clear; If x = 1 Then {by defau...
Give a code snippet in #Free_Pascal The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Io
Io
Roman := Object clone do ( nums := list(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) rum := list("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")   numeral := method(number, result := "" for(i, 0, nums size, if(number == 0, break) while(...
Give a code snippet in #Io Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Dyalect
Dyalect
func fact(n) => n is 0 ? 1 : (n^-1..<0).Fold(1, (acc, val) => acc * val)   func lah(n, k) { return fact(n) when k is 1 return 1 when k == n return 0 when k > n || k < 1 || n < 1 (fact(n) * fact(n - 1)) / (fact(k) * fact(k - 1)) / fact(n - k) }   print("Unsigned Lah numbers: L(n, k):"); print("n/k ",...
Give a code snippet in #Dyalect Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearl...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wheel
Word wheel
A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain the letter in the centre of the w...
#Julia
Julia
using Combinatorics   const tfile = download("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") const wordlist = Dict(w => 1 for w in split(read(tfile, String), r"\s+"))   function wordwheel(wheel, central) returnlist = String[] for combo in combinations([string(i) for i in wheel]) if central in com...
Give a code snippet in #Julia A "word wheel" is a type of word game commonly found on the "puzzle" page of newspapers. You are presented with nine letters arranged in a circle or 3×3 grid. The objective is to find as many words as you can using only the letters contained in the wheel or grid. Each word must contain th...
christopher/rosetta-code
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Raku
Raku
use SVG; my $w = 600; my $h = 600;   for 3..33 -> $a { my $angle = $a/τ; my $x1 = $w/2; my $y1 = $h/2; my @lines;   for 1..144 { my $length = 3 * $_; my ($x2, $y2) = ($x1, $y1) «+« |cis($angle * $_).reals».round(.01) »*» $length ; @lines.push: 'line' => [:x1($x1.clone), :y1(...
Give a code snippet in #Raku A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the an...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Wren
Wren
import "os" for Process   var hq9plus = Fn.new { |code| var acc = 0 var sb = "" for (c in code) { if (c == "h" || c == "H") { sb = sb + "Hello, world!\n" } else if (c == "q" || c == "Q") { sb = sb + code + "\n" } else if (c == "9") { for (i in 99.....
Give a code snippet in #Wren Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#PicoLisp
PicoLisp
(de encode (Str) (pack (make (for (Lst (chop Str) Lst) (let (N 1 C) (while (= (setq C (pop 'Lst)) (car Lst)) (inc 'N) ) (link N C) ) ) ) ) )   (de decode (Str) (pack (make (let N 0 (for C (chop Str) ...
Give a code snippet in #PicoLisp Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a f...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Bracmat
Bracmat
( ( mapRange = a1,a2,b1,b2,s .  !arg:(?a1,?a2.?b1,?b2.?s) & !b1+(!s+-1*!a1)*(!b2+-1*!b1)*(!a2+-1*!a1)^-1 ) & out$"Mapping [0,10] to [-1,0] at intervals of 1:" & 0:?n & whl ' ( !n:~>10 & out$("f(" !n ") = " flt$(mapRange$(0,10.-1,0.!n),2)) & 1+!n:?n ) );
Give a code snippet in #Bracmat Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS
HTTPS
Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Request task, and also the task on HTT...
#REALbasic
REALbasic
  Dim sock As New HTTPSecureSocket Print(sock.Get("https://sourceforge.net", 10)) //set the timeout period to 10 seconds.  
Give a code snippet in #REALbasic Task Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console. Checking the host certificate for validity is recommended. Do not authenticate. That is the subject of other tasks. Readers may wish to contrast with the HTTP Req...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Burlesque
Burlesque
  blsq ) {1 2 3 4}R@ {{} {1} {2} {1 2} {3} {1 3} {2 3} {1 2 3} {4} {1 4} {2 4} {1 2 4} {3 4} {1 3 4} {2 3 4} {1 2 3 4}}  
Give a code snippet in #Burlesque A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. G...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Python
Python
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("localhost", 256)) sock.sendall("hello socket world") sock.close()
Give a code snippet in #Python For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#PureBasic
PureBasic
  DataSection Data.s "In olden times when wishing still helped one, there lived a king "+ "whose daughters were all beautiful, but the youngest was so beautiful "+ "that the sun itself, which has seen so much, was astonished whenever "+ "it shone-in-her-face. Close-by-the-king's castle lay a great dark...
Give a code snippet in #PureBasic Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#Nim
Nim
import math   type Circle = tuple[x, y, r: float]   proc solveApollonius(c1, c2, c3: Circle; s1, s2, s3: float): Circle = let v11 = 2*c2.x - 2*c1.x v12 = 2*c2.y - 2*c1.y v13 = c1.x*c1.x - c2.x*c2.x + c1.y*c1.y - c2.y*c2.y - c1.r*c1.r + c2.r*c2.r v14 = 2*s2*c2.r - 2*s1*c1.r   v21 = 2*c3.x - 2*c2.x ...
Give a code snippet in #Nim Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforw...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#Kotlin
Kotlin
// version 1.1.2   class SomeClass { val id: Int   companion object { private var lastId = 0 val objectsCreated get() = lastId }   init { id = ++lastId } }   fun main(args: Array<String>) { val sc1 = SomeClass() val sc2 = SomeClass() println(sc1.id) println(...
Give a code snippet in #Kotlin Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static s...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#JavaScript
JavaScript
  function wrap (text, limit) { if (text.length > limit) { // find the last space within limit var edge = text.slice(0, limit).lastIndexOf(' '); if (edge > 0) { var line = text.slice(0, edge); var remainder = text.slice(edge + 1); return line + '\n' + wrap(remainder, limit); } } ...
Give a code snippet in #JavaScript Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or...
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...
#Lingo
Lingo
repeat with i = 10 down to 0 put i end repeat
Give a code snippet in #Lingo 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