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/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#C.2B.2B
C++
#include <cmath>   bool is_prime(unsigned int n) { if (n <= 1) return false; if (n == 2) return true; for (unsigned int i = 2; i <= sqrt(n); ++i) if (n % i == 0) return false; return true; }
Give a code snippet in #C.2B.2B Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loo...
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
#XLISP
XLISP
(DISPLAY "Hello world!") (NEWLINE)
Give a code snippet in #XLISP 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/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Go
Go
package main   import ( "fmt" "math/big" )   var m, n, z big.Int   func init() { m.SetString("2562047788015215500854906332309589561", 10) n.SetString("6795454494268282920431565661684282819", 10) }   func main() { fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n)) }
Give a code snippet in #Go Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has bo...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
Find palindromic numbers in both binary and ternary bases
Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base 2   base 3   Display   0   ...
#REXX
REXX
/*REXX program finds numbers that are palindromic in both binary and ternary. */ digs=50; numeric digits digs /*biggest known B2B3 palindrome: 44 dig*/ parse arg maxHits .; if maxHits=='' then maxHits=6 /*use six as a limit.*/ hits=0; #= 'fiat' ...
Give a code snippet in #REXX Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Batch_File
Batch File
>set r=Rosetta   >set c=Code   >set s=:   >echo %r%%s%%s%%c% Rosetta::Code   >
Give a code snippet in #Batch_File Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a sh...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' This example is taken directly from the FB documentation (see [http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgFiledatetime])   #include "vbcompat.bi" '' to use Format function   Dim filename As String, d As Double   Print "Enter a filename: " Line Input filename   If FileExists(filename) Then...
Give a code snippet in #FreeBASIC Task Get and set the modification time of a file.
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
#PILOT
PILOT
C :z=0  :n=3 *num C :s=0  :x=n *perfect C :t=0  :i=1 *totient C :a=x  :b=i *gcd C :c=a-b*(a/b)  :a=b  :b=c J (b>0):*gcd C (a=1):t=t+1 C :i=i+1 J (i<=x-1):*totient C :x=t  :s=s+x J (x<>1):*perfect T (s=n):#n C (s=n):z=z+1 C :n=n+2 J (z<20):*num E :
Give a code snippet in #PILOT 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/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example of Currying in a specific la...
#PowerShell
PowerShell
  function Add($x) { return { param($y) return $y + $x }.GetNewClosure() }  
