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/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#QB64
QB64
  ' Jumps in QB64 are inherited by Qbasic/ QuickBasic/ GWBasic ' here a GOTO demo of loops FOR-NEXT and WHILE-WEND   Dim S As String, Q As Integer Randomize Timer 0: Locate 1, 1: Print "jump demostration" Print "Press J to jump to FOR NEXT emulator or" Print "L to jump to WHILE WEND emulator or" Print "Q for quitting"...
Give a code snippet in #QB64 Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#PureBasic
PureBasic
EnableExplicit Define vzr.b = -1, vzc.b = ~vzr, nMAX.i = 10, n.i , k.i   Procedure coeff(nRow.i, Array pd.i(2)) Define n.i, k.i For n=1 To nRow For k=0 To n If k=0 Or k=n : pd(n,k)=1 : Continue : EndIf pd(n,k)=pd(n-1,k-1)+pd(n-1,k) Next Next EndProcedure   Procedure.b isPrime(n.i, Array pd.i(2...
Give a code snippet in #PureBasic The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Agena
Agena
move := proc(n::number, src::number, dst::number, via::number) is if n > 0 then move(n - 1, src, via, dst) print(src & ' to ' & dst) move(n - 1, via, dst, src) fi end   move(4, 1, 2, 3)
Give a code snippet in #Agena Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#Pascal
Pascal
program Pot5Test; {$IFDEF FPC} {$MODE DELPHI}{$ELSE]{$APPTYPE CONSOLE}{$ENDIF} type tTest = double;//UInt64;{ On linux 32Bit double is faster than Uint64 } var Pot5 : array[0..255] of tTest; res,tmpSum : tTest; x0,x1,x2,x3, y : NativeUint;//= Uint32 or 64 depending on OS xx-Bit i : byte; BEGIN For i := 1 ...
Give a code snippet in #Pascal There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power,...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#PARI.2FGP
PARI/GP
Crv ( k, v, d ) = { if( d == k, print ( vecextract( v , "2..-2" ) ) , for( i = v[ d + 1 ] + 1, #v, v[ d + 2 ] = i; Crv( k, v, d + 1 ) )); }   combRV( n, k ) = Crv ( k, vector( n, X, X-1), 0 );
Give a code snippet in #PARI.2FGP Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#M2000_Interpreter
M2000 Interpreter
  a=(1,2,3,4,5) b=Cons(a, (6,7,8),a) Print b 1 2 3 4 5 6 7 8 1 2 3 4 5  
Give a code snippet in #M2000_Interpreter Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Rust
Rust
struct SimpleMovingAverage { period: usize, numbers: Vec<usize> }   impl SimpleMovingAverage { fn new(p: usize) -> SimpleMovingAverage { SimpleMovingAverage { period: p, numbers: Vec::new() } }   fn add_number(&mut self, number: usize) -> f64 { self.nu...
Give a code snippet in #Rust Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#Groovy
Groovy
import org.joda.time.* import java.text.*   def dateString = 'March 7 2009 7:30pm EST'   def sdf = new SimpleDateFormat('MMMM d yyyy h:mma zzz')   DateTime dt = new DateTime(sdf.parse(dateString))   println (dt) println (dt.plusHours(12)) println (dt.plusHours(12).withZone(DateTimeZone.UTC))
Give a code snippet in #Groovy Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (de c () (prinl "Got 'c': " (opt)) )   (de h () (prinl "Got 'h': " (opt)) )   (load T) (bye)
Give a code snippet in #PicoLisp Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/File_size_distribution
File size distribution
Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no...
#Rust
Rust
  use std::error::Error; use std::marker::PhantomData; use std::path::{Path, PathBuf}; use std::{env, fmt, io, time}; use walkdir::{DirEntry, WalkDir};   fn main() -> Result<(), Box<dyn Error>> { let start = time::Instant::now(); let args: Vec<String> = env::args().collect();   let root = parse_path(&args)....
Give a code snippet in #Rust Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#Lua
Lua
require("LuaXML")   function addNode(parent, nodeName, key, value, content) local node = xml.new(nodeName) table.insert(node, content) parent:append(node)[key] = value end   root = xml.new("CharacterRemarks") addNode(root, "Character", "name", "April", "Bubbly: I'm > Tam and <= Emily") addNode(root, "Charac...
Give a code snippet in #Lua Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> elem...
christopher/rosetta-code
http://rosettacode.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm
Elliptic Curve Digital Signature Algorithm
Elliptic curves. An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp, which satisfy the above defining eq...
#Wren
Wren
import "/dynamic" for Struct import "/big" for BigInt import "/fmt" for Fmt import "/math" for Boolean import "random" for Random   var rand = Random.new()   // rational ec point: x and y are BigInts var Epnt = Struct.create("Epnt", ["x", "y"])   // elliptic curve parameters: N is a BigInt, G is an Epnt, rest are integ...
Give a code snippet in #Wren Elliptic curves. An elliptic curve E over ℤp (p ≥ 5) is defined by an equation of the form y^2 = x^3 + ax + b, where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set E(ℤp) consists of all points (x, y), with x, y ∈ ℤp, which...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Little_Man_Computer
Little Man Computer
  // Little Man Computer // Sort x, y, z, in ascending order // Based on a sorting network: // if x > z then swap( x, z) // if x > y then swap( x, y) // if y > z then swap( y, z) // with the addition that if the 2nd swap is executed // then the 3rd comparison is not needed.   // Read numbers x, y, z, and display ...
Give a code snippet in #Little_Man_Computer 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#Racket
Racket
  #lang racket ; This file contains utf-8 charachters: λ, α, γ ... (for ([c (in-port read-char (open-input-file "read-file.rkt"))]) (display c))  
Give a code snippet in #Racket Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should supp...
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...
#Visual_Basic_.NET
Visual Basic .NET
' Bernoulli numbers - vb.net - 06/03/2017 Imports System.Numerics 'BigInteger   Module Bernoulli_numbers   Function gcd_BigInt(ByVal x As BigInteger, ByVal y As BigInteger) As BigInteger Dim y2 As BigInteger x = BigInteger.Abs(x) Do y2 = BigInteger.Remainder(x, y) x =...
Give a code snippet in #Visual_Basic_.NET 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 us...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Java
Java
public class QuadraticRoots { private static class Complex { double re, im;   public Complex(double re, double im) { this.re = re; this.im = im; }   @Override public boolean equals(Object obj) { if (obj == this) {return true;} i...
Give a code snippet in #Java This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your p...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#D
D
func Integer.Double() { this + this } print(8.Double())
Give a code snippet in #D Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#PL.2FI
PL/I
*process or(!) source attributes xref; joseph: Proc Options(main); /* REXX ************************************************************** * 15.11.2012 Walter Pachl - my own solution * 16.11.2012 Walter Pachl generalized n prisoners + w killing distance * and s=number of survivors * 03.05.2...
Give a code snippet in #PL.2FI Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Julia
Julia
isleap(yr::Integer) = yr % 4 == 0 && (yr < 1582 || yr % 400 == 0 || yr % 100 != 0)   @assert all(isleap, [2400, 2012, 2000, 1600, 1500, 1400]) @assert !any(isleap, [2100, 2014, 1900, 1800, 1700, 1499])
Give a code snippet in #Julia Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Clipper
Clipper
Replicate( "Ha", 5 )
Give a code snippet in #Clipper Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#C
C
#include <stdio.h>   int main() { fprintf(stderr, "Goodbye, "); fputs("World!\n", stderr);   return 0; }
Give a code snippet in #C Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". T...
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#11l
11l
F zigzag(n) F compare(xy) V (x, y) = xy R (x + y, I (x + y) % 2 {-y} E y) V xs = 0 .< n R Dict(enumerate(sorted((multiloop(xs, xs, (x, y) -> (x, y))), key' compare)), (n, index) -> (index, n))   F printzz(myarray) V n = Int(myarray.len ^ 0.5 + 0.5) V xs = 0 .< n print((xs.map(y -> @xs.map(...
Give a code snippet in #11l Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encod...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#J
J
variable=: '' 0=#variable 1 0<#variable 0
Give a code snippet in #J Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other t...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Rust
Rust
#![feature(inclusive_range_syntax)]   extern crate rand;   use rand::Rng;   fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize { rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1 }   fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize { let mut bit = rand_n(rng, n); while bit == rand_n(rng, ...
Give a code snippet in #Rust P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator t...
christopher/rosetta-code
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "net/http" "os" "strings" "time" )   func get(url string) (res string, err error) { resp, err := http.Get(url) if err != nil { return "", err } buf, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } return string(buf), nil }   func grep(n...
Give a code snippet in #Go Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or yo...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#Nim
Nim
import algorithm, math, sequtils, strutils   type Partition = seq[seq[int]]     func isIncreasing(s: seq[int]): bool = ## Return true if the sequence is sorted in increasing order. var prev = 0 for val in s: if prev >= val: return false prev = val result = true     iterator partitions(lengths: varargs[i...
Give a code snippet in #Nim In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r ...
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#MAD
MAD
NORMAL MODE IS INTEGER   R VERIFY DAMM CHECKSUM OF NUMBER INTERNAL FUNCTION(CKNUM) VECTOR VALUES DAMMIT = 0 0,3,1,7,5,9,8,6,4,2 1 , 7,0,9,2,1,5,4,8,6,3 2 , 4,2,0,6,8,7,1,3,5,9 3 , 1,7,5,0,9,8,3,4,2,6 4...
Give a code snippet in #MAD The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#D
D
import std.bigint; import std.conv; import std.stdio; import std.string;   void main() { auto rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]; BigInt one = 1; BigInt nine = 9;   for (int ii = 2; ii <= 9; ii++) { writefln("First 10 super-%d numbers:", ii); ...
Give a code snippet in #D A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Modula-2
Modula-2
MODULE IntCompare;   IMPORT InOut;   VAR A, B: INTEGER;   BEGIN InOut.ReadInt(A); InOut.ReadInt(B); InOut.WriteInt(A, 1);   IF A < B THEN InOut.WriteString(' is less than ') ELSIF A = B THEN InOut.WriteString(' is equal to ') ELSE InOut.WriteString(' is greater than ') END; InOut.WriteInt(...
Give a code snippet in #Modula-2 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#PicoLisp
PicoLisp
  #if niven number, return it. (de niven (N) (if (=0 (% N (apply + (getN N)))) N) )   #function which creates a list of numbers from input (de getN (N) (mapcar format (chop N)) )   #This function generates niven number list (de nivGen (R N) (extract niven (range R N)) )   #print 1st 20 niven numbers and 1st ni...
Give a code snippet in #PicoLisp The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Fixed_length_records
Fixed length records
Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had a limited character set, encod...
#Phix
Phix
without js -- file i/o constant sample_text = """ Line 1...1.........2.........3.........4.........5.........6.........7.........8 Line 2 Line 3 Line 4 Line 6 Line 7 Indented line 8............................................................ Line 9 ...
Give a code snippet in #Phix Fixed length read/write Before terminals, computers commonly used punch card readers or paper tape input. A common format before these devices were superseded by terminal technology was based on the Hollerith code, Hollerith code. These input devices handled 80 columns per card and had ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#jq
jq
def Quaternion(q0;q1;q2;q3): { "q0": q0, "q1": q1, "q2": q2, "q3": q3, "type": "Quaternion" };   # promotion of a real number to a quaternion def Quaternion(r): if (r|type) == "number" then Quaternion(r;0;0;0) else r end;   # thoroughly recursive pretty-print def pp:   def signage: if . >= 0 then "+ \(.)" else "- \...
Give a code snippet in #jq Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number mig...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#C.23
C#
using System; using System.Linq; using System.Collections.Generic;   public class Program { string s = @"gHHH5YY++///\"; Console.WriteLine(s.RunLengthSplit().Delimit(", ")); }   public static class Extensions { public static IEnumerable<string> RunLengthSplit(this string source) { using (var enumera...
Give a code snippet in #C.23 Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Factor
Factor
USING: ascii math.order sorting.human ;   IN: scratchpad "foo" "bar" = . ! compare for equality f IN: scratchpad "foo" "bar" = not . ! compare for inequality t IN: scratchpad "foo" "bar" before? . ! lexically ordered before? f IN: scratchpad "foo" "bar" after? . ! lexically ordered after? t IN: scratchpad "Foo" "foo" <...
Give a code snippet in #Factor Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#OCaml
OCaml
let get g x y = try g.(x).(y) with _ -> 0   let neighbourhood g x y = (get g (x-1) (y-1)) + (get g (x-1) (y )) + (get g (x-1) (y+1)) + (get g (x ) (y-1)) + (get g (x ) (y+1)) + (get g (x+1) (y-1)) + (get g (x+1) (y )) + (get g (x+1) (y+1))   let next_cell g x y = let n = neighbourhood g x y i...
Give a code snippet in #OCaml The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#Ceylon
Ceylon
import ceylon.random {   DefaultRandom }   abstract class Colour(name, ordinal) of red | white | blue satisfies Comparable<Colour> { shared String name; shared Integer ordinal; string => name; compare(Colour other) => this.ordinal <=> other.ordinal; }   object red extends Colour("red", 0) {} object white extends ...
Give a code snippet in #Ceylon The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the c...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Wren
Wren
System.print("møøse".bytes.count) System.print("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".bytes.count) System.print("J̲o̲s̲é̲".bytes.count)
Give a code snippet in #Wren Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme conta...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PureBasic
PureBasic
#STEP=2.2   Procedure Shell_sort(Array A(1)) Protected l=ArraySize(A()), increment=Int(l/#STEP) Protected i, j, temp While increment For i= increment To l j=i temp=A(i) While j>=increment And A(j-increment)>temp A(j)=A(j-increment) j-increment Wend A(j)=temp N...
Give a code snippet in #PureBasic Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Forth
Forth
  ( Gforth 0.7.3 )   : dnacode s" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCG...
Give a code snippet in #Forth Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAAT...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type DynamicVariable As String name As String value End Type   Function FindVariableIndex(a() as DynamicVariable, v as String, nElements As Integer) As Integer v = LCase(Trim(v)) For i As Integer = 1 To nElements If a(i).name = v Then Return i Next Return 0 End Function   Dim As Int...
Give a code snippet in #FreeBASIC Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#C
C
#include <sys/stat.h> #include <stdio.h> #include <time.h> #include <utime.h>   const char *filename = "input.txt";   int main() { struct stat foo; time_t mtime; struct utimbuf new_times;   if (stat(filename, &foo) < 0) { perror(filename); return 1; } mtime = foo.st_mtime; /* seconds since the epoch...
Give a code snippet in #C Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Compile-time_calculation
Compile-time calculation
Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
#Haskell
Haskell
module Factorial where import Language.Haskell.TH.Syntax   fact n = product [1..n]   factQ :: Integer -> Q Exp factQ = lift . fact
Give a code snippet in #Haskell Some programming languages allow calculation of values at compile time. Task Calculate   10!   (ten factorial)   at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
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...
#Run_BASIC
Run BASIC
a$ = shell$("RENAME input.txt output.txt") a$ = shell$("RENAME docs mydocs") a$ = shell$("RENAME \input.txt \output.txt") a$ = shell$("RENAME \docs \mydocs")
Give a code snippet in #Run_BASIC 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Quackery
Quackery
[ split reverse join ] is flip ( [ n --> [ )   [ 0 swap behead swap witheach [ 2dup > iff [ nip nip i^ 1+ swap ] else drop ] drop ] is smallest ( [ --> n )   [ dup size times [ dup i^ split nip smallest i^ + flip i^ flip ] ] i...
Give a code snippet in #Quackery 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/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Maple
Maple
  with(LinearAlgebra):   ReducedRowEchelonForm(<<1,2,-2>|<2,3,0>|<-1,-1,-3>|<-4,-11,22>>);  
Give a code snippet in #Maple Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenien...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Modula-2
Modula-2
MODULE LeapYear; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   PROCEDURE IsLeapYear(year : INTEGER) : BOOLEAN; BEGIN IF year MOD 100 = 0 THEN RETURN year MOD 400 = 0; END; RETURN year MOD 4 = 0 END IsLeapYear;   PROCEDURE Print(year : INTEGER); VAR buf : ARR...
Give a code snippet in #Modula-2 Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#PowerShell
PowerShell
  &{}  
Give a code snippet in #PowerShell Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#UNIX_Shell
UNIX Shell
#!/bin/sh   if [ -t 1 ] then echo "Output is a terminal" else echo "Output is NOT a terminal" >/dev/tty fi
Give a code snippet in #UNIX_Shell Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#AppleScript
AppleScript
on factorCount(n) set counter to 0 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set counter to counter + 1 set limit to limit - 1 end if repeat with i from limit to 1 by -1 if (n mod i is 0) then set counter to counter + 2 end repeat   return...
Give a code snippet in #AppleScript The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Factor
Factor
USING: io kernel math.ranges prettyprint random sequences ;   10 [ 20 [ 20 [1,b] random ] replicate ] replicate  ! make a table of random values [ [ dup pprint bl 20 = ] find nl drop ] find 2drop  ! print values until 20 is found
Give a code snippet in #Factor Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is m...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#GML
GML
#define charMatch { first = "qwertyuiop";   // Determining if the first string starts with second string second = "qwerty"; if (string_pos(second, first) > 0) { show_message("'" + first + "' starts with '" + second + "'"); } else { show_message("'" + first + "' does not start with '...
Give a code snippet in #GML Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
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,...
#Modula-2
Modula-2
VAR staticArray: ARRAY [1..10] OF INTEGER;
Give a code snippet in #Modula-2 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 re...
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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Main() Dim iList As Integer[] = [1, 2, 3, 4, 5] Dim iSum, iCount As Integer Dim iPrd As Integer = 1   For iCount = 0 To iList.Max iSum += iList[iCount] iPrd *= iList[iCount] Next   Print "The Sum =\t" & iSum Print "The Product =\t" & iPrd   End
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#PowerShell
PowerShell
$Strings = "Enjoy","Rosetta","Code"   $SB = {param($String)Write-Output $String}   foreach($String in $Strings) { Start-Job -ScriptBlock $SB -ArgumentList $String | Out-Null }   Get-Job | Wait-Job | Receive-Job Get-Job | Remove-Job
Give a code snippet in #PowerShell Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in y...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#dc
dc
1000 sn [ n = number of iterations ]sx 2574k [ precision to use during computation ]sx 1 d se sf [ set e and f to 1 ]sx 0 si [ set i to 0 ]sx [ [ p = begin ]sx lf li 1 + d si * sf [ f = f*(++i) ]sx le 1 lf / + se [...
Give a code snippet in #dc Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Simulate_input/Mouse
Simulate input/Mouse
#FreeBASIC
FreeBASIC
#include "fbgfx.bi" #define rect 4   Windowtitle "Mouse events" Screen 19,32 Dim Shared As Integer xres, yres Screeninfo xres, yres   Type box As Single x, y, z As String caption As Uinteger textcol, boxcol End Type   Dim Shared As box label(rect,1) Dim Shared As box button(rect,1) Dim Shared As Boolean fla...
Give a code snippet in #FreeBASIC
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#LotusScript
LotusScript
Sub Click() 'a few declarations as example Dim s as New NotesSession ' declaring a New NotesSession actually returns the current, active NotesSession Dim i as Integer ' i = 0 Dim s as String ' s= "" Dim v as Variant ' v is nothing Dim l as Long ' l = 0 Dim doc as NotesDocument 'doc is EMTPY   '...   End Sub  
Give a code snippet in #LotusScript Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Eiffel
Eiffel
  note description: "Example of Ackerman function" synopsis: "[ The EIS link below (in Eiffel Studio) will launch in either an in-IDE browser or and external browser (your choice). The protocol informs Eiffel Studio about what program to use to open the `src' reference, which can be URI, PDF, or DOC. See seco...
Give a code snippet in #Eiffel The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Bracmat
Bracmat
( (sqrt=.!arg^1/2) & (log=.e\L!arg) & (A=x2d (=.!arg^2) log (=.!arg*pi)) & ( B = d2x sqrt (=.e^!arg) (=.!arg*pi^-1) ) & ( compose = f g .  !arg:(?f.?g) & '(.($f)$(($g)$!arg)) ) & whl ' ( !A:%?F ?A & !B:%?G ?B & out$((compose$(!F.!G))$3210) ) )
Give a code snippet in #Bracmat A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Locomotive_Basic
Locomotive Basic
10 CLS:RANDOMIZE TIME 20 PRINT "Please specify lower and upper limits":guess=0 30 INPUT " (must be positive integers) :", first, last 40 IF first<1 OR last<1 THEN 20 50 num=INT(RND*(last-first+1)+first) 60 WHILE num<>guess 70 INPUT "Your guess? ", guess 80 IF guess<num THEN PRINT "too small!" 90 IF guess>num THEN PRIN...
Give a code snippet in #Locomotive_Basic 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 gu...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Kotlin
Kotlin
/* for symmetry with Kotlin's other binary bitwise operators we wrap Java's 'rotate' methods as infix functions */ infix fun Int.rol(distance: Int): Int = Integer.rotateLeft(this, distance) infix fun Int.ror(distance: Int): Int = Integer.rotateRight(this, distance)   fun main(args: Array<String>) { // inferred...
Give a code snippet in #Kotlin Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Swift_2
Swift
struct RecursiveFunc<F> { let o : RecursiveFunc<F> -> F }   func Y<A, B>(f: (A -> B) -> A -> B) -> A -> B { let r = RecursiveFunc<A -> B> { w in f { w.o(w)($0) } } return r.o(r) }   let fac = Y { (f: Int -> Int) in { $0 <= 1 ? 1 : $0 * f($0-1) } } let fib = Y { (f: Int -> Int) in { $0 <= 2 ? 1 : f($0-1)+f($0-...
Give a code snippet in #Swift_2 In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#uBasic.2F4tH
uBasic/4tH
dim @y(2) ' yin or yang dim @e(5) ' the elements dim @a(12) ' the animals   Push Dup("yang"), Dup("yin") ' fill Ying/Yang table For i = 1 to 0 step -1 : @y(i) = Pop() : Next i ' fill El...
Give a code snippet in #uBasic.2F4tH Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.2B.2B
C++
#include <string> #include <iostream>   int main() { // Allocate enough memory to hold an instance of std::string char* data = new char[sizeof(std::string)];   // use placement new to construct a std::string in the memory we allocated previously std::string* stringPtr = new (data) std::string("ABCD");  ...
Give a code snippet in #C.2B.2B Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Nim
Nim
import strutils   proc magic(n: int) = let length = len($(n * n)) for row in 1 .. n: for col in 1 .. n: let cell = (n * ((row + col - 1 + n div 2) mod n) + ((row + 2 * col - 2) mod n) + 1) stdout.write ($cell).align(length), ' ' echo "" echo "\nAll sum to magic number ", (n *...
Give a code snippet in #Nim A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers a...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#PARI.2FGP
PARI/GP
  Pascals_triangle_puzzle(topvalue=151,leftsidevalue=40,bottomvalue1=11,bottomvalue2=4) = { y=(topvalue-(4*(bottomvalue1+bottomvalue2)))/7; x=leftsidevalue-(y+2*bottomvalue1); z=y-x; print(x","y","z); }  
Give a code snippet in #PARI.2FGP This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#Dyalect
Dyalect
func bubbleSort(list) { var done = false while !done { done = true for i in 1..(list.Length()-1) { if list[i - 1] > list[i] { var x = list[i] list[i] = list[i - 1] list[i - 1] = x done = false } } ...
Give a code snippet in #Dyalect 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/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...
#Icon_and_Unicon
Icon and Unicon
  procedure power_set (s) result := set () if *s = 0 then insert (result, set ()) # empty set else { head := set(?s) # take a random element # and find powerset of remaining part of set tail_pset := power_set (x -- head) result ++:= tail_pset # add powerset of remainder to results ...
Give a code snippet in #Icon_and_Unicon 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 ignor...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#ATS
ATS
(* Languages with pattern matching ALREADY HAVE THIS! *)   fn func (pred1 : bool, pred2 : bool) : void = case+ (pred1, pred2) of | (true, true) => println! ("(true, true)") | (true, false) => println! ("(true, false)") | (false, true) => println! ("(false, true)") | (false, false) => println! ("(false, false)...
Give a code snippet in #ATS Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. b...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#ALGOL_68
ALGOL 68
BEGIN # find sequences of primes where the gaps between the elements # # are strictly ascending/descending # # reurns a list of primes up to n # PROC prime list = ( INT n )[]INT: BEGIN # sieve the primes to n # INT no = 0, yes = 1; [ ...
Give a code snippet in #ALGOL_68 Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for p...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#SPARK
SPARK
with Spark_IO; --# inherit Spark_IO; --# main_program; procedure Dot_Product_Main --# global in out Spark_IO.Outputs; --# derives Spark_IO.Outputs from *; is Limit : constant := 1000; type V_Elem is range -Limit .. Limit; V_Size : constant := 100; type V_Index is range 1 .. V_Size; type Vector is array(V...
Give a code snippet in #SPARK Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1...
christopher/rosetta-code
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Wren
Wren
var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6\%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"   var encode = Fn.new { |s| var res = "" for (c in s) res = res + key[c.bytes[0] - 32] return res }   var decode = Fn.new { |s| var res = "" for (c in s) res = res + String.fromByte(key.inde...
Give a code snippet in #Wren Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then aga...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Ring
Ring
  n = 1234567 middle(n)   func middle nr mnr = floor(len(string(nr))/2) lennr = len(string(nr)) if lennr = 3 see "" + nr + nl but lennr < 3 see "Number must have at least three digits" but lennr%2=0 see "Number must have an odd number of digits" else cnr = substr(string(nr),mnr,3) see cnr ...
Give a code snippet in #Ring Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tes...
christopher/rosetta-code
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Lua
Lua
  -- Accept an integer representing a codepoint. -- Return the values of the individual octets. function encode (codepoint) local codepoint_str = utf8.char(codepoint) local result = {}   for i = 1, #codepoint_str do result[#result + 1] = string.unpack("B", codepoint_str, i) end   return table.unpack(resul...
Give a code snippet in #Lua As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes repre...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#TXR
TXR
/* window_creation_x11.wren */   var KeyPressMask = 1 << 0 var ExposureMask = 1 << 15 var KeyPress = 2 var Expose = 12   foreign class XGC { construct default(display, screenNumber) {} }   foreign class XEvent { construct new() {}   foreign eventType }   foreign class XDisplay { construct open...
Give a code snippet in #TXR Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Scala
Scala
object LastLetterFirstLetterNaive extends App { def solve(names: Set[String]) = { def extend(solutions: List[List[String]]): List[List[String]] = { val more = solutions.flatMap{solution => val lastLetter = solution.head takeRight 1 (names -- solution).filter(_.take(1) equalsIgnoreCase lastLe...
Give a code snippet in #Scala A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the ca...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#F.23
F#
//val inline factorial : // ^a -> ^a // when ^a : (static member get_One : -> ^a) and // ^a : (static member ( + ) : ^a * ^a -> ^a) and // ^a : (static member ( * ) : ^a * ^a -> ^a) let inline factorial n = Seq.reduce (*) [ LanguagePrimitives.GenericOne .. n ]
Give a code snippet in #F.23 Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#ERRE
ERRE
  PROGRAM LOOK   PROCEDURE LOOK_AND_SAY(N$->N$) LOCAL I%,J%,C$,O$ I%=1 REPEAT C$=MID$(N$,I%,1) J%=I%+1 WHILE MID$(N$,J%,1)=C$ DO J%+=1 END WHILE O$+=MID$(STR$(J%-I%),2)+C$ I%=J% UNTIL I%>LEN(N$) N$=O$ END PROCEDURE   BEGIN NUM...
Give a code snippet in #ERRE The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#NewLISP
NewLISP
(pow 0 0)
Give a code snippet in #NewLISP Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     o...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ /* program taufunction64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "....
Give a code snippet in #AArch64_Assembly Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#XQuery
XQuery
  xquery version "3.1";   declare function local:decode-roman-numeral($roman-numeral as xs:string) { $roman-numeral => upper-case() => for-each( function($roman-numeral-uppercase) { analyze-string($roman-numeral-uppercase, ".")/fn:match  ! map { "M": 1000, "D": 500, "C": 10...
Give a code snippet in #XQuery Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#Julia
Julia
function levendist(s::AbstractString, t::AbstractString) ls, lt = length.((s, t)) ls == 0 && return lt lt == 0 && return ls   s₁, t₁ = s[2:end], t[2:end] ld₁ = levendist(s₁, t₁) s[1] == t[1] ? ld₁ : 1 + min(ld₁, levendist(s, t₁), levendist(s₁, t)) end   @show levendist("kitten", "sitting") # 3 @...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and com...
christopher/rosetta-code
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#C
C
#include <stdio.h> #include <math.h>   int main() { int n = 1, count = 0, sq, cr; for ( ; count < 30; ++n) { sq = n * n; cr = (int)cbrt((double)sq); if (cr * cr * cr != sq) { count++; printf("%d\n", sq); } else { printf("%d is square an...
Give a code snippet in #C Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Potion
Potion
# The readable recursive version palindrome_i = (s, b, e): if (e <= b): true. elsif (s ord(b) != s ord(e)): false. else: palindrome_i(s, b+1, e-1). .   palindrome = (s): palindrome_i(s, 0, s length - 1).   palindrome(argv(1))
Give a code snippet in #Potion A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly a...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#langur
langur
val .isPrime = f .i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2   val .isMersennePrime = f(.p) { if .p == 2: return true if not .isPrime(.p): return false   val .mp = 2 ^ .p - 1 for[.s=4] of 3 to .p { .s = (.s ^ 2 - 2) rem .mp } == 0 }   writeln join " ", map f $"M\....
Give a code snippet in #langur Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#JavaScript
JavaScript
document.onkeydown = function(evt) { if (evt.keyCode === 118) { alert("You pressed F7!"); return false; } }
Give a code snippet in #JavaScript Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Run_BASIC
Run BASIC
graphic #g, 600,600 RL$ = "R" loc = 90 pass = 0   [loop] #g "cls ; home ; north ; down ; fill black" for i =1 to len(RL$) v = 255 * i /len(RL$) #g "color "; v; " 120 "; 255 -v #g "go "; loc if mid$(RL$,i,1) ="R" then #g "turn 90" else #g "turn -90" next i   #g "color 255 120 0" #g "go "; loc LR$ ="" for...
Give a code snippet in #Run_BASIC Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#Raku
Raku
sub div-count (\x) { return 2 if x.is-prime; +flat (1 .. x.sqrt.floor).map: -> \d { unless x % d { my \y = x div d; y == d ?? y !! (y, d) } } }   my $limit = 15;   my $m = 1; put "First $limit terms of OEIS:A069654"; put (1..$limit).map: -> $n { my $ = $m = first { $n == .&div-count }, $m..Inf };  
Give a code snippet in #Raku Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exac...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-dimensional_array
Multi-dimensional array
For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value. ...
#Ada
Ada
  type Grade is range 0..100; subtype Lower_Case is Character range 'a'..'z'; subtype Natural is Integer range 0..Integer'Last; subtype Positive is Integer range 1..Integer'Last; type Deflection is range -180..180;  
Give a code snippet in #Ada For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. It is enough to: State the number and extent of each index to the array. Provide specific, ordered, integer indices for all dimensions of the array together with a new value ...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#F.23
F#
let str = "hello" let additionalReference = str let deepCopy = System.String.Copy( str )   printfn "%b" <| System.Object.ReferenceEquals( str, additionalReference ) // prints true printfn "%b" <| System.Object.ReferenceEquals( str, deepCopy ) // prints false
Give a code snippet in #F.23 This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty st...
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#Haskell
Haskell
module RSAMaker where import Data.Char ( chr )   encode :: String -> [Integer] encode s = map (toInteger . fromEnum ) s   rsa_encode :: Integer -> Integer -> [Integer] -> [Integer] rsa_encode n e numbers = map (\num -> mod ( num ^ e ) n ) numbers   rsa_decode :: Integer -> Integer -> [Integer] -> [Integer] rsa_deco...
Give a code snippet in #Haskell Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encrypti...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#11l
11l
F url_decode(s) V r = ‘’ V i = 0 L i < s.len I s[i] == ‘%’ [Byte] b L i < s.len & s[i] == ‘%’ i++ b.append(Int(s[i.+2], radix' 16)) i += 2 r ‘’= b.decode(‘utf-8’) E r ‘’= s[i] i++ R r   print(url_decode(‘http%3A%2F%...
Give a code snippet in #11l This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#SQL
SQL
  SELECT to_char( next_day( last_day( add_months( to_date(  :yr||'01','yyyymm' ),level-1))-7,'Fri') ,'yyyy-mm-dd Dy') lastfriday FROM dual CONNECT BY level <= 12;  
Give a code snippet in #SQL Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-0...
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...
#Python
Python
def remove_comments(line, sep): for s in sep: i = line.find(s) if i >= 0: line = line[:i] return line.strip()   # test print remove_comments('apples ; pears # and bananas', ';#') print remove_comments('apples ; pears # and bananas', '!')  
Give a code snippet in #Python 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/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#Stata
Stata
void gauss(real matrix a, real matrix b, real scalar det) { real scalar i,j,n,s real vector js   det = 1 n = rows(a) for (i=1; i<n; i++) { maxindex(abs(a[i::n,i]), 1, js=., .) j = js[1]+i-1 if (j!=i) { a[(i\j),i..n] = a[(j\i),i..n] b[(i\j),.] = b[(j\i),.] det = -det } for (j=i+1; j<=n; j++) { ...
Give a code snippet in #Stata Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#Go
Go
package main   import ( "fmt" "os"   "golang.org/x/crypto/ssh/terminal" )   func main() { w, h, err := terminal.GetSize(int(os.Stdout.Fd())) if err != nil { fmt.Println(err) return } fmt.Println(h, w) }
Give a code snippet in #Go Determine the height and width of the terminal, and store this information into variables for subsequent use.
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Exam...
#11l
11l
V neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] [Int] exists V lastNumber = 0 V wid = 0 V hei = 0   F find_next(pa, x, y, z) L(i) 4 V a = x + :neighbours[i][0] V b = y + :neighbours[i][1] I a C -1 <.< :wid & b C -1 <.< :hei I pa[a][b] == z R (a, b) R (-1, -1)   F find_solu...
Give a code snippet in #11l Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end nod...
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...
#ALGOL_68
ALGOL 68
MODE RANGE = STRUCT(INT lwb, upb);   PROC sum = (PROC (INT)LONG REAL f, RANGE range)LONG REAL:( LONG REAL sum := LENG 0.0; FOR i FROM lwb OF range TO upb OF range DO sum := sum + f(i) OD; sum );   test:( RANGE range = (1,1000); PROC f = (INT x)LONG REAL: LENG REAL(1) / LENG REAL(x)**2; print(("Sum of...
Give a code snippet in #ALGOL_68 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/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (F, ARG); DECLARE F BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PUT$CHAR: PROCEDURE (CH); DECLARE CH BYTE; CALL BDOS(2,CH); END PUT$CHAR;   DECLARE MAXIMUM LITERALLY '120';   PRINT4: PROCEDURE (N); DECLARE (N, MAGN, Z) BYTE; CALL PUT$CHAR(' '); MAGN...
Give a code snippet in #PL.2FM A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task ...
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
#IS-BASIC
IS-BASIC
PRINT "Hello world!"
Give a code snippet in #IS-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/Standard erro...
christopher/rosetta-code