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/Simple_turtle_graphics
Simple turtle graphics
The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart. See imag...
#Logo
Logo
to rectangle :width :height repeat 2 [ forward :height left 90 forward :width left 90 ] end   to square :size rectangle size size end   to triangle :size repeat 3 [ forward size right 120 ] end   to house :size left 90 square size ...
Give a code snippet in #Logo The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#F.23
F#
open System   [ 2008 .. 2121 ] |> List.choose (fun y -> if DateTime(y,12,25).DayOfWeek = DayOfWeek.Sunday then Some(y) else None) |> printfn "%A"
Give a code snippet in #F.23 A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Ultra_useful_primes
Ultra useful primes
An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime. k must always be an odd number since 2 to any power is always even. Task Find and show here, on this page, the first 10 elements of the sequence. Stretch Find and show the next sev...
#Arturo
Arturo
ultraUseful: function [n][ k: 1 p: (2^2^n) - k while ø [ if prime? p -> return k p: p-2 k: k+2 ] ]   print [pad "n" 3 "|" pad.right "k" 4] print repeat "-" 10 loop 1..10 'x -> print [(pad to :string x 3) "|" (pad.right to :string ultraUseful x 4)]
Give a code snippet in #Arturo An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime. k must always be an odd number since 2 to any power is always even. Task Find and show here, on this page, the first 10 elements of the sequence. Stre...
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...
#C.2B.2B
C++
  /* Michal Sikorski 06/07/2016 */ #include <cstdlib> #include <iostream> #include <windows.h> #include <string.h> using namespace std; int main(int argc, char *argv[]) { string inpt; char ascii[28] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ", lwcAscii[28] = " abcdefghijklmnopqrstuvwxyz"; string morse[27] = {" ", ".- ...
