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/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 |...
#C.23
C#
class Program { static void Main(string[] args) { string x = "foo"; x += "bar"; System.Console.WriteLine(x); } }
Give a code snippet in #C.23 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/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Kotlin
Kotlin
// version 1.1.2   typealias Func = (Int) -> Int typealias FuncS = (Func, List<Int>) -> List<Int>   fun fs(f: Func, seq: List<Int>) = seq.map { f(it) }   fun partial(fs: FuncS, f: Func) = { seq: List<Int> -> fs(f, seq) }   fun f1(n: Int) = 2 * n   fun f2(n: Int) = n * n   fun main(args: Array<String>) { val fsf1 =...
Give a code snippet in #Kotlin Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original functi...
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...
#Icon_and_Unicon
Icon and Unicon
global bloop   procedure main(A) if older(11,7) then stop("Must have version >= 11.7!") bloop := -5 # global variable floop := -11.3 # local variable write(proc("abs")(variable("bloop"))) write(proc("abs")(variable("floop"))) end   procedure older(maj,min) &version ? { (tab(...
Give a code snippet in #Icon_and_Unicon 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 c...
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...
#Wren
Wren
import "/seq" for Stack   var s = Stack.new() s.push(1) s.push(2) System.print("Stack contains %(s.toList)") System.print("Number of elements in stack = %(s.count)") var item = s.pop() System.print("'%(item)' popped from the stack") System.print("Last element is now %(s.peek())") s.clear() System.print("Stack cleared")...
Give a code snippet in #Wren 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 acc...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Lua
Lua
function sameDigits(n,b) local f = n % b n = math.floor(n / b) while n > 0 do if n % b ~= f then return false end n = math.floor(n / b) end return true end   function isBrazilian(n) if n < 7 then return false end if (n % 2 == 0) and (n >= 8) th...
Give a code snippet in #Lua Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 ...
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...
#Swift
Swift
println(String(26, radix: 16)) // prints "1a"
Give a code snippet in #Swift 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/Order_disjoint_list_items
Order disjoint list items
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 ...
#Phix
Phix
with javascript_semantics function order_disjoint(sequence m, sequence n) integer rlen = length(n) sequence rdis = repeat(0,rlen) for i=1 to rlen do object e = n[i] integer j = find(e,m) while j!=0 and find(j,rdis) do j = find(e,m,j+1) end while rdis[i] = ...
Give a code snippet in #Phix 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Racket
Racket
  #lang racket (define (pick-item l) (list-ref l (random (length l))))  