Give a code snippet in #PowerShell This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#LiveCode
LiveCode
put max(2,3,6,7,4,1)
Give a code snippet in #LiveCode Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
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) ...
#Go
Go
package main   import ( "bytes" "fmt" "math/rand" "time" )   func init() { rand.Seed(time.Now().UnixNano()) }   func generate(n uint) string { a := bytes.Repeat([]byte("[]"), int(n)) for i := len(a) - 1; i >= 1; i-- { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } re...
Give a code snippet in #Go 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...
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...
#R
R
m <- 10 n <- 10 mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat done <- FALSE for(i in seq_len(m)) { for(j in seq_len(n)) { cat(mat[i,j]) if(mat[i,j] == 20) { done <- TRUE break } cat(", ") } if(done) { cat("\n") break } }
Give a code snippet in #R 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#Futhark
Futhark
  import "futlib/math"   fun main(as: [n]f64): f64 = f64.sqrt ((reduce (+) 0.0 (map (**2.0) as)) / f64(n))  
Give a code snippet in #Futhark Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#J
J
32}._129}.a. !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ NB. A are the decimal ASCII values [A =: 10 |."1 ] 12 ": |: _16 [\ 32 }. i. 128 32 48 64 80 96 112 33 49 65 81 ...
Give a code snippet in #J Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I bef...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance/Alignment
Levenshtein distance/Alignment
The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used t...
#Haskell
Haskell
costs :: String -> String -> [[Int]] costs s1 s2 = reverse $ reverse <$> matrix where matrix = scanl transform [0 .. length s1] s2 transform ns@(n:ns1) c = scanl calc (n + 1) $ zip3 s1 ns ns1 where calc z (c1, x, y) = minimum [ y + 1, z + 1 , x + fromEnum (c1 ...
Give a code snippet in #Haskell The Levenshtein distance algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used ...
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#J
J
rollD5=: [: >: ] ?@$ 5: NB. makes a y shape array of 5s, "rolls" the array and increments. roll2xD5=: [: rollD5 2 ,~ */ NB. rolls D5 twice for each desired D7 roll (y rows, 2 cols) toBase10=: 5 #. <: NB. decrements and converts rows from base 5 to 10 keepGood=: #~ 21&> NB. compress out values n...
Give a code snippet in #J Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the fun...
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 ...
#Ra
Ra
  class FibonacciSequence **Prints the nth fibonacci number**   on start   args := program arguments   if args empty print .fibonacci(8)   else   try print .fibonacci(integer.parse(args[0]))   catch FormatException print to Console.error made !, "Input must be an integer" exit program with ...
Give a code snippet in #Ra 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 ge...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   module Main (main) where   import Data.Foldable (for_) import qualified Data.Text.Encoding as Text (encodeUtf8) import Ldap.Client (Attr(..), Filter(..)) import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)   main :: IO () main = do ...
Give a code snippet in #Haskell Make sure you Connect to Active Directory
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#360_Assembly
360 Assembly
* Temperature conversion 10/09/2015 TEMPERAT CSECT USING TEMPERAT,R15 LA R4,1 i=1 LA R5,TT @tt(1) LA R6,IDE @ide(1) LOOPI CH R4,=AL2((T-TT)/8) do i=1 to hbound(tt) BH ELOOPI ZAP T,0(8,R5) ...
Give a code snippet in #360_Assembly There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to ...
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...
#Modula-3
Modula-3
MODULE Quad EXPORTS Main;   IMPORT IO, Fmt, Math;   TYPE Roots = ARRAY [1..2] OF LONGREAL;   VAR r: Roots;   PROCEDURE Solve(a, b, c: LONGREAL): Roots = VAR sd: LONGREAL := Math.sqrt(b * b - 4.0D0 * a * c); x: LONGREAL; BEGIN IF b < 0.0D0 THEN x := (-b + sd) / (2.0D0 * a); RETURN Roots{x, c / ...
Give a code snippet in #Modula-3 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} . Yo...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Oberon-2
Oberon-2
  MODULE CSV2HTML; IMPORT Object, IO, IO:FileChannel, IO:TextRider, SB := ADT:StringBuffer, NPCT:Tools, NPCT:CGI:Utils, Ex := Exception, Out; VAR fileChannel: FileChannel.Channel; rd: TextRider.Reader; line: ARRAY 1024 OF CHAR; table: SB.StringBuffer; parts: ARRAY 2 OF STRING;   PROCEDU...
Give a code snippet in #Oberon-2 Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#Slate
Slate
26 printString &radix: 16 Integer readFrom: '1A' &radix: 16.
Give a code snippet in #Slate Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#ANSI_Standard_BASIC
ANSI Standard BASIC
100 FUNCTION multiFactorial (n, degree) 110 IF n < 2 THEN 120 LET multiFactorial = 1 130 EXIT FUNCTION 140 END IF 150 LET result = n 160 FOR i = n - degree TO 2 STEP -degree 170 LET result = result * i 180 NEXT i 190 LET multiFactorial = result 200 END FUNCTION 210 220 FOR degree =...
Give a code snippet in #ANSI_Standard_BASIC The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 )...
christopher/rosetta-code
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[a] a[1] = 1; a[n_?(GreaterThan[1])] := a[n] = 1/(2 Floor[a[n - 1]] + 1 - a[n - 1]) a /@ Range[20]   ClearAll[a] a = 1; n = 1; Dynamic[n] done = False; While[! done, a = 1/(2 Floor[a] + 1 - a); n++; If[a == 83116/51639, Print[n]; Break[]; ] ]
Give a code snippet in #Mathematica_.2F_Wolfram_Language The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf ...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Do[Print[Which[Mod[i, 15] == 0, "FizzBuzz", Mod[i, 5] == 0, "Buzz", Mod[i, 3] == 0, "Fizz", True, i]], {i, 100}]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three a...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Julia
Julia
  //version 1.0.1 import HTTP.URIs: escapeuri   dcd = "http://foo bar/" enc = escapeuri(dcd)   println(dcd, " => ", enc)  
Give a code snippet in #Julia Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
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 |...
#Lasso
Lasso
local(x = ', World!') #x->merge(1,'Hello') #x // Hello, World!
Give a code snippet in #Lasso 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/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Fortran
Fortran
program LargestProperDivisors implicit none integer i, lpd do 10 i=1, 100 write (*,'(I3)',advance='no') lpd(i) 10 if (i/10*10 .eq. i) write (*,*) end program   integer function lpd(n) implicit none integer n, i if (n .le. 1) then ...
Give a code snippet in #Fortran Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Fermat
Fermat
Func Lecm(a,b)=|a|*|b|/GCD(a,b).
Give a code snippet in #Fermat Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that ha...
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...
#Raku
Raku
my $n = 1024; while $n > 0 { say $n; $n div= 2 }
Give a code snippet in #Raku 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...
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...
#Nim
Nim
import algorithm   proc reverse(infile, outfile: string) =   let input = infile.open(fmRead) defer: input.close() let output = outfile.open(fmWrite) defer: output.close()   var buffer: array[80, byte] while not input.endOfFile: let countRead = input.readBytes(buffer, 0, 80) if countRead < 80: ...
Give a code snippet in #Nim 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#uBasic.2F4tH
uBasic/4tH
10 LET n=0: LET p=0 20 INPUT "Enter number: ";n 30 LET p=0 : IF n>1 THEN GOSUB 1000 40 IF p=0 THEN PRINT n;" is not prime!" 50 IF p#0 THEN PRINT n;" is prime!" 60 GOTO 10 1000 REM *************** 1001 REM * PRIME CHECK * 1002 REM *************** 1010 LET p=0 1020 IF (n%2)=0 THEN RETURN 1030 LET p=1 : PUSH n,0 : GOSUB 9...
Give a code snippet in #uBasic.2F4tH Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but othe...
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#J
J
input=: 1 :0 nlines=: 0 u;._2@fread 'input.txt' smoutput nlines )   output=: 3 :0 nlines=: nlines+1 smoutput y )
Give a code snippet in #J The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different n...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#TI-83_Hex_Assembly
TI-83 Hex Assembly
PROGRAM:HELLO :AsmPrgm :219F9D :EF0A45 :EF2E45 :C9 :48656C6C6F2C20576F726C642100
Give a code snippet in #TI-83_Hex_Assembly Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume...
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. ...
#Lua
Lua
-- Variadic, first argument is the value with which to populate the array. function multiArray (initVal, ...) local function copy (t) local new = {} for k, v in pairs(t) do if type(v) == "table" then new[k] = copy(v) else new[k] = v ...
Give a code snippet in #Lua 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/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Raku
Raku
.say for (0, { '0' ~ @_.join.trans( "01" => "10", :g) } ... *)[^8];
Give a code snippet in #Raku Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#Clojure
Clojure
(require 'clojure.repl)   (def start (System/nanoTime))   (defn shutdown [_] (println "Received INT after" (/ (- (System/nanoTime) start) 1e9) "seconds.") (System/exit 0))   (clojure.repl/set-break-handler! shutdown)   (doseq [i (range)] (prn i) (Thread/sleep 500))
Give a code snippet in #Clojure Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that t...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Visual_Basic_.NET
Visual Basic .NET
var assertEnabled = true   var assert = Fn.new { |cond| if (assertEnabled && !cond) Fiber.abort("Assertion failure") }   var x = 42 assert.call(x == 42) // fine assertEnabled = false assert.call(x > 42) // no error assertEnabled = true assert.call(x > 42) // error
Give a code snippet in #Visual_Basic_.NET Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Objeck
Objeck
bundle Default { class MyClass { @var : Int;   New() { }   method : public : SomeMethod() ~ Nil { @var := 1; }   method : public : SetVar(var : Int) ~ Nil { @var := var; }   method : public : GetVar() ~ Int { return @var; } }   class Test { function : Main(...
Give a code snippet in #Objeck In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the cl...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show a maze, using the simple Depth...
#Sidef
Sidef
var(w:5, h:5) = ARGV.map{.to_i}... var avail = (w * h)   # cell is padded by sentinel col and row, so I don't check array bounds var cell = (1..h -> map {([true] * w) + [false]} + [[false] * w+1]) var ver = (1..h -> map {["| "] * w }) var hor = (0..h -> map {["+--"] * w })   func walk(x, y) { cell[y][x] = false;...
Give a code snippet in #Sidef This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show...
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Perl
Perl
my @directories = grep { chomp; -d } `ls`; for (@directories) { chomp; ...; # Operate on directories }
Give a code snippet in #Perl Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Picat
Picat
import util.   main => Text = "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$eit...
Give a code snippet in #Picat 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 lef...
christopher/rosetta-code
http://rosettacode.org/wiki/Jaro-Winkler_distance
Jaro-Winkler distance
The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler distance also adds an increase ...
#Java
Java
import java.io.*; import java.util.*;   public class JaroWinkler { public static void main(String[] args) { try { List<String> words = loadDictionary("linuxwords.txt"); String[] strings = { "accomodate", "definately", "goverment", "occured", "publicall...
Give a code snippet in #Java The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler d...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#langur
langur
val .wordsets = [ w/the that a/, w/frog elephant thing/, w/walked treaded grows/, w/slowly quickly/, ]   val .alljoin = f(.words) for[=true] .i of len(.words)-1 { if last(.words[.i]) != first(.words[.i+1]): break = false }   # .amb expects 2 or more arguments val .amb = f(...[2 to -1] .words) if(.al...
Give a code snippet in #langur Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automato...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#C.23
C#
abstract class Class1 { public abstract void method1();   public int method2() { return 0; } }
Give a code snippet in #C.23 Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Processing
Processing
color black = color(0); color white = color(255);   void setup(){ size(320,240); // frameRate(300); // 60 by default }   void draw(){ loadPixels(); for(int i=0; i<pixels.length; i++){ if(random(1)<0.5){ pixels[i] = black; }else{ pixels[i] = white; } } updatePixels(); fill(0,128); ...
Give a code snippet in #Processing Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#PARI.2FGP
PARI/GP
fnice(n)={ my(f,s="",s1); if (n < 2, return(n)); f = factor(n); s = Str(s, f[1,1]); if (f[1, 2] != 1, s=Str(s, "^", f[1,2])); for(i=2,#f[,1], s1 = Str(" * ", f[i, 1]); if (f[i, 2] != 1, s1 = Str(s1, "^", f[i, 2])); s = Str(s, s1) ); s }; n=0;while(n++, print(fnice(n)))
Give a code snippet in #PARI.2FGP Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it w...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
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 |...
#PowerShell
PowerShell
$extra = "little" "Mary had a {0} lamb." -f $extra
Give a code snippet in #PowerShell 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 Operat...
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...
#Icon_and_Unicon
Icon and Unicon
link linddraw,wopen   procedure main() gener := 12 # generations w := h := 800 # window size rewrite := table() # L rewrite rules rewrite["X"] := "X+YF+" rewrite["Y"] := "-FX-Y" every (C := '') ++:= !!rewrite every /rewrite[c := !C] := c # map all rule characters   ...
Give a code snippet in #Icon_and_Unicon 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 f...
christopher/rosetta-code
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DIM o$(5) 20 LET xm=0: LET xx=31: REM screen limits 30 LET ym=0: LET yx=18 40 LET xo=16: LET yo=9: REM origin 50 LET xc=xo: LET yc=yo 60 PRINT AT yc,xc;" ": REM entry point for scan loop - blank cursor 70 LET xc=xo: LET yc=yo 80 LET t=IN 31 90 IF t=1 OR t=5 OR t=9 OR t=17 OR t=21 OR t=25 THEN LET xc=xx: LET o$(2)="R...
Give a code snippet in #ZX_Spectrum_Basic The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according t...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_length_of_two_strings
Compare length of two strings
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 |...
#Pascal
Pascal
program compareLengthOfStrings(output);   const specimenA = 'RosettaCode'; specimenB = 'Pascal'; specimenC = 'Foobar'; specimenD = 'Pascalish';   type specimen = (A, B, C, D); specimens = set of specimen value [];   const specimenMinimum = A; specimenMaximum = D;   var { the explicit range min..max serves as a...
Give a code snippet in #Pascal 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/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Seed7
Seed7
const proc: foo is func begin raise RANGE_ERROR; end func;
Give a code snippet in #Seed7 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions...
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...
#Arturo
Arturo
lookAndSay: function [n][ if n=0 -> return "1" previous: lookAndSay n-1   result: new "" currentCounter: 0 currentCh: first previous loop previous 'ch [ if? currentCh <> ch [ if not? zero? currentCounter -> 'result ++ (to :string currentCounter) ++ currentCh ...
Give a code snippet in #Arturo 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 sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Java
Java
class Point { protected int x, y; public Point() { this(0); } public Point(int x) { this(x, 0); } public Point(int x, int y) { this.x = x; this.y = y; } public Point(Point p) { this(p.x, p.y); } public int getX() { return this.x; } public int getY() { return this.y; } public void setX(int x) { t...
Give a code snippet in #Java Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#PL.2FI
PL/I
MERGE: PROCEDURE (A,LA,B,LB,C);   /* Merge A(1:LA) with B(1:LB), putting the result in C B and C may share the same memory, but not with A. */ DECLARE (A(*),B(*),C(*)) BYADDR POINTER; DECLARE (LA,LB) BYVALUE NONASGN FIXED BIN(31); DECLARE (I,J,K) FIXED BIN(31); DECLARE (SX) CHAR(58) VAR BASED (PX); D...
Give a code snippet in #PL.2FI Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#ABAP
ABAP
  CLASS lcl_hailstone DEFINITION. PUBLIC SECTION. TYPES: tty_sequence TYPE STANDARD TABLE OF i WITH NON-UNIQUE EMPTY KEY, BEGIN OF ty_seq_len, start TYPE i, len TYPE i, END OF ty_seq_len, tty_seq_len TYPE HASHED TABLE OF ty_...
Give a code snippet in #ABAP The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Io
Io
str := ("123" asNumber + 1) asString
Give a code snippet in #Io Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program formatNum.s */ /* use C library printf ha, ha, ha !!! */ /* Constantes */ .equ EXIT, 1 @ Linux syscall /* Initialized data */ .data szFormat1: .asciz " %09.3f\n" .align 4 sfNumber: .double 0f-7125E-3 sfNumber1: ...
Give a code snippet in #ARM_Assembly Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
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...
#.D0.9C.D0.9A-61.2F52
МК-61/52
СЧ 2 0 * П0 1 0 - [x] x#0 18 СЧ 2 0 * П1 БП 00 ИП0 С/П
Give a code snippet in #.D0.9C.D0.9A-61.2F52 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 restart...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Wren
Wren
import "io" for Stdin   System.print("Input device is a terminal? %(Stdin.isTerminal ? "Yes" : "No")")
Give a code snippet in #Wren Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#360_Assembly
360 Assembly
* Topswops optimized 12/07/2016 TOPSWOPS CSECT USING TOPSWOPS,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13) ...
Give a code snippet in #360_Assembly Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A roun...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#zkl
zkl
fcn evalWithX(text,x) { f:=Compiler.Compiler.compileText(text); f.x = x; // set free var in compiled blob f.__constructor(); // run blob vm.regX // compiler sets the VMs X register for cases like this } const TEXT="var x; x*2"; // variables need to be declared evalWithX(TEXT,5) - evalWithX(TEXT,3) #--> 4
Give a code snippet in #zkl x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and l...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Transd
Transd
#lang transd   MainModule : { v10: [1, 1234, 10000000], vvar: ["fe:16", "f0e:16", "2022:3", "Transd:30"],   sumDigits: (λ s String() (with snum (substr s 0 ":") base (first (substr s after: ":") "10") n 0 (textout "sum of " :left width: 10 (+ snum ":" base " : " )) (t...
Give a code snippet in #Transd Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#PicoLisp
PicoLisp
(call "ls")
Give a code snippet in #PicoLisp Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#AutoHotkey
AutoHotkey
q := [1, 2, 3, 4] q1 := [2, 3, 4, 5] q2 := [3, 4, 5, 6] r := 7   MsgBox, % "q = " PrintQ(q) . "`nq1 = " PrintQ(q1) . "`nq2 = " PrintQ(q2) . "`nr = " r . "`nNorm(q) = " Norm(q) . "`nNegative(q) = " PrintQ(Negative(q)) . "`nConjugate(q) = " PrintQ(Conjugate(q)) . "`nq + r = " PrintQ(AddR(q, r)) . "`nq1 + q2 = " ...
Give a code snippet in #AutoHotkey 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 nu...
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...
#Rust
Rust
use std::collections::BTreeSet;   fn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> { if set.is_empty() { let mut powerset = BTreeSet::new(); powerset.insert(set); return powerset; } // Access the first value. This could be replaced with `set.pop_first().unwr...
Give a code snippet in #Rust 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
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 |...
#Emacs_Lisp
Emacs Lisp
(defvar str "bar") (setq str (concat "foo" str)) str ;=> "foobar"
Give a code snippet in #Emacs_Lisp Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
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 ...
#Chapel
Chapel
iter fib() { var a = 0, b = 1;   while true { yield a; (a, b) = (b, b + a); } }
Give a code snippet in #Chapel 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 ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Aime
Aime
void step_up(void) { while (!step()) { step_up(); } }
Give a code snippet in #Aime From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function dete...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Jsish
Jsish
#!/usr/bin/env jsish function httpGet(fileargs:array|string, conf:object=void) {   var options = { // Web client for downloading files from url headers : [], // Header fields to send. nowait : false, // Just return object: caller will call update. onDone : null...
Give a code snippet in #Jsish Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#Maple
Maple
  content := URL:-Get( "http://www.google.com/" );  
Give a code snippet in #Maple Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
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"
#min
min
args
Give a code snippet in #min 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/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
magic[num_] := Capitalize[ StringRiffle[ Partition[ FixedPointList[IntegerName[StringLength[#], "Cardinal"] &, IntegerName[num, "Cardinal"]], 2, 1] /. {n_, n_} :> {n, "magic"}, ", ", " is "] <> "."]
Give a code snippet in #Mathematica.2FWolfram_Language Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal represe...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#JavaScript
JavaScript
if (some_condition) quit();
Give a code snippet in #JavaScript Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object final...
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.
#Prolog
Prolog
  %File: stdin_to_stdout.pl :- initialization(main).   main :- repeat, get_char(X), put_char(X), X == end_of_file, fail.  
Give a code snippet in #Prolog 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/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#D
D
  import std.stdio; import std.conv; import std.datetime.stopwatch;   int a; void f0() {} void f1() { auto b = a; } void f2() { auto b = to!string(a); }     void main() { auto r = benchmark!(f0, f1, f2)(10_000);   writeln("Time fx took to run 10,000 times:\n"); writeln("f0: ", r[0]); writeln("f1: ", r[1]); wr...
Give a code snippet in #D Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these g...
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.
#Emacs_Lisp
Emacs Lisp
(make-empty-file "output.txt") (make-directory "docs") (make-empty-file "/output.txt") (make-directory "/docs")
Give a code snippet in #Emacs_Lisp 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/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Julia
Julia
open(readlines, "path/to/file")[7]
Give a code snippet in #Julia Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it i...
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...
#Smalltalk
Smalltalk
text := '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,$rig...
Give a code snippet in #Smalltalk 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...
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...
#VBScript
VBScript
Dim a, b, i   Do a = Int(Rnd * 20) WScript.StdOut.Write a If a = 10 Then Exit Do b = Int(Rnd * 20) WScript.Echo vbNullString, b Loop   For i = 1 To 100000 a = Int(Rnd * 20) WScript.StdOut.Write a If a = 10 Then Exit For b = Int(Rnd * 20) WScript.Echo vbNullString, b Next
Give a code snippet in #VBScript 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/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#Picolisp
Picolisp
  (de gpentagonals (Max) (make (let (N 0 M 1) (loop (inc 'N (if (=0 (& M 1)) (>> 1 M) M)) (T (> N Max)) (link N) (inc 'M)))))   (de p (N) (cache '(NIL) N (if (=0 N) 1 (let (Sum 0 Sgn 0) (for G (gpentagonals N) ...
Give a code snippet in #Picolisp The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#MATLAB_.2F_Octave
MATLAB / Octave
  function x = isEmptyDirectory(p) if isdir(p) f = dir(p) x = length(f)>2; else error('Error: %s is not a directory'); end; end;  
Give a code snippet in #MATLAB_.2F_Octave Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root direc...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Pike
Pike
  int i=1; while(true) write("0%o\n", i++);  
Give a code snippet in #Pike Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Swift
Swift
var s = "foo" // "foo" s += "bar" // "foobar" print(s) // "foobar" s.appendContentsOf("baz") // "foobarbaz" print(s) // "foobarbaz"
Give a code snippet in #Swift 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/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#PicoLisp
PicoLisp
$ apt-get install picolisp
Give a code snippet in #PicoLisp Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the langu...
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
#OpenLisp
OpenLisp
  #!/openlisp/uxlisp -shell (format t "Hello world!~%") (print "Hello world!")  
Give a code snippet in #OpenLisp 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
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Objeck
Objeck
class Cusip { function : native : IsCusip(s : String) ~ Bool { if(s->Size() <> 9) { return false; };   sum := 0; for(i := 0; i < 7; i+=1;) { c := s->Get(i);   v : Int; if (c >= '0' & c <= '9') { v := c - 48; ...
Give a code snippet in #Objeck This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeri...
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,...
#Computer.2Fzero_Assembly
Computer/zero Assembly
load: LDA ary ADD sum STA sum   LDA load ADD one STA load   SUB end BRZ done   JMP load   done: LDA sum STP   one: 1 end: LDA ary+10   sum: 0   ary: 1 2 3 4 ...
Give a code snippet in #Computer.2Fzero_Assembly 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 val...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#PowerShell
PowerShell
  function Get-ProperDivisorSum ( [int]$N ) { If ( $N -lt 2 ) { return 0 }   $Sum = 1 If ( $N -gt 3 ) { $SqrtN = [math]::Sqrt( $N ) ForEach ( $Divisor in 2..$SqrtN ) { If ( $N % $Divisor -eq 0 ) { $Sum += $Divisor + $N / $Divisor } } If...
Give a code snippet in #PowerShell These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as defi...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Dim lines = IO.File.ReadAllLines("days_of_week.txt") Dim i = 0   For Each line In lines i += 1 If line.Length > 0 Then Dim days = line.Split() If days.Length <> 7 Then Throw New Exception(...
Give a code snippet in #Visual_Basic_.NET The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#Icon_and_Unicon
Icon and Unicon
procedure main() every dir := "." | "./empty" do write(dir, if isdirempty(dir) then " is empty" else " is not empty") end   procedure isdirempty(s) #: succeeds if directory s is empty (and a directory) local d,f if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { while f := read(d) do ...
Give a code snippet in #Icon_and_Unicon Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directo...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: permutations is array array integer;   const func permutations: permutations (in array integer: items) is func result var permutations: permsList is 0 times 0 times 0; local const proc: perms (in array integer: sequence, in array integer: prefix) is func local ...
Give a code snippet in #Seed7 Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   gene...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Standard_ML
Standard ML
print "Goodbye, World!"
Give a code snippet in #Standard_ML 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Falcon
Falcon
  a = 1 b = 2 a,b = arr = b,a  
Give a code snippet in #Falcon Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides generici...
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...
#bc
bc
i = -3   /* Assumes that i is an integer. */ scale = 0 if (i % 2 == 0) "i is even " if (i % 2) "i is odd "
Give a code snippet in #bc 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 ...
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...
#zkl
zkl
fcn strip(text,c){ // if c in text, remove it and following text if (Void!=(n:=text.find(c))) text=text[0,n]; text.strip() // remove leading and trailing white space } fcn stripper(text,a,b,c,etc){ // strip a,b,c,etc from text foreach c in (vm.arglist[1,*]){ text=strip(text,c) } text }
Give a code snippet in #zkl Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whi...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program cursorPos.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall     /* Initialized data */ .data szMessStartPgm: ...
Give a code snippet in #ARM_Assembly Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Derangements
Permutations/Derangements
A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n. The...
#QBasic
QBasic
' Heap's algorithm non-recursive FUNCTION permsderange (n!, flag!) IF n = 0 THEN permsderange = 1   DIM a!(0 TO n), c!(0 TO n)   FOR j = 0 TO n - 1: a(j) = j: NEXT j   WHILE i < n IF c(i) < i THEN IF (i AND 1) = 0 THEN SWAP a(0), a(i) ELSE ...
Give a code snippet in #QBasic A derangement is a permutation of the order of distinct items in which no item appears in its original place. For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). The number of derangements of n distinct items is known as the subfactorial of...
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 ...
#zkl
zkl
File.stderr.writeln("Goodbye, World!")
Give a code snippet in #zkl Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". ...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Hoon
Hoon
:-  %say |= [^ [in=@tas ~] ~] :-  %noun =+ obj=(need (poja in))  :: try parse to json =+ typ=$:(name=@tas age=@ud)  :: datastructure =+ spec=(ot name/so age/ni ~):jo  :: parsing spec  ?.  ?=([%o *] obj)  :...
Give a code snippet in #Hoon Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#Logtalk
Logtalk
  :- object(singly_linked_list).   :- public(show/0).   show :- traverse([1,2,3]).   traverse([]). traverse([Head| Tail]) :- write(Head), nl, traverse(Tail).   :- end_object.  
Give a code snippet in #Logtalk Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Defin...
christopher/rosetta-code