Give a code snippet in #C.2B.2B 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 igno...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#ERRE
ERRE
!-------------------------------------------- ! TRIS.R : gioca a tris contro l'operatore !-------------------------------------------- PROGRAM TRIS DIM TRIS%[9],T1%[9],PIECES$[3] !$SEGMENT=$B800 !$INCLUDE="PC.LIB" PROCEDURE DELAY(COUNT%) FOR Z%=1 TO COUNT DO END FOR END PROCEDURE PROCEDURE SET_BOARD ! ! Diseg...
Give a code snippet in #ERRE Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™,...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#PL.2FI
PL/I
*process m or(!) s attributes source; cb: Proc Options(main); /* PL/I program to check for balanced brackets [] ******************** * 07.12.2013 Walter Pachl translated from REXX Version 2 *********************************************************************/ Dcl v Char(20) Var; Dcl (i,j) Bin Fixed(31); Dcl r B...
Give a code snippet in #PL.2FI Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#BBC_BASIC
BBC BASIC
target$ = "METHINKS IT IS LIKE A WEASEL" parent$ = "IU RFSGJABGOLYWF XSMFXNIABKT" mutation_rate = 0.5 children% = 10   DIM child$(children%)   REPEAT bestfitness = 0 bestindex% = 0 FOR index% = 1 TO children% child$(index%) = FNmutate(parent$, mutati...
Give a code snippet in #BBC_BASIC Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Lua
Lua
require "iuplua"   dlg = iup.dialog{iup.label{title="Goodbye, World!"}; title="test"} dlg:show()   if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then iup.MainLoop() end
Give a code snippet in #Lua Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#SequenceL
SequenceL
even(x) := x mod 2 = 0; odd(x) := x mod 2 = 1;
Give a code snippet in #SequenceL Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Ada
Ada
with Ada.Containers.Vectors; with Ada.Text_IO; with Ada.Unchecked_Conversion;   procedure VLQ is   package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);   type Byte is mod 2**8;   package Byte_IO is new Ada.Text_IO.Modular_IO (Byte);   type Int7 is mod 2**7;   package Int7_IO is new Ada.Text_IO.Modular...
Give a code snippet in #Ada Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert th...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#PicoLisp
PicoLisp
  (scl 8) (load "@lib/math.l")   (setq LN2 0.693147180559945309417)   (de tabulate-chars (Str) (let Map NIL (for Ch (chop Str) (if (assoc Ch Map) (con @ (inc (cdr @))) (setq Map (cons (cons Ch 1) Map)))) Map))   (de entropy (Str) (let ( Sz (length Str) Hist...
Give a code snippet in #PicoLisp Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary...
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...
#Maple
Maple
> for n in [ 1666, 1990, 2008 ] do printf( "%d\t%s\n", n, convert( n, 'roman' ) ) end: 1666 MDCLXVI 1990 MCMXC 2008 MMVIII
Give a code snippet in #Maple 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 val...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Lingo
Lingo
put integer("123")+1 -- 124
Give a code snippet in #Lingo Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Haskell
Haskell
import Data.List (intersperse, intercalate) import qualified Data.Set as S   consolidate :: Ord a => [S.Set a] -> [S.Set a] consolidate = foldr comb [] where comb s_ [] = [s_] comb s_ (s:ss) | S.null (s `S.intersection` s_) = s : comb s_ ss | otherwise = comb (s `S.union` s_) ss   -- TESTS ---...
Give a code snippet in #Haskell Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Scala
Scala
object ColouredText extends App { val ESC = "\u001B" val (normal, bold, blink, black, white) = (ESC + "[0", ESC + "[1" , ESC + "[5" // not working on my machine , ESC + "[0;40m" // black background , ESC + "[0;37m" // normal white foreground )   print(s"${ESC}c") // clear terminal first ...
Give a code snippet in #Scala Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Ioke
Ioke
use("benchmark")   func = method((1..50000) reduce(+))   Benchmark report(1, 1, func)
Give a code snippet in #Ioke Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between ...
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.
#Prolog
Prolog
  ?- append([1,2,3],[4,5,6],R). R = [1, 2, 3, 4, 5, 6].  
Give a code snippet in #Prolog 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/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#PHP
PHP
<?php print_r(array_count_values(str_split(file_get_contents($argv[1])))); ?>
Give a code snippet in #PHP Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assig...
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...
#Vedit_macro_language
Vedit macro language
#1 = CP IT("alphaBETA") Case_Upper_Block(#1, CP) Case_Lower_Block(#1, CP)
Give a code snippet in #Vedit_macro_language 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Nim
Nim
import rdstdin, strutils   let str = readLineFromStdin "Input a string: " let num = parseInt(readLineFromStdin "Input an integer: ")
Give a code snippet in #Nim User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Stata
Stata
mata function pow(a, n) { x = a for(p=1; n>0; n=floor(n/2)) { if(mod(n,2)==1) p = p*x x = x*x } return(p) } end
Give a code snippet in #Stata Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Free_Pascal
Free Pascal
program Stack; {$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF} {$ASSERTIONS ON} uses Generics.Collections;   var lStack: TStack<Integer>; begin lStack := TStack<Integer>.Create; try lStack.Push(1); lStack.Push(2); lStack.Push(3); Assert(lStack.Peek = 3); // 3 shoul...
Give a code snippet in #Free_Pascal Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#Scheme
Scheme
$ include "seed7_05.s7i";   const proc: brainF (in string: source, inout file: input, inout file: output) is func local var array char: memory is 100000 times '\0;'; var integer: dataPointer is 50000; var integer: instructionPointer is 1; var integer: nestingLevel is 0; begin while instructionPo...
Give a code snippet in #Scheme Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly imple...
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...
#PicoLisp
PicoLisp
: (length '(apple orange)) -> 2 :
Give a code snippet in #PicoLisp 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 fr...
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
#Cduce
Cduce
print "Hello world!";;
Give a code snippet in #Cduce 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/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Go
Go
package main   import ( "fmt" "io" "log" "os"   "github.com/stacktic/ftp" )   func main() { // Hard-coded demonstration values const ( hostport = "localhost:21" username = "anonymous" password = "anonymous" dir = "pub" file = "somefile.bin" )   conn, err := ftp.Connect(hostport) if err != n...
Give a code snippet in #Go Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#PL.2FI
PL/I
  /* BITMAP FILE: read in a file in PPM format, P6 (binary). 14/5/2010 */ test: procedure options (main); declare (m, n, max_color, i, j) fixed binary (31); declare ch character (1), ID character (2); declare 1 pixel union, 2 color bit(24) aligned, 2 primary_colors, 3 R c...
Give a code snippet in #PL.2FI Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grays...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Scala
Scala
object CopyStdinToStdout extends App { io.Source.fromInputStream(System.in).getLines().foreach(println) }
Give a code snippet in #Scala Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
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...
#C.23
C#
using System; using System.Collections; using System.Collections.Generic;   namespace SieveOfEratosthenes { class Program { static void Main(string[] args) { int maxprime = int.Parse(args[0]); var primelist = GetAllPrimesLessThan(maxprime); foreach (int prime ...
Give a code snippet in #C.23 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/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Vlang
Vlang
import rand import rand.seed   fn main() { rand.seed(seed.time_seed_array(2)) for { a := rand.intn(20)? println(a) if a == 10 { break } b := rand.intn(20)? println(b) } }
Give a code snippet in #Vlang Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. ...
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...
#ReScript
ReScript
let m = []   for _ in 0 to 9 { let n = [] for _ in 0 to 9 { let _ = Js.Array2.push(n, 1 + Js.Math.random_int(0, 20)) } let _ = Js.Array2.push(m, n) }   try { for i in 0 to 9 { for j in 0 to 9 { Js.log(m[i][j]) if m[i][j] == 20 { raise(Exit) } } } } catch { | Exit => Js.log("stop") }
Give a code snippet in #ReScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Run_BASIC
Run BASIC
a$ = httpGet$("http://www.puzzlers.org/pub/wordlists/unixdict.txt") dim theWord$(30000) dim ssWord$(30000)   c10$ = chr$(10) i = 1 while instr(a$,c10$,i) <> 0 j = instr(a$,c10$,i) ln = j - i again = 1 sWord$ = mid$(a$,i,j-i) n = n + 1 theWord$(n) = sWord$   while again = 1 again = 0 for kk = 1...
Give a code snippet in #Run_BASIC Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. ...
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 |...
#Perl
Perl
sub test_num { my $f = shift; my $s = shift; if ($f < $s){ return -1; # returns -1 if $f is less than $s } elsif ($f > $s) { return 1; # returns 1 if $f is greater than $s } elsif ($f == $s) { # = operator is an assignment # == operator is a numeric comparison return 0; # retu...
Give a code snippet in #Perl 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 C...
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...
#AutoHotkey
AutoHotkey
If !pToken := Gdip_Startup() { MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system ExitApp }   OnExit, Exit gdip1()   incr := 0 π := 3.141592653589793 loop { incr := Mod(incr + 0.05, 360) x1 := Width/2 y1 := Height/2 length := 5 angle := incr ...
Give a code snippet in #AutoHotkey 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list of   precedence   and   associativity...
#Lua
Lua
42 :my-var 42 "my-var" define
Give a code snippet in #Lua This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list of   pre...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#Julia
Julia
Welcome to Kotlin version 1.1.1 (JRE 1.8.0_121-b13) Type :help for help, :quit for quit >>> println("Look no main!") Look no main! >>> :quit
Give a code snippet in #Julia Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages m...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Racket
Racket
  #lang racket (require math) (define in (open-input-file "function-frequency.rkt")) (void (read-language in)) (define s-exprs (for/list ([s (in-port read in)]) s)) (define symbols (filter symbol? (flatten s-exprs))) (define counts (sort (hash->list (samples->hash symbols)) >= #:key cdr)) (take counts (min 10 (length ...
Give a code snippet in #Racket Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runt...
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...
#Kotlin
Kotlin
// Version 1.3.21   const val MAX = 15   fun countDivisors(n: Int): Int { var count = 0 var i = 1 while (i * i <= n) { if (n % i == 0) { count += if (i == n / i) 1 else 2 } i++ } return count }   fun main() { var seq = IntArray(MAX) println("The first $MAX...
Give a code snippet in #Kotlin 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 S...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Nemerle
Nemerle
null
Give a code snippet in #Nemerle Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Date-Format.   DATA DIVISION. WORKING-STORAGE SECTION.   01 Days-Area. 03 Days-Data. 05 FILLER PIC X(9) VALUE "Monday". 05 FILLER PIC X(9) VALUE "Tuesday". 05 FILLER PIC X(9) VALUE "Wedne...
Give a code snippet in #COBOL This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
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...
#PL.2FI
PL/I
  * PROCESS GONUMBER, MARGINS(1,72), NOINTERRUPT, MACRO; TEST:PROCEDURE OPTIONS(MAIN); DECLARE SYSIN FILE STREAM INPUT, DRAGON FILE STREAM OUTPUT PRINT, SYSPRINT FILE STREAM OUTPUT PRINT; DECLARE (MIN,MAX,MOD,INDEX,LENGTH,SUBSTR,VERIFY,TRANSLATE) BUILTIN; DECLARE (COMPLEX,SQRT,REAL,IMAG,ATAN,SIN,EXP,COS,ABS) B...
Give a code snippet in #PL.2FI 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 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Erlang
Erlang
  -include("my_header.hrl"). % Includes the file at my_header.erl  
Give a code snippet in #Erlang Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
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 ...
#AutoHotkey
AutoHotkey
JortSort(Array){ sorted:=[] for index, val in Array sorted[val]:=1 for key, val in sorted if (key<>Array[A_Index]) return 0 return 1 }
Give a code snippet in #AutoHotkey 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 | Qui...
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...
#Pascal
Pascal
Program ArithmeticGeometricMean;   uses gmp;   procedure agm (in1, in2: mpf_t; var out1, out2: mpf_t); begin mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); end;   const nl = chr(13)+chr(10); var x0, y0, resA, resB: mpf_t; i: integer; begin mpf_se...
Give a code snippet in #Pascal 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Standard_ML
Standard ML
val seed = 0w42; val gen = Rand.mkRandom seed; fun random_gaussian () = 1.0 + Math.sqrt (~2.0 * Math.ln (Rand.norm (gen ()))) * Math.cos (2.0 * Math.pi * Rand.norm (gen ())); val a = List.tabulate (1000, fn _ => random_gaussian ());
Give a code snippet in #Standard_ML Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. R...
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,...
#Ol
Ol
  ; making a vector > #(1 2 3 4 5) #(1 2 3 4 5)   ; making a vector in a functional way > (vector 1 2 3 4 5) #(1 2 3 4 5)   ; another functional vector making way > (make-vector '(1 2 3 4 5)) #(1 2 3 4 5)   ; the same as above functional vector making way > (list->vector '(1 2 3 4 5)) #(1 2 3 4 5)   ; modern syntax of ...
Give a code snippet in #Ol 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Icon_and_Unicon
Icon and Unicon
procedure main() f := open("input.txt","r") | stop("cannot open file ",fn) while line := read(f) close(f) end
Give a code snippet in #Icon_and_Unicon Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class Utils.Net.RosettaCode [ Abstract ] {   ClassMethod GetTopLanguages(pHost As %String = "", pPath As %String = "", pTop As %Integer = 10) As %Status { // check input parameters If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { Quit $$$ERROR($$$GeneralError, "Invalid host n...
Give a code snippet in #Cach.C3.A9_ObjectScript Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Ursala
Ursala
#import std #import int   #executable&   main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L
Give a code snippet in #Ursala A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separat...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#LotusScript
LotusScript
  Sub Click(Source As Button) 'Create timestamp as of now Dim timeStamp As NotesDateTime Set timeStamp = New NotesDateTime ( Now )   'Assign epoch start time to variable Dim epochTime As NotesDateTime Set epochTime = New NotesDateTime ( "01/01/1970 00:00:00 AM GMT" ) ''' These two commands only to get epoc...
Give a code snippet in #LotusScript Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind...
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 ...
#COBOL
COBOL
*> TECTONICS *> wget http://wiki.puzzlers.org/pub/wordlists/unixdict.txt *> or visit https://sourceforge.net/projects/souptonuts/files *> or snag ftp://ftp.openwall.com/pub/wordlists/all.gz *> for a 5 million all language word file (a few phrases) *> cobc -xj anagrams.co...
Give a code snippet in #COBOL 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Smalltalk
Smalltalk
(FileDirectory on: 'c:\') newFileNamed: 'output.txt'; createDirectory: 'docs'.
Give a code snippet in #Smalltalk In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Fermat
Fermat
heap:=12; while heap>0 do  !!('There are ',heap,' tokens left. How many do you want to take?');  ?take; while take<1 or take>3 or take>heap do  !!('You cannot take that number. Choose again.');  ?take; od;  !!('On my turn I will take ',4-take,' tokens.'); heap:-(4); od;   !!('I got th...
Give a code snippet in #Fermat Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes...
christopher/rosetta-code
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cyli...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var Rand = Random.new()   class Revolver { construct new() { _cylinder = List.filled(6, false) }   rshift() { var t = _cylinder[-1] for (i in 4..0) _cylinder[i+1] = _cylinder[i] _cylinder[0] = t }   unload() { ...
Give a code snippet in #Wren The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet....
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...
#Run_BASIC
Run BASIC
a$ = "ha " for i = 1 to 5 a1$ = a1$ + a$ next i a$ = a1$ print a$
Give a code snippet in #Run_BASIC 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("*",...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#68000_Assembly
68000 Assembly
PrintString: ;input: A0 = source address ;outputs to screen. MOVE.B (A0)+,D0 BEQ Terminated JSR PrintChar BRA PrintString Terminated: ; If this routine did in fact put a new line by default, it would do so here with the following: ; MOVE.B #13,D0  ;13 is ascii for Carriage Return (moves cursor back to beginning of row)...
Give a code snippet in #68000_Assembly Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello wo...
christopher/rosetta-code
http://rosettacode.org/wiki/ASCII_art_diagram_converter
ASCII art diagram converter
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RC...
#Nim
Nim
import macros import strutils import tables   const Diagram = """ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--...
Give a code snippet in #Nim Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program dateFormat64.s */     /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstante...
Give a code snippet in #AArch64_Assembly This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
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 ...
#PARI.2FGP
PARI/GP
error("Goodbye, World!")
Give a code snippet in #PARI.2FGP 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Softbridge_BASIC
Softbridge BASIC
  Function Fibonacci(n) x = 0 y = 1 i = 0 n = ABS(n) If n < 2 Then Fibonacci = n Else Do Until (i = n) sum = x+y x=y y=sum i=i+1 Loop Fibonacci = x End If   End Function  
Give a code snippet in #Softbridge_BASIC The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive so...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#FreeBASIC
FreeBASIC
Dim Shared As Long lastsquare, nextsquare, lastcube, midcube, nextcube   Function squares() As Long lastsquare += nextsquare nextsquare += 2 squares = lastsquare End Function   Function cubes() As Long lastcube += nextcube nextcube += midcube midcube += 6 cubes = lastcube End Function   last...
Give a code snippet in #FreeBASIC A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so t...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#11l
11l
F knuth_shuffle(&x) L(i) (x.len - 1 .< 0).step(-1) V j = random:(0..i) swap(&x[i], &x[j])   V x = Array(0..9) knuth_shuffle(&x) print(‘shuffled: ’x)
Give a code snippet in #11l The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Raku
Raku
sub function { 2 * $^x + 3 }; my @array = 1 .. 5;   # via map function .say for map &function, @array;   # via map method .say for @array.map(&function);   # via for loop for @array { say function($_); }   # via the "hyper" metaoperator and method indirection say @array».&function;   # we neither need a variable fo...
Give a code snippet in #Raku Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_n-step_number_sequences
Padovan n-step number sequences
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n ==...
#C
C
#include <stdio.h>   void padovanN(int n, size_t t, int *p) { int i, j; if (n < 2 || t < 3) { for (i = 0; i < t; ++i) p[i] = 1; return; } padovanN(n-1, t, p); for (i = n + 1; i < t; ++i) { p[i] = 0; for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j]; } }   int main...
Give a code snippet in #C As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n,...
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...
#Java
Java
for(int i = 2; i <= 8;i += 2){ System.out.print(i + ", "); } System.out.println("who do we appreciate?");
Give a code snippet in #Java 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/Incr...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#zkl
zkl
fcn sortByColumn(list,col) { list.sort('wrap(city1,city2){ city1[col]<city2[col] }) }
Give a code snippet in #zkl Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#OCaml
OCaml
module FIFO : sig type 'a fifo val empty: 'a fifo val push: fifo:'a fifo -> item:'a -> 'a fifo val pop: fifo:'a fifo -> 'a * 'a fifo val is_empty: fifo:'a fifo -> bool end = struct type 'a fifo = 'a list * 'a list let empty = [], [] let push ~fifo:(input,output) ~item = (item::input,output) let is_emp...
Give a code snippet in #OCaml 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#Racket
Racket
#lang racket   (define probs# (make-hash))   (define (NdD n d) (hash-ref! probs# (cons n d) (λ () (cond [(= n 0) ; every chance of nothing! (hash 0 1)] [else (for*/fold ((hsh (hash))) (((i p) (in-hash (NdD (sub1 n) d))) (r (in-range 1 (+ d 1)))) (hash-update hsh (+ r...
Give a code snippet in #Racket Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The playe...
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...
#Python
Python
def caesar(s, k, decode = False): if decode: k = 26 - k return "".join([chr((ord(i) - 65 + k) % 26 + 65) for i in s.upper() if ord(i) >= 65 and ord(i) <= 90 ])   msg = "The quick brown fox jumped over the lazy dogs" print msg enc = caesar(msg, 11) print enc print caesar(enc, 11, decode = True)
Give a code snippet in #Python 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#tr
tr
echo 'Hello,How,Are,You,Today' | tr ',' '.'
Give a code snippet in #tr Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks relat...
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...
#GAP
GAP
# Built-in Combinations([1, 2, 3]); # [ [ ], [ 1 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], [ 2 ], [ 2, 3 ], [ 3 ] ]   # Note that it handles duplicates Combinations([1, 2, 3, 1]); # [ [ ], [ 1 ], [ 1, 1 ], [ 1, 1, 2 ], [ 1, 1, 2, 3 ], [ 1, 1, 3 ], [ 1, 2 ], [ 1, 2, 3 ], [ 1, 3 ], ...
Give a code snippet in #GAP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#C
C
  #include <stdio.h> #include <stdlib.h> #define otherwise do { register int _o = 2; do { switch (_o) { case 1: #define given(Mc)  ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)     int foo() { return 1; }   main() { int a = 0;   otherwise a = 4 given (foo(...
Give a code snippet in #C Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the stateme...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP // saving 664,578 primes (vs generating them on the fly) seems a bit overkill   fcn safePrime(p){ ((p-1)/2).probablyPrime() } // p is a BigInt prime   fcn safetyList(sN,nsN){ p,safe,notSafe := BI(2),List(),List(); do{ if(safePrime(p)) safe.append(p.toInt()) el...
Give a code snippet in #zkl Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't ...
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...
#Phix
Phix
with javascript_semantics include mpfr.e constant lim = 100, lim1 = lim+1, last = 12 sequence l = repeat(0,lim1) for n=1 to lim1 do l[n] = mpz_inits(lim1) mpz_set_si(l[n][n],1) if n!=2 then mpz_fac_ui(l[n][2],n-1) end if end for mpz {t, m100} = mpz_inits(2) for n=1 to lim do...
Give a code snippet in #Phix 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#PureBasic
PureBasic
FileName$ = OpenFileRequester("","foo.txt","*.txt",0)   If ReadFile(0, FileName$) ; use ReadFile instead of OpenFile to include read-only files BOMformat = ReadStringFormat(0) ; reads the BOMformat (Unicode, UTF-8, ASCII, ...) While Not Eof(0) line$ = ReadString(0, BOMformat) DoSomethingWithTheLin...
Give a code snippet in #PureBasic Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Tcl
Tcl
proc do_fwd_diff {list} { set previous [lindex $list 0] set new [list] foreach current [lrange $list 1 end] { lappend new [expr {$current - $previous}] set previous $current } return $new }   proc fwd_diff {list order} { while {$order >= 1} { set list [do_fwd_diff $list] ...
Give a code snippet in #Tcl Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Nim
Nim
import strutils   proc encrypt(msg, key: string): string = var pos = 0 for c in msg: if c in Letters: result.add chr(((ord(key[pos]) + ord(c.toUpperAscii)) mod 26) + ord('A')) pos = (pos + 1) mod key.len   proc decrypt(msg, key: string): string = var pos = 0 for c in msg: result.add chr(((26...
Give a code snippet in #Nim Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.)...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#IS-BASIC
IS-BASIC
100 IF VERNUM<2.1 THEN PRINT "Version is too old.":STOP 110 WHEN EXCEPTION USE ERROR 120 PRINT ABS(BLOOP) 130 END WHEN 140 HANDLER ERROR 150 PRINT EXSTRING$(EXTYPE) 160 CONTINUE 170 END HANDLER
Give a code snippet in #IS-BASIC Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Befunge
Befunge
0110"txt.tupni"#@i10"txt.tuptuo"#@o@
Give a code snippet in #Befunge File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#Nim
Nim
# Longest common substring.   import sequtils   func lcs(a, b: string): string = var lengths = newSeqWith(a.len, newSeq[int](b.len)) var greatestLength = 0 for i, x in a: for j, y in b: if x == y: lengths[i][j] = if i == 0 or j == 0: 1 else: lengths[i - 1][j - 1] + 1 if lengths[i][j] > g...
Give a code snippet in #Nim Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutiv...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Free_Pascal
Free Pascal
  program RandomNumbers; // Program to demonstrate the Random and Randomize functions. var RandomInteger: integer; RandomFloat: double; begin Randomize; // generate a new sequence every time the program is run RandomFloat := Random(); // 0 <= RandomFloat < 1 Writeln('Random float between 0 and 1: ', Ran...
Give a code snippet in #Free_Pascal The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the al...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Prolog
Prolog
% We need operators :- op(700, xfx, <-). :- op(450, xfx, ..). :- op(1100, yfx, &).   % use for explicit list usage my_bind(V, [H|_]) :- V = H. my_bind(V, [_|T]) :- my_bind(V, T).   % we need to define the intervals of numbers Vs <- M..N :- integer(M), integer(N), M =< N, between(M, N, Vs).   % for explicit l...
Give a code snippet in #Prolog A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and t...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#BaCon
BaCon
CLEAR
Give a code snippet in #BaCon Task Clear the terminal window.
christopher/rosetta-code
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...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { intArrayOf(4, 5, 6).forEach lambda@ { if (it == 5) return@lambda println(it) } println() loop@ for (i in 0 .. 3) { for (j in 0 .. 3) { if (i + j == 4) continue@loop if (i + j == 5) break@loop p...
Give a code snippet in #Kotlin 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Julia
Julia
  n = 1024   while n > 0 println(n) n >>= 1 end  
Give a code snippet in #Julia Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwar...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Sidef
Sidef
var (a, b) = (-5, 7); say eval '(a * b).abs'; # => 35 say (a * b -> abs); # => 35
Give a code snippet in #Sidef Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applica...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#AWK
AWK
$ awk 'BEGIN{print systime(),strftime()}'
Give a code snippet in #AWK Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Da...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#AutoHotkey
AutoHotkey
#NoEnv SetBatchLines, -1 #SingleInstance, Force   ; Greatest common divisor, from http://rosettacode.org/wiki/Greatest_common_divisor#AutoHotkey gcd(a,b) { Return b=0 ? Abs(a) : Gcd(b,mod(a,b)) }   count_triples(max) { primitives := 0, triples := 0, m := 2 while m <= (max / 2)**0.5 { n := mod(m, 2) + 1 ,p := 2*...
Give a code snippet in #AutoHotkey A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Icon_and_Unicon
Icon and Unicon
procedure retList() # returns as ordered list return [1,2,3] end   procedure retSet() # returns as un-ordered list insert(S := set(),3,1,2) return S end   procedure retLazy() # return as a generator suspend 1|2|3 end   procedure retTable() # return as a table T := table() T["A"] := 1 ...
Give a code snippet in #Icon_and_Unicon Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#JavaScript
JavaScript
/** * @typedef {{ * x: (!number), * y: (!number) * }} */ let pointType;   /** * @param {!Array<pointType>} l * @param {number} eps */ const RDP = (l, eps) => { const last = l.length - 1; const p1 = l[0]; const p2 = l[last]; const x21 = p2.x - p1.x; const y21 = p2.y - p1.y;   const [dMax, x] = ...
Give a code snippet in #JavaScript Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Fortran
Fortran
  SUBROUTINE RAKE(IN,M,X,WAY) !Casts forth text in fixed-width columns. Collates column widths so that each column is wide enough for its widest member. INTEGER IN !Fingers the input file. INTEGER M !Maximum record length thereof. CHARACTER*1 X !The delimiter, possibly a comma. INTE...
Give a code snippet in #Fortran Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either l...
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 ...
#GML
GML
  //Setting a var from an argument passed to the script var str; str = argument0 //Takes out all spaces/anything that is not a letter or a number and turns uppercase letters to lowercase str = string_lettersdigits(string_lower(string_replace(str,' ',''))); var inv; inv = ''; //for loop that reverses the sequence var i;...
Give a code snippet in #GML A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#Scala
Scala
//List of perfect totients def isPerfectTotient(num: Int): Boolean = LazyList.iterate(totient(num))(totient).takeWhile(_ != 1).foldLeft(0L)(_+_) + 1 == num def perfectTotients: LazyList[Int] = LazyList.from(3).filter(isPerfectTotient)   //Totient Function @tailrec def scrub(f: Long, num: Long): Long = if(num%f == 0) sc...
Give a code snippet in #Scala Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
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...
#zkl
zkl
ls -ld input.txt docs output.txt mydocs ls: cannot access 'output.txt': No such file or directory ls: cannot access 'mydocs': No such file or directory drwxr-xr-x 2 craigd craigd 4096 Aug 10 16:24 docs -rw-r--r-- 1 craigd craigd 0 Aug 10 16:24 input.txt $ zkl zkl: File.rename("input.txt","output.txt") True zkl: File...
Give a code snippet in #zkl 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 righ...
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.
#LFE
LFE
  > (++ '(1 2 3) '(4 5 6)) (1 2 3 4 5 6) > (: lists append '(1 2 3) '(4 5 6)) (1 2 3 4 5 6)  
Give a code snippet in #LFE 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/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Phix
Phix
procedure Repeat(integer rid, integer n) for i=1 to n do rid() end for end procedure procedure Hello() ?"Hello" end procedure Repeat(Hello,5)
Give a code snippet in #Phix Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclops_numbers
Cyclops numbers
A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10. There are many different ...
#F.23
F#
  // Cyclop numbers. Nigel Galloway: June 25th., 2021 let rec fG n g=seq{yield! g|>Seq.collect(fun i->g|>Seq.map(fun g->n*i+g)); yield! fG(n*10)(fN g)} let cyclops=seq{yield 0; yield! fG 100 [1..9]} let primeCyclops,blindCyclops=cyclops|>Seq.filter isPrime,Seq.zip(fG 100 [1..9])(fG 10 [1..9])|>Seq.filter(fun(n,g)->isPr...
Give a code snippet in #F.23 A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base ...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Java
Java
import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Timer; import java.util.TimerTask; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants;   public class Rotate {   privat...
Give a code snippet in #Java Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task dem...
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...
#Logo
Logo
to about :a :b output and [:a - :b < 1e-15] [:a - :b > -1e-15] end to agm :arith :geom if about :arith :geom [output :arith] output agm (:arith + :geom)/2 sqrt (:arith * :geom) end   show agm 1 1/sqrt 2  
Give a code snippet in #Logo 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Elena
Elena
//single line comment   /*multiple line comment*/
Give a code snippet in #Elena Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code