Give a code snippet in #Racket Demonstrate how to pick a random element from a list.
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...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT MODE DATA $$ BUILD X_TABLE alfabet2moco =* "!"---."\".-..-."$"...-..-"'".----." "("-.--.")"-.--.-"+".-.-.","--..--" "-"-....-".".-.-.-"/"-..-." "0"-----"1".----"2"..---"3"...--" "4"....-"5"....."6"-...."7"--..." "8"---.."9"----." ":"---...";"-.-.-."="-...-"?"..--.." "@".--.-." "A".-"B"-..."C"-.-."D"-...
Give a code snippet in #TUSCRIPT 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 ign...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi
Arithmetic-geometric mean/Calculate Pi
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing: π ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
pi[n_, prec_] := Module[{a = 1, g = N[1/Sqrt[2], prec], k, s = 0, p = 4}, For[k = 1, k < n, k++, {a, g} = {N[(a + g)/2, prec], N[Sqrt[a g], prec]}; s += p (a^2 - g^2); p += p]; N[4 a^2/(1 - s), prec]]     pi[7, 100] - N[Pi, 100] 1.2026886537*10^-86   pi[7, 100] 3.14159265358979323846264338327950288419716939...
Give a code snippet in #Mathematica.2FWolfram_Language Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate π {\displaystyle \pi } . With the same notations used in Arithmetic-geomet...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#EchoLisp
EchoLisp
  ;; stern (2n ) = stern (n) ;; stern(2n+1) = stern(n) + stern(n+1)   (define (stern n) (cond (( < n 3) 1) ((even? n) (stern (/ n 2))) (else (let ((m (/ (1- n) 2))) (+ (stern m) (stern (1+ m))))))) (remember 'stern)  
Give a code snippet in #EchoLisp For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered me...
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...
#Clojure
Clojure
(def i (ref 1024))   (while (> @i 0) (println @i) (dosync (ref-set i (quot @i 2))))
Give a code snippet in #Clojure 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/Downw...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Groovy
Groovy
Number.metaClass.isHappy = { def number = delegate as Long def cycle = new HashSet<Long>() while (number != 1 && !cycle.contains(number)) { cycle << number number = (number as String).collect { d = (it as Long); d * d }.sum() } number == 1 }   def matches = [] for (int i = 0; matches...
Give a code snippet in #Groovy From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly...
christopher/rosetta-code
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifi...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; static class Md4 { public static string Md4Hash(this string input) { // get padded uints from bytes List<byte> bytes = Encoding.ASCII.GetBytes(input).ToList(); uint bitCount = (uint)(bytes.Count) * 8; ...
Give a code snippet in #C.23 Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolet...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#BBC_BASIC
BBC BASIC
DIM ft{dwLowDateTime%, dwHighDateTime%} DIM st{wYear{l&,h&}, wMonth{l&,h&}, wDayOfWeek{l&,h&}, \ \ wDay{l&,h&}, wHour{l&,h&}, wMinute{l&,h&}, \ \ wSecond{l&,h&}, wMilliseconds{l&,h&} }   REM File is assumed to exist: file$ = @tmp$ + "rosetta.tmp"   REM Get and display...
Give a code snippet in #BBC_BASIC Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#Scala
Scala
sealed trait Trit { self => def nand(that:Trit):Trit=(this,that) match { case (TFalse, _) => TTrue case (_, TFalse) => TTrue case (TMaybe, _) => TMaybe case (_, TMaybe) => TMaybe case _ => TFalse }   def nor(that:Trit):Trit = this.or(that).not() def and(that:Trit):Trit = this.nand(that).not(...
Give a code snippet in #Scala This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#zkl
zkl
bases:= #<<<" CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA ...
Give a code snippet in #zkl Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGG...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Clojure
Clojure
(defn proper-divisors [n] (if (< n 4) [1] (->> (range 2 (inc (quot n 2))) (filter #(zero? (rem n %))) (cons 1))))   (defn perfect? [n] (= (reduce + (proper-divisors n)) n))
Give a code snippet in #Clojure Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itse...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
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 |...
#AppleScript
AppleScript
-- SUBSTRINGS -----------------------------------------------------------------   -- take :: Int -> Text -> Text on take(n, s) text 1 thru n of s end take   -- drop :: Int -> Text -> Text on drop(n, s) text (n + 1) thru -1 of s end drop   -- breakOn :: Text -> Text -> (Text, Text) on breakOn(strPattern, s) ...
Give a code snippet in #AppleScript 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Elixir
Elixir
defmodule First_class_functions do def task(val) do as = [&:math.sin/1, &:math.cos/1, fn x -> x * x * x end] bs = [&:math.asin/1, &:math.acos/1, fn x -> :math.pow(x, 1/3) end] Enum.zip(as, bs) |> Enum.each(fn {a,b} -> IO.puts compose([a,b], val) end) end   defp compose(funs, x) do Enum.reduce(...
Give a code snippet in #Elixir A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other ...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#BBC_BASIC
BBC BASIC
PRINT FNenvironment("PATH") PRINT FNenvironment("USERNAME") END   DEF FNenvironment(envar$) LOCAL buffer%, size% SYS "GetEnvironmentVariable", envar$, 0, 0 TO size% DIM buffer% LOCAL size% SYS "GetEnvironmentVariable", envar$, buffer%, size%+1 = $$buffer%
Give a code snippet in #BBC_BASIC Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#Wren
Wren
import "/math" for Nums import "/fmt" for Fmt   /* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores and then, if the scores are equal, by reverse alphabetic order of names */   var standardRanking = Fn.new { |scores| var rankings = List.filled(scor...
Give a code snippet in #Wren 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Home_primes
Home primes
This page uses content from Wikipedia. The original article was at Home prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, the home prime HP(n) of an integer n greater than 1 is...
#Julia
Julia
using Primes   function homeprimechain(n::BigInt) isprime(n) && return [n] concat = prod(string(i)^j for (i, j) in factor(n).pe) return pushfirst!(homeprimechain(parse(BigInt, concat)), n) end homeprimechain(n::Integer) = homeprimechain(BigInt(n))   function printHPiter(n, numperline = 4) chain = homepr...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Home prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, the home prime HP(n) of...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#C.23
C#
int main(){}
Give a code snippet in #C.23 Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Prolog
Prolog
short_circuit :- ( a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl, ( a_or_b(true, false)-> writeln('==> true'); writeln('==> false')) , nl, ( a_or_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl, ( a_or_b(false, false)-> writeln('==> true'); writeln('==> false')) , n...
Give a code snippet in #Prolog Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable re...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#FOCAL
FOCAL
01.01 S T=0 01.02 A "LOWER LIMIT",L 01.03 A "UPPER LIMIT",H 01.04 I (H-L)1.05,1.05,1.06 01.05 T "INVALID RANGE",!;G 1.02 01.06 S S=FITR(L+FRAN()*(H-L+1)) 01.10 A "GUESS",G 01.11 I (H-G)1.13,1.12,1.12 01.12 I (G-L)1.13,1.14,1.14 01.13 T "OUT OF RANGE",!;G 1.1 01.14 S T=T+1 01.15 I (G-S)1.16,1.17,1.18 01.16 T "TOO LOW!",...
Give a code snippet in #FOCAL Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hi...
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...
#Python
Python
a, b = b, a
Give a code snippet in #Python 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/Keyboard_input/Flush_the_keyboard_buffer
Keyboard input/Flush the keyboard buffer
Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
#Wren
Wren
import "io" for Stdin   System.print("Press some keys followed by enter.") while (true) { var b = Stdin.readByte() // reads and removes a key from the buffer System.print("Removed key with code %(b).") if (b == 10) break // buffer will be empty when enter key pressed } System.print("Keyboard buffer is now...
Give a code snippet in #Wren Flush the   keyboard   buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered,   and then allows the program to continue. The program must not wait for users to type anything.
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Klingphix
Klingphix
include ..\Utilitys.tlhy     %Size 5 !Size 0 ( $Size dup ) dim   %i 1 !i %j 1 !j     $Size 2 power [ 1 - ( $i $j ) set $i $j + 1 band 0 == ( [$j $Size < ( [$j 1 + !j] [$i 2 + !i] ) if $i 1 > [ $i 1 - !i] if ] [$i $Size < ( [$i 1 + !i] [$j 2 + !j] ) if $j 1 > [ $j 1 - !j] if...
Give a code snippet in #Klingphix Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program puzzle15.s */   /************************************/ /* Constantes */ /************************************/ .equ STDIN, 0 @ Linux input console .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 ...
Give a code snippet in #ARM_Assembly Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Arturo
Arturo
enum: [apple banana cherry] print "as a block of words:" inspect.muted enum   enum: ['apple 'banana 'cherry] print "\nas a block of literals:" print enum   enum: #[ apple: 1 banana: 2 cherry: 3 ] print "\nas a dictionary:" print enum
Give a code snippet in #Arturo Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#AutoIt
AutoIt
  $ww = "" $ww &= "tH........." & @CR $ww &= ". . " & @CR $ww &= " ... " & @CR $ww &= ". . " & @CR $ww &= "Ht.. ......" $rows = StringSplit($ww, @CR) $cols = StringSplit($rows[1], "") Global $Wireworldarray[$rows[0]][$cols[0]] For $I = 1 To $rows[0] $cols = StringSplit($rows[$I], "") For $k = 1 To...
Give a code snippet in #AutoIt Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell...
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
#ooRexx
ooRexx
  p = .point~new(3,2) c = .circle~new(,2,6)   p~print c~print   ::class point ::method init expose x y use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates   ::attribute x ::attribute y   ::method print expose x y say "A point at location ("||x","y")"   ::class circle subclass point ...
Give a code snippet in #ooRexx 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/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Python
Python
'''Brazilian numbers'''   from itertools import count, islice     # isBrazil :: Int -> Bool def isBrazil(n): '''True if n is a Brazilian number, in the sense of OEIS:A125134. ''' return 7 <= n and ( 0 == n % 2 or any( map(monoDigit(n), range(2, n - 1)) ) )     # monoDi...
Give a code snippet in #Python Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#Go
Go
package main   import "fmt"   type Item struct { name string weight, value, qty int }   var items = []Item{ {"map", 9, 150, 1}, {"compass", 13, 35, 1}, {"water", 153, 200, 2}, {"sandwich", 50, 60, 2}, {"glucose", 15, 60, 2}, {"tin", 68, 45, 3}, {"banana", 27, 60, 3}, {"apple", 39, 40, ...
Give a code snippet in #Go A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#MMIX
MMIX
x IS $1 % flt calculations y IS $2 % id z IS $3 % z = sum series t IS $4 % temp var   LOC Data_Segment GREG @ BUF OCTA 0,0,0 % print buffer   LOC #1000 GREG @ // print floating point number in scientific format: 0.xxx...ey.. // most of this routine is adopted from: // http://www.pspu.ru/personal/eremin/emmi/ro...
Give a code snippet in #MMIX Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
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.
#EchoLisp
EchoLisp
  ;; a random length list of random values (define L (map random (make-list (random 50) 100))) → L L → (24 60 83 8 24 60 31 97 96 65 9 41 64 24 22 57 73 17 6 28 77 58 18 13 27 22 41 69 85)   ;; find max (apply max L) → 97  
Give a code snippet in #EchoLisp 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/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. 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) The   International Bank Account Number (IBAN)   is an internationally agree...
#Julia
Julia
function validiban(iban::AbstractString) country2length = Dict( "AL" => 28, "AD" => 24, "AT" => 20, "AZ" => 28, "BE" => 16, "BH" => 22, "BA" => 20, "BR" => 29, "BG" => 22, "CR" => 21, "HR" => 21, "CY" => 28, "CZ" => 24, "DK" => 18, "DO" => 28, "EE" => 20, "FO" => 18, "FI" => 18, "FR" => 27, ...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at IBAN. 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) The   International Bank Account Number (IBAN...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#zkl
zkl
const INF=(0).MAX; fcn dijkstra(graph,start,dst){ Q  :=graph.copy(); prev:=graph.keys.pump(Dictionary().add.fp1(Void)); dist:=graph.keys.pump(Dictionary().add.fp1(INF)); dist[start]=0; while(Q){ Q.reduce('wrap(min,[(v,_)],ru){ if((d:=dist[v])<min){ ru.set(v); d } else min }, IN...
Give a code snippet in #zkl This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the si...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#J
J
  NB. http://rosettacode.org/wiki/Loops/Wrong_ranges#J NB. define range as a linear polynomial start =: 0&{ stop =: 1&{ increment =: 2&{ :: 1: NB. on error use 1 range =: (start , increment) p. [: i. [: >: [: <. (stop - start) % increment   f =: 3 :0 input =. y 'prod sum x y z one three seven' =. 1 0 5 _5 _2 1 3 7 ...
Give a code snippet in #J Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as i...
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...
#ABAP
ABAP
  report z_powerset.   interface set. methods: add_element importing element_to_be_added type any returning value(new_set) type ref to set,   remove_element importing element_to_be_removed type any returning value(new_set) type ref to set,   ...
Give a code snippet in #ABAP 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/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#PARI.2FGP
PARI/GP
magic(v)=vector(#v,i,v[if(i%2,1,#v/2)+i\2]); shuffles_slow(n)=my(v=[1..n],o=v,s=1);while((v=magic(v))!=o,s++);s; shuffles(n)=znorder(Mod(2,n-1)); vector(5000,n,shuffles_slow(2*n))
Give a code snippet in #PARI.2FGP A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q...
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...
#68000_Assembly
68000 Assembly
main: MOVE.W #1024,D0   WhileLoop: jsr PrintHexWord LSR.W #1,D0 BNE WhileLoop
Give a code snippet in #68000_Assembly 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   Loop...
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...
#HicEst
HicEst
CHARACTER str = "alphaBETA" EDIT(Text=str, UpperCase=LEN(str)) EDIT(Text=str, LowerCase=LEN(str)) EDIT(Text=str, UpperCase=1)
Give a code snippet in #HicEst 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#Scala
Scala
object NoConnection extends App {   private def links = Seq( Seq(2, 3, 4), // A to C,D,E Seq(3, 4, 5), // B to D,E,F Seq(2, 4), // D to C, E Seq(5), // E to F Seq(2, 3, 4), // G to C,D,E Seq(3, 4, 5)) // H to D,E,F   private def genRandom: LazyList[Seq[Int]] = util.Random.shuffle((1 to 8).to...
Give a code snippet in #Scala You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#Clojure
Clojure
(require '[postal.core :refer [send-message]])   (send-message {:host "smtp.gmail.com"  :ssl true  :user your_username  :pass your_password} {:from "you@yourdomain.com"  :to ["your_friend@example.com"]  :cc ["bob@builder.com" "dora@expl...
Give a code snippet in #Clojure Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given...
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Stata
Stata
. display %21x . +1.0000000000000X+3ff   . display %21x .a +1.0010000000000X+3ff   . display %21x .z +1.01a0000000000X+3ff   . display %21x c(maxdouble) +1.fffffffffffffX+3fe
Give a code snippet in #Stata The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language ...
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...
#Ada
Ada
package Morse is   type Symbols is (Nul, '-', '.', ' '); -- Nul is the letter separator, space the word separator; Dash : constant Symbols := '-'; Dot : constant Symbols := '.'; type Morse_Str is array (Positive range <>) of Symbols; pragma Pack (Morse_Str);   function Convert (Input : String) retu...
Give a code snippet in #Ada 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 u...
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
#TMG
TMG
begin: parse(( = { <Hello, World!> * } ));
Give a code snippet in #TMG 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/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#Io
Io
List do( countingSort := method(min, max, count := list() setSize(max - min + 1) mapInPlace(0) foreach(x, count atPut(x - min, count at(x - min) + 1) )   j := 0 for(i, min, max, while(count at(i - min) > 0, atPut(j, i) c...
Give a code snippet in #Io 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/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#Action.21
Action!
INCLUDE "D2:CHARTEST.ACT" ;from the Action! Tool Kit   PROC Main() CHAR ARRAY lower(128),upper(128) CHAR c BYTE lowerLen,upperLen   Put(125) PutE() ;clear screen   lowerLen=0 upperLen=0 FOR c=0 TO 127 DO IF IsLower(c) THEN lowerLen==+1 lower(lowerLen)=c ELSEIF IsUpper(c) THEN u...
Give a code snippet in #Action.21 Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). T...
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#jq
jq
def array($init): [range(0; .) | $init];   # Test if input is a one-character string holding a digit def isDigit: type=="string" and length==1 and explode[0] as $c | (48 <= $c and $c <= 57);   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   def generate($n; $i; $c): if $n <= 1 then "'n' mu...
Give a code snippet in #jq An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#BASIC
BASIC
n = 1  : n1 = 1 e1 = 0 : e = 1 / 1   while e <> e1 e1 = e e += 1 / n n1 += 1 n *= n1 end while   print "The value of e = "; e end
Give a code snippet in #BASIC Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Python
Python
csvtxt = '''\ Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!\ '''   fro...
Give a code snippet in #Python Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task C...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Scala
Scala
  object CatalanNumbers { def main(args: Array[String]): Unit = { for (n <- 0 to 15) { println("catalan(" + n + ") = " + catalan(n)) } }   def catalan(n: BigInt): BigInt = factorial(2 * n) / (factorial(n + 1) * factorial(n))   def factorial(n: BigInt): BigInt = BigInt(1).to(n).foldLeft(BigInt(1))(...
Give a code snippet in #Scala Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#zkl
zkl
var PS=Import("Src/ZenKinetic/sieve").postponed_sieve; var ps=Utils.Generator(PS), plist=ps.walk(10).copy();   fcn isEmirp(p){ rp:=p.toString().reverse().toInt(); if(p==rp) return(False); if(plist.holds(rp)) return(True); tp:=p; mp:=p.max(rp); while(tp<mp) { plist.append(tp=ps.next()) } return(tp==rp); } ...
Give a code snippet in #zkl An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   em...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#X86_Assembly
X86 Assembly
  extern _printf   section .data output db 0,0   section .text global _main _main: mov bl, 0 looping: add bl, 0x31 ;0x30 to 0x39 is 0 to 9 in ASCII mov [output], bl sub bl, 0x30 push output call _printf add esp, 4 xor eax, eax xor edx, edx ...
Give a code snippet in #X86_Assembly Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#BBC_BASIC
BBC BASIC
dummy% = FNsubrand(292929) FOR i% = 1 TO 10 PRINT FNsubrand(0) NEXT END   DEF FNsubrand(s%) PRIVATE r%(), p% : DIM r%(54) IF s% = 0 THEN p% = (p% + 1) MOD 55 r%(p%) = r%(p%) - r%((p% + 31) MOD 55) IF r%(p%) < 0 r%(p%) += 10^9 = r%(p%) ...
Give a code snippet in #BBC_BASIC A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pm...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#ALGOL_68
ALGOL 68
PROC factorial = (INT upb n)LONG LONG INT:( LONG LONG INT z := 1; FOR n TO upb n DO z *:= n OD; z ); ~
Give a code snippet in #ALGOL_68 Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#Arturo
Arturo
getCurlVersion: function [][ try? [ call.external:'curl "curl_version" .expect: :string [] ] else [ "library not found" ] ]   print ["curl version:" getCurlVersion]
Give a code snippet in #Arturo Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign langua...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Bracmat
Bracmat
(fractran= np n fs A Z fi P p N L M .  !arg:(?N,?n,?fs) {Number of iterations, start n, fractions} & :?P:?L {Initialise accumulators.} & whl ' ( -1+!N:>0:?N {Stop when counted down to zero.} & !n !L:?L {Prepend all numbers...
Give a code snippet in #Bracmat FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an init...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/2
Text processing/2
The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters...
#C
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>   typedef struct { const char *s; int ln, bad; } rec_t; int cmp_rec(const void *aa, const void *bb) { const rec_t *a = aa, *b = bb; return a->s == b->s ? 0 : !a->s ? 1 : !b->s...
Give a code snippet in #C The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or m...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#Run_BASIC
Run BASIC
for penny = 0 to 100 for nickel = 0 to 20 for dime = 0 to 10 for quarter = 0 to 4 if penny + nickel * 5 + dime * 10 + quarter * 25 = 100 then print penny;" pennies ";nickel;" nickels "; dime;" dimes ";quarter;" quarters" count = count + 1 end if next qua...
Give a code snippet in #Run_BASIC There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels a...
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...
#Sidef
Sidef
func sieve(limit) { var sieve_arr = [false, false, (limit-1).of(true)...] gather { sieve_arr.each_kv { |number, is_prime| if (is_prime) { take(number) for i in (number**2 .. limit `by` number) { sieve_arr[i] = false } ...
Give a code snippet in #Sidef 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   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#J
J
NB. converts the image to grayscale according to formula NB. L = 0.2126*R + 0.7152*G + 0.0722*B toGray=: [: <. +/ .*"1&0.2126 0.7152 0.0722   NB. converts grayscale image to the color image, with all channels equal toColor=: 3 & $"0
Give a code snippet in #J Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
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 |...
#Sed
Sed
  # 2 chars starting from 3rd $ echo string | sed -r 's/.{3}(.{2}).*/\1/' in # remove first 3 chars echo string | sed -r 's/^.{3}//' # delete last char $ echo string | sed -r 's/.$//' strin # `r' with two following chars $ echo string | sed -r 's/.*(r.{2}).*/\1/' rin  
Give a code snippet in #Sed Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#Lua
Lua
local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt local bitmap = { init = function(self, w, h, value) self.w, self.h, self.pixels = w, h, {} for y=1,h do self.pixels[y]={} end self:clear(value) end, clear = function(self, value) for y=1,self.h...
Give a code snippet in #Lua Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspect...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Action.21
Action!
CARD FUNC Gcd(CARD a,b) CARD tmp   IF a<b THEN tmp=a a=b b=tmp FI   WHILE b#0 DO tmp=a MOD b a=b b=tmp OD RETURN(a)   PROC Test(CARD a,b) CARD res   res=Gcd(a,b) PrintF("GCD of %I and %I is %I%E",a,b,res) RETURN   PROC Main() Test(48,18) Test(9360,12240) Test(17,19) Test(123,1...
Give a code snippet in #Action.21 Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   grea...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Lasso
Lasso
define printTimesTables(max::integer) => { local(result) = `` local(padSize) = string(#max*#max)->size + 1   // Print header row #result->append((' ' * #padSize) + '|') loop(#max) => { #result->append(loop_count->asString(-padding=#padSize)) } #result->append("\n" + (`-` * #padSize)...
Give a code snippet in #Lasso Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#BCPL
BCPL
get "libhdr"   // Definitions let popcount(n) = n=0 -> 0, (n&1) + popcount(n >> 1) let evil(n) = (popcount(n) & 1) = 0 let odious(n) = (popcount(n) & 1) = 1   // The BCPL word size is implementation-dependent, // but very unlikely to be big enough to store 3^29. // This implements a 48-bit integer using byte stri...
Give a code snippet in #BCPL Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Factor
Factor
: is-f? ( obj -- ? ) f = ;
Give a code snippet in #Factor Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your lang...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Oforth
Oforth
: revWords(s) s words reverse unwords ;   : reverseWords "---------- Ice and Fire ------------" revWords println " " revWords println "fire, in end will world the say Some" revWords println "ice. in say Some " revWords println "desire of tasted I'...
Give a code snippet in #Oforth Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spa...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#Action.21
Action!
PROC Main() DEFINE PTR="CARD" DEFINE COUNT="20" CHAR ARRAY s(256) PTR ARRAY a(COUNT) BYTE i   a(0)="It is certain." a(1)="It is decidedly so." a(2)="Without a doubt." a(3)="Yes - definitely." a(4)="You may rely on it." a(5)="As I see it, yes." a(6)="Most likely." a(7)="Outlook good." a(8)="Y...
Give a code snippet in #Action.21 Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinf...
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,...
#VBScript
VBScript
''''''''''''''''''''''''''''''''''''''''''''' ' Rosetta Code/Rank Languages by Popularity ' ' VBScript Implementation ' '...........................................' 'API Links (From C Code) URL1 = "http://www.rosettacode.org/mw/api.php?format=json&action=query&generator=categorymembe...
Give a code snippet in #VBScript 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 ju...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#F.23
F#
  // Determine if a string has all unique characters. Nigel Galloway: June 9th., 2020 let fN (n:string)=n.ToCharArray()|>Array.mapi(fun n g->(n,g))|>Array.groupBy(fun (_,n)->n)|>Array.filter(fun(_,n)->n.Length>1)   let allUnique n=match fN n with g when g.Length=0->printfn "All charcters in <<<%s>>> (l...
Give a code snippet in #F.23 Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its lengt...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#Wren
Wren
import "/fmt" for Fmt   var magicSquareOdd = Fn.new { |n| if (n < 3 || n%2 == 0) Fiber.abort("Base must be odd and > 2") var value = 1 var gridSize = n * n var c = (n/2).floor var r = 0 var result = List.filled(n, null) for (i in 0...n) result[i] = List.filled(n, 0) while (value <= gridS...
Give a code snippet in #Wren A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#ACL2
ACL2
(defun filter-evens (xs) (cond ((endp xs) nil) ((evenp (first xs)) (cons (first xs) (filter-evens (rest xs)))) (t (filter-evens (rest xs)))))
Give a code snippet in #ACL2 Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Batch_File
Batch File
ren input.txt output.txt ren \input.txt output.txt ren docs mydocs ren \docs mydocs
Give a code snippet in #Batch_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 t...
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...
#Scala
Scala
import scala.util.Random   object MazeTypes { case class Direction(val dx: Int, val dy: Int)   case class Loc(val x: Int, val y: Int) { def +(that: Direction): Loc = Loc(x + that.dx, y + that.dy) }   case class Door(val from: Loc, to: Loc)   val North = Direction(0,-1) val South = Direction(0,1) val W...
Give a code snippet in #Scala 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/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 ...
#PHP
PHP
function fibIter($n) { if ($n < 2) { return $n; } $fibPrev = 0; $fib = 1; foreach (range(1, $n-1) as $i) { list($fibPrev, $fib) = array($fib, $fib + $fibPrev); } return $fib; }
Give a code snippet in #PHP 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 g...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#FOCAL
FOCAL
01.10 T %1,"BULLS AND COWS"!"----- --- ----"!! 01.20 S T=0;D 3 01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!! 01.40 I (B-4)1.3 01.50 T "YOU WON! GUESSES",%4,T,!! 01.60 Q   02.10 A "GUESS",A 02.20 F X=0,3;S B=FITR(A/10);S G(3-X)=A-B*10;S A=B 02.30 S A=1 02.40 F X=0,3;S A=A*G(X) 02.50 I (-A)2.6;T "NEED FOUR NONZERO DIGIT...
Give a code snippet in #FOCAL Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Icon_and_Unicon
Icon and Unicon
procedure main() delay(1000) # give user a chance to input if kbhit() then # test for input write("You entered ",x := getch()) # read w/o echo else # use getche for echo write("No input waiting") end
Give a code snippet in #Icon_and_Unicon Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Lua
Lua
for _,v in ipairs({ 0.9054054, 0.518518, 0.75, math.pi }) do local n, d, dmax, eps = 1, 1, 1e7, 1e-15 while math.abs(n/d-v)>eps and d<dmax do d=d+1 n=math.floor(v*d) end print(string.format("%15.13f --> %d / %d", v, n, d)) end
Give a code snippet in #Lua This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is n...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#JavaScript
JavaScript
  function twentyfour(numbers, input) { var invalidChars = /[^\d\+\*\/\s-\(\)]/;   var validNums = function(str) { // Create a duplicate of our input numbers, so that // both lists will be sorted. var mnums = numbers.slice(); mnums.sort();   // Sort after mapping to numbe...
Give a code snippet in #JavaScript The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} ) ...
#Java
Java
import java.awt.image.BufferedImage; import java.util.Arrays;   /** * <p><em>This software has been released into the public domain. * <strong>Please read the notes in this source file for additional information. * </strong></em></p> * * <p>This class provides a configurable implementation of the Canny edge * de...
Give a code snippet in #Java Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Icon_and_Unicon
Icon and Unicon
$define FILLER "*" # the filler character   procedure main(A)   width := 3 ^ ( order := (0 < \A[1]) | 3 ) write("Carpet order= ",order)   every !(canvas := list(width)) := list(width," ") # prime the canvas   every y := 1 to width & x := 1 to width do # traverse it if IsFilled(x-...
Give a code snippet in #Icon_and_Unicon Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### ...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#BASIC
BASIC
ABS(x) 'absolute value SQR(x) 'square root EXP(x) 'exponential LOG(x) 'natural logarithm x ^ y 'power 'floor, ceiling, e, and pi not available
Give a code snippet in #BASIC Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "m...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Clojure
Clojure
(spit "/dev/tape" "Hello, World!")
Give a code snippet in #Clojure The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#HicEst
HicEst
REAL :: m=4, n=2, p=3, a(m,n), b(n,p), res(m,p)   a = $ ! initialize to 1, 2, ..., m*n b = $ ! initialize to 1, 2, ..., n*p   res = 0 DO i = 1, m DO j = 1, p DO k = 1, n res(i,j) = res(i,j) + a(i,k) * b(k,j) ENDDO ENDDO ENDDO   DLG(DefWidth=4, Text=a, Text=b,Y=0, Text=res,Y=0)
Give a code snippet in #HicEst Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#8th
8th
var bucket var bucket-size   \ The 'bucket' will be a simple array of some values: : genbucket \ n -- a:new swap ( \ make a random int up to 1000 rand-pcg n:abs 1000 n:mod a:push ) swap times bucket ! ;   \ display bucket and its total: : .bucket bucket lock @ dup . space ' n:+ 0 a:redu...
Give a code snippet in #8th Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all buck...
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...
#PicoLisp
PicoLisp
(in "file.txt" (do 6 (line)) (or (line) (quit "No 7 lines")) )
Give a code snippet in #PicoLisp 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
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 ...
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC CoctailShakerSort(INT ARRAY a INT size) INT begIdx,endIdx,newBegIdx,newEndIdx,i,tmp   begIdx=0 endIdx=size-2 WHILE begIdx<=endIdx DO newBegIdx=en...
Give a code snippet in #Action.21 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Erlang
Erlang
def class Foo { """ This is a docstring. Every object in Fancy can have it's own docstring. Either defined in the source code, like this one, or by using the Object#docstring: method """ def a_method { """ Same for methods. They can have docstrings, too. """ } } Foo docstring println # prints do...
Give a code snippet in #Erlang See also Related task: Comments Related task: Here_document
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func array integer: expand_x_1 (in integer: p) is func result var array integer: ex is [] (1); local var integer: i is 0; begin for i range 0 to p - 1 do ex := [] (ex[1] * -(p - i) div (i + 1)) & ex; end for; end func;   const func boolean: aks_test (in in...
Give a code snippet in #Seed7 The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Quackery
Quackery
500 eratosthenes   [] 500 times [ i^ isprime if [ i^ 10 digitsum isprime if [ i^ join ] ] ] dup echo cr cr size echo say " additive primes found."
Give a code snippet in #Quackery Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS ent...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#K
K
{[n;k]_(*/(k-1)_1+!n)%(*/1+!k)} . 5 3 10
Give a code snippet in #K This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#C.23
C#
using System;   class Program { static double PositiveInfinity() { return double.PositiveInfinity; }   static void Main() { Console.WriteLine(PositiveInfinity()); } }
Give a code snippet in #C.23 Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Python
Python
import cmath     class Complex(complex): def __repr__(self): rp = '%7.5f' % self.real if not self.pureImag() else '' ip = '%7.5fj' % self.imag if not self.pureReal() else '' conj = '' if ( self.pureImag() or self.pureReal() or self.imag < 0.0 ) else '+' return '0....
Give a code snippet in #Python The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Pinstripe/Printer
Pinstripe/Printer
The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing gra...
#PicoLisp
PicoLisp
(load "@lib/ps.l")   (call 'lpr (pdf "pinstripes" (a4) # 595 x 842 dots (for X 595 (gray (if (bit? 1 X) 0 100) (vline X 0 842) ) ) (page) ) )
Give a code snippet in #PicoLisp The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the prin...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#Python
Python
from heapq import heappush, heappop, heapify from collections import defaultdict   def encode(symb2freq): """Huffman encode the given dict mapping symbols to weights""" heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] heapify(heap) while len(heap) > 1: lo = heappop(heap) hi = he...
Give a code snippet in #Python Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you ...
christopher/rosetta-code