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/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Phix
Phix
sequence grid = repeat(repeat(' ',100),100) integer aX = 50, aY = 50, gXY, angle = 1 -- ' '/'#'; 0,1,2,3 = NESW constant dX = {0,-1,0,1} -- (dY = reverse(dX)) while aX>=1 and aX<=100 and aY>=1 and aY<=100 do gXY = grid[aX][aY] grid[aX][aY] = 67-gXY ...
Give a code snippet in #Phix Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Forth
Forth
: -leading ( addr len -- addr' len' ) \ called "minus-leading" begin over c@ bl = \ fetch character at addr, test if blank (space) while \ cut 1 leading character by incrementing address & decrementing length 1 /string \ "cut-string" repeat ;
Give a code snippet in #Forth Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace re...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Aime
Aime
length("Hello, World!")
Give a code snippet in #Aime Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme conta...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Objective-C
Objective-C
type bool = false | true
Give a code snippet in #Objective-C Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Phix
Phix
with javascript_semantics constant lim = 1000000, {names, probs} = columnize({{"aleph", 1/5}, {"beth", 1/6}, {"gimel", 1/7}, {"daleth", 1/8}, {"he", 1/9}, {"waw", ...
Give a code snippet in #Phix Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floa...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program zumkellex641.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */   /* REMARK 2 : this program...
Give a code snippet in #AArch64_Assembly Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on ho...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#AutoHotkey
AutoHotkey
DllCall("AllocConsole") Octal(int){ While int out := Mod(int, 8) . out, int := int//8 return out } Loop { FileAppend, % Octal(A_Index) "`n", CONOUT$ Sleep 200 }
Give a code snippet in #AutoHotkey Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reach...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Haxe
Haxe
using StringTools;   class Main { static function main() { var data = haxe.io.Bytes.ofString("The quick brown fox jumps over the lazy dog"); var crc = haxe.crypto.Crc32.make(data); Sys.println(crc.hex()); } }
Give a code snippet in #Haxe Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#REXX
REXX
/*REXX program counts the number of Pythagorean triples that exist given a maximum */ /*──────────────────── perimeter of N, and also counts how many of them are primitives.*/ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N= 100 ...
Give a code snippet in #REXX A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Batch_File
Batch File
@echo off set /a answer=%random%%%(10-1+1)+1 set /p guess=Pick a number between 1 and 10: :loop if %guess%==%answer% (echo Well guessed! pause) else (set /p guess=Nope, guess again: goto loop)
Give a code snippet in #Batch_File Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issu...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#min
min
"Hello,How,Are,You,Today" "," split "." join print
Give a code snippet in #min Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rela...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream();   var board = [_]i8{-1} ** 8;   inline fn abs(x: var) @TypeOf(x) { return if (x < 0) -x else x; }   fn safe(c: i32, r: i32) bool { var i: i32 = 0; return while (i < c) : (i += 1) { const q = board[@intCast(u3, i)]; ...
Give a code snippet in #Zig Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tou...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Qi
Qi
(define prime?-0 K N -> true where (> (* K K) N) K N -> false where (= 0 (MOD N K)) K N -> (prime?-0 (+ K 2) N))   (define prime? 1 -> false 2 -> true N -> false where (= 0 (MOD N 2)) N -> (prime?-0 3 N))
Give a code snippet in #Qi Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
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 |...
#Nim
Nim
import parseopt, strutils   var opt: OptParser = initOptParser() str = opt.cmdLineRest.split a: int = 0 b: int = 0   try: a = parseInt(str[0]) b = parseInt(str[1]) except ValueError: quit("Invalid params. Two integers are expected.")     echo("a  : " & $a) echo("b  : " & $b) echo("a + b  : " & $(...
Give a code snippet in #Nim 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/Remove_duplicate_elements
Remove duplicate elements
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 ...
#Modula-2
Modula-2
  MODULE RemoveDuplicates;   FROM STextIO IMPORT WriteLn; FROM SWholeIO IMPORT WriteInt;   TYPE TArrayRange = [1 .. 7]; TArray = ARRAY TArrayRange OF INTEGER;   VAR DataArray, ResultArray: TArray; ResultIndex, LastResultIndex, Position: CARDINAL; IsNewNumber: BOOLEAN;   BEGIN (* Set the data. *); Data...
Give a code snippet in #Modula-2 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Elixir
Elixir
defmodule MontyHall do def simulate(n) do {stay, switch} = simulate(n, 0, 0)  :io.format "Staying wins ~w times (~.3f%)~n", [stay, 100 * stay / n]  :io.format "Switching wins ~w times (~.3f%)~n", [switch, 100 * switch / n] end   defp simulate(0, stay, switch), do: {stay, switch} defp simulate...
Give a code snippet in #Elixir Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for th...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#J
J
a.#~1=#@;: ::0:"1 'b',.a.,.'c' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
Give a code snippet in #J Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer prog...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#ooRexx
ooRexx
v='' w=' ' if v=='' Then Say 'v contains the empty string'< If length(w)>0 Then Say 'Variable w does not contain the empty string' If w='' Then Say 'this is not a good test'
Give a code snippet in #ooRexx Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#BBC_BASIC
BBC BASIC
PRINT FNsum(j, 1, 100, FNreciprocal) END   DEF FNsum(RETURN i, lo, hi, RETURN func) LOCAL temp FOR i = lo TO hi temp += FN(^func) NEXT = temp   DEF FNreciprocal = 1/i
Give a code snippet in #BBC_BASIC Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#Racket
Racket
#lang racket   (define (lex<? a b) (cond ((null? b) #f) ((null? a) #t) ((= (car a) (car b)) (lex<? (cdr a) (cdr b))) (else (< (car a) (car b)))))   (lex<? '(1 2 3 4 5) '(1 2 3 4 4)) ; -> #f  
Give a code snippet in #Racket sorting 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 |...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#F.23
F#
  // A program that will run in the interpreter (fsi.exe) printf "Goodbye, World!";;   // A compiled program [<EntryPoint>] let main args = printf "Goodbye, World!" 0  
Give a code snippet in #F.23 Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin primality test or Rabin–Miller prima...
#OCaml
OCaml
  (* Translated from the wikipedia pseudo-code *) let miller_rabin n ~iter:k = (* return r and d where n = 2^r*d (from scheme implementation) *) let get_rd n = let rec loop r d = (* not even *) if Z.(equal (logand d one) one) then (r,d) else loop Z.(r + one) Z.(div d ~$2) i...
Give a code snippet in #OCaml This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin prima...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Nanoquery
Nanoquery
println " ________ ________ ________ ________ ________ ___ ___ _______ ________ ___ ___ " println "|\\ ___ \\|\\ __ \\|\\ ___ \\|\\ __ \\|\\ __ \\|\\ \\|\\ \\|\\ ___ \\ |\\ __ \\ |\\ \\ / /| " println "\\ \\ \\\\ \\ \\ \\ \\|\\ \\ \\ \\\\ \\ \\ \\ \\|\\ \\ \\...
Give a code snippet in #Nanoquery Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#SSEM
SSEM
11101000000000100000000000000000 0. -23 to c 10011000000000010000000000000000 1. Sub. 25 10010000000001100000000000000000 2. c to 9 10101000000000010000000000000000 3. Sub. 21 11010000000001100000000000000000 4. c to 11 10010000000000100000000000000000 5. -9 to c 10010000000001100000000000000000 6. c to 9...
Give a code snippet in #SSEM Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definiti...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Befunge
Befunge
~:"z"`#v_:"m"`#v_:"`"` |>  :"Z"`#v_:"M"`#v_:"@"`|>  : 0 `#v_@v-6-7< > , < <+6+7 <<v
Give a code snippet in #Befunge Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#E
E
def makeNounExpr := <elang:evm.makeNounExpr>   def dynVarName(name) { def variable := makeNounExpr(null, name, null)   return e`{   def a := 1 def b := 2 def c := 3   { def $variable := "BOO!" [a, b, c] }   }`.eval(safeScope) }   ? dynVarName("...
Give a code snippet in #E Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
christopher/rosetta-code
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#J
J
require 'math/misc/linear' augmentR_I1=: ,. e.@i.@# NB. augment matrix on the right with its Identity matrix matrix_invGJ=: # }."1 [: gauss_jordan@augmentR_I1
Give a code snippet in #J Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. string-case-85.   DATA DIVISION. WORKING-STORAGE SECTION. 01 example PIC X(9) VALUE "alphaBETA".   01 result PIC X(9).   PROCEDURE DIVISION. DISPLAY "Example: " example   *> Using the intrinsic functions. ...
Give a code snippet in #COBOL Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not r...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#S-BASIC
S-BASIC
  comment Return the rot13 transformation of s, preserving case and passing non-alphabetic characters without change end   function rot13(s = string) = string var i, k = integer var ch = char var normal, rotated = string normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" rotated = "NOPQRSTUV...
Give a code snippet in #S-BASIC Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-...
christopher/rosetta-code
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity
Abelian sandpile model/Identity
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addition on sandpiles is done by a...
#Ruby
Ruby
class Sandpile   def initialize(ar) = @grid = ar   def to_a = @grid.dup   def + (other) res = self.to_a.zip(other.to_a).map{|row1, row2| row1.zip(row2).map(&:sum) } Sandpile.new(res) end   def stable? = @grid.flatten.none?{|v| v > 3}   def avalanche topple until stable? self end   def =...
Give a code snippet in #Ruby Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addi...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Tcl
Tcl
  puts "Enter width:" set width [gets stdin] puts "Enter height:" set height [gets stdin] # Initialize array for {set i 0} {$i < $width} {incr i} { for {set j 0} {$j < $height} {incr j} { set arr($i,$j) "" } } # Store value set arr(0,0) "abc" # Print value puts "Element (0/0): $arr(0,0)" # Cleanup array unset arr  
Give a code snippet in #Tcl Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those number...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#GB_BASIC
GB BASIC
10 print "Hello world!"
Give a code snippet in #GB_BASIC Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard erro...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Ruby
Ruby
str = "asdf" reversed = str.reverse
Give a code snippet in #Ruby Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Sidef
Sidef
# Read var csvfile = %f'data.csv'; var fh = csvfile.open_r; var header = fh.line.trim_end.split(','); var csv = fh.lines.map { .trim_end.split(',').map{.to_num} }; fh.close;   # Write var out = csvfile.open_w; out.say([header..., 'SUM'].join(',')); csv.each { |row| out.say([row..., row.sum].join(',')) }; out.close;
Give a code snippet in #Sidef CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, chan...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#C.2B.2B
C++
    #include <string> #include <regex> #include <algorithm> #include <numeric> #include <sstream>   bool CheckFormat(const std::string& isin) { std::regex isinRegEpx(R"([A-Z]{2}[A-Z0-9]{9}[0-9])"); std::smatch match; return std::regex_match(isin, match, isinRegEpx); }   std::string CodeISIN(const std::string& isin) ...
Give a code snippet in #C.2B.2B An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the corre...
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 ...
#K
K
{:[x<3;1;_f[x-1]+_f[x-2]]}
Give a code snippet in #K 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 gen...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   make do io.put_string ("Survivor is prisoner: " + execute (12, 4).out) end   execute (n, k: INTEGER): INTEGER -- Survivor of 'n' prisoners, when every 'k'th is executed. require n_positive: n > 0 k_positive: k > 0 n_larger: n > k local killidx:...
Give a code snippet in #Eiffel Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {...
christopher/rosetta-code
http://rosettacode.org/wiki/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.   ...
#CLU
CLU
% Sieve of Erastothenes % Returns an array [1..max] marking the primes sieve = proc (max: int) returns (array[bool]) prime: array[bool] := array[bool]$fill(1, max, true) prime[1] := false   for p: int in int$from_to(2, max/2) do if prime[p] then for comp: int in int$from_to_by(p*2, max,...
Give a code snippet in #CLU 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:  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#XPL0
XPL0
code ChOut=8, CrLf=9, IntOut=11;   ffunc M; \forward-referenced function declaration   func F(N); int N; return if N=0 then 1 else N - M(F(N-1));   func M(N); int N; return if N=0 then 0 else N - F(M(N-1));   int I; [for I:= 0 to 19 do [IntOut(0, F(I)); ChOut(0, ^ )]; CrLf(0); for I:= 0 to 19 do [IntOut(0, M(I)); ...
Give a code snippet in #XPL0 Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n )...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Lasso
Lasso
local(haystack) = array('Zig', 'Zag', 'Wally', 'Ronald', 'Bush', 'Krusty', 'Charlie', 'Bush', 'Bozo')   #haystack->findindex('Bush')->first // 5 #haystack->findindex('Bush')->last // 8   protect => {^ handle_error => {^ error_msg ^} fail_if(not #haystack->findindex('Washington')->first,'Washington is not in...
Give a code snippet in #Lasso Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle th...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Ring
Ring
  # Project : Hilbert curve   load "guilib.ring"   paint = null x1 = 0 y1 = 0   new qapp { win1 = new qwidget() { setwindowtitle("Hilbert curve") setgeometry(100,100,400,500) label1 = new qlabel(win1) { setgeometry(10,1...
Give a code snippet in #Ring Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Action.21
Action!
TYPE Unicode=[BYTE bc1,bc2,bc3] BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]   BYTE FUNC DecodeHex(CHAR c) BYTE i   FOR i=0 TO 15 DO IF c=hex(i) THEN RETURN (i) FI OD Break() RETURN (255)   BYTE FUNC DecodeHex2(CHAR c1,c2) BYTE h1,h2,res   h1=DecodeHex(c1) h2=DecodeHex(...
Give a code snippet in #Action.21 As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes...
christopher/rosetta-code
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[FindPeriodGroup] FindPeriodGroup[n_Integer] := Which[57 <= n <= 70, {8, n - 53} , 89 <= n <= 102, {9, n - 85} , 1 <= n <= 118, {ElementData[n, "Period"], ElementData[n, "Group"]} , True, Missing["Element does not exist"] ] Row[{"Element ", #, " -> ", FindPeriodGroup[#]}] & /@ {1, 2, 29, 42,...
Give a code snippet in #Mathematica.2FWolfram_Language Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Hough_transform
Hough transform
Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displaystyle (\rho ,\theta )} , ...
#BBC_BASIC
BBC BASIC
Width% = 320 Height% = 240   VDU 23,22,Width%;Height%;8,16,16,128 *DISPLAY Pentagon.bmp OFF   DIM hist%(Width%-1, Height%-1)   rs = 2 * SQR(Width%^2 + Height%^2) / Height% : REM Radial step ts = PI / Width% : REM Angular step h% = Height% / 2   REM Hough trans...
Give a code snippet in #BBC_BASIC Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplicative_order
Multiplicative order
The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient also for large numbers is ...
#C
C
ulong mpow(ulong a, ulong p, ulong m) { ulong r = 1; while (p) { if ((1 & p)) r = r * a % m; a = a * a % m; p >>= 1; } return r; }   ulong ipow(ulong a, ulong p) { ulong r = 1; while (p) { if ((1 & p)) r = r * a; a *= a; p >>= 1; } return r; }   ulong gcd(ulong m, ulong n) { ulong t; while (m) { t...
Give a code snippet in #C The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m). Example The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do. One possible algorithm that is efficient...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Phix
Phix
with javascript_semantics requires("1.0.0") include mpfr.e atom t0 = time() mpz z = mpz_init() for i=1 to 25 do integer pi = get_prime(i) mpz_ui_pow_ui(z,2,pi) mpz_sub_ui(z,z,1) string zs = mpz_get_str(z), fs = mpz_factorstring(mpz_pollard_rho(z)) if fs!=zs then zs &= " = "&fs end if ...
Give a code snippet in #Phix The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_database
Simple database
Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be a collection (CDs, coins, base...
#REBOL
REBOL
rebol [author: "Nick Antonaccio"] write/append %rdb "" db: load %rdb switch system/options/args/1 [ "new" [write/append %rdb rejoin [now " " mold/only next system/options/args newline]] "latest" [print copy/part tail sort/skip db 4 -4] "latestcat" [ foreach cat unique extract at db 3 4 [ ...
Give a code snippet in #REBOL Task Write a simple tool to track a small set of data. The tool should have a command-line interface to enter at least two different values. The entered data should be stored in a structured format and saved to disk. It does not matter what kind of data is being tracked.   It could be...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Go
Go
func printLogic(a, b bool) { fmt.Println("a and b is", a && b) fmt.Println("a or b is", a || b) fmt.Println("not a is", !a) }
Give a code snippet in #Go 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 Con...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Factor
Factor
USING: kernel math ; IN: rosettacode.fibonacci.ar   : fib ( n -- m ) dup 0 < [ "fib of negative" throw ] when [  ! If n < 2, then drop q, else find q(n - 1) + q(n - 2). [ dup 2 < ] dip swap [ drop ] [ [ [ 1 - ] dip dup call ] [ [ 2 - ] dip dup call ] 2bi + ] if ...
Give a code snippet in #Factor While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwan...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function hailstone (n) ... $ v=[n]; $ repeat $ if mod(n,2) then n=3*n+1; $ else n=n/2; $ endif; $ v=v|n; $ until n==1; $ end; $ return v; $ endfunction >hailstone(27), length(%) [ 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 ...
Give a code snippet in #Euler_Math_Toolbox The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   =...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_regression
Polynomial regression
Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficients are (3, 2, 1). This task is i...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <numeric> #include <vector>   void polyRegression(const std::vector<int>& x, const std::vector<int>& y) { int n = x.size(); std::vector<int> r(n); std::iota(r.begin(), r.end(), 0); double xm = std::accumulate(x.begin(), x.end(), 0.0) / x.size(); doub...
Give a code snippet in #C.2B.2B Find an approximating polynomial of known degree for a given data. Example: For input data: x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; The approximating polynomial is: 3 x2 + 2 x + 1 Here, the polynomial's coefficien...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#Fantom
Fantom
  using xml   class XmlInput { public static Void main () { // create the XML parser parser := XParser(File("sample-xml.xml".toUri).in) // parse the document, creating an XML document XDoc doc := parser.parseDoc // walk through each child element from the root of the document doc.root.elems...
Give a code snippet in #Fantom Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Scheme
Scheme
  (import (scheme base) (scheme char) (scheme file) (scheme write) (srfi 125) ; hash tables (srfi 132)) ; sorting library   ;; read in the words (define (read-groups) (with-input-from-file "unixdict.txt" (lambda () (let ((groups (hash-table string=?))) ...
Give a code snippet in #Scheme When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in ...
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
1+Fold[1.+#1/#2&,1,Range[10,2,-1]]
Give a code snippet in #Mathematica.2FWolfram_Language 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/P-value_correction
P-value correction
Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted p-values are sometimes called "q...
#C.2B.2B
C++
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector>   std::vector<int> seqLen(int start, int end) { std::vector<int> result;   if (start == end) { result.resize(end + 1); std::iota(result.begin(), result.end(), 1); } else if (start < end) { ...
Give a code snippet in #C.2B.2B Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate. This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1]. The adjusted...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main(A) h := (0 < integer(\A[1])) | 4 # cells high w := (0 < integer(\A[2])) | 5 # cells wide u := (10 < integer(\A[3])) | 30 # length of cell side HoneyComb(h,w,u) end   $define INACTIVE "light yellow" $define ACTIVE "light purple...
Give a code snippet in #Icon_and_Unicon The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in col...
christopher/rosetta-code
http://rosettacode.org/wiki/Floyd-Warshall_algorithm
Floyd-Warshall algorithm
The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been checked for loops, parallel ...
#D
D
import std.stdio;   void main() { int[][] weights = [ [1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1] ]; int numVertices = 4;   floydWarshall(weights, numVertices); }   void floydWarshall(int[][] weights, int numVertices) { import std.array;   real...
Give a code snippet in #D The Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights. Task Find the lengths of the shortest paths between all pairs of vertices of the given directed graph. Your code may assume that the input has already been c...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Pike
Pike
> int x=10; Result: 10 > x * 5; Result: 50 > dump wrapper Last compiled wrapper: 001: mapping(string:mixed) ___hilfe = ___Hilfe->variables; 002: # 1 003: mixed ___HilfeWrapper() { return (([mapping(string:int)](mixed)___hilfe)->x) * 5; ; } 004: >
Give a code snippet in #Pike x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Python
Python
from collections import defaultdict   def order_words(words): byfirst = defaultdict(set) for word in words: byfirst[word[0]].add( word ) #byfirst = dict(byfirst) return byfirst   def linkfirst(byfirst, sofar): '''\ For all words matching last char of last word in sofar as FIRST char and ...
Give a code snippet in #Python A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the c...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Arturo
Arturo
loop split.every:10 [1] ++ map 2..100 'x -> last chop factors x 'row [ print map to [:string] row 'r -> pad r 5 ]
Give a code snippet in #Arturo Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Groovy
Groovy
  def normal = "http://foo bar/" def encoded = URLEncoder.encode(normal, "utf-8") println encoded  
Give a code snippet in #Groovy Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes...
christopher/rosetta-code
http://rosettacode.org/wiki/Tarjan
Tarjan
This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in graph theory for finding the strongly...
#Raku
Raku
sub tarjan (%k) { my %onstack; my %index; my %lowlink; my @stack; my @connected;   sub strong-connect ($vertex) { state $index = 0; %index{$vertex} = $index; %lowlink{$vertex} = $index++; %onstack{$vertex} = True; @stack.push: $vertex; ...
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Graph. 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) Tarjan's algorithm is an algorithm in graph t...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#ERRE
ERRE
PROGRAM NARCISISTIC   !$DOUBLE   BEGIN N=0 LOOP C$=MID$(STR$(N),2) LENG=LEN(C$) SUM=0 FOR I=1 TO LENG DO C=VAL(MID$(C$,I,1)) SUM+=C^LENG END FOR IF N=SUM THEN PRINT(N;) COUNT=COUNT+1 EXIT IF COUNT=25 END IF N=N+1 END LOO...
Give a code snippet in #ERRE A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Perl
Perl
#!/usr/bin/env perl use strict; use warnings; use feature qw/say/; use List::Util qw(first);   my %Likes = ( M => { abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /], bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /], col => [qw/ hope eve abi dee bea fay ivy gay cath jan /], dan => ...
Give a code snippet in #Perl Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#M2000_Interpreter
M2000 Interpreter
  Print str$(7.125,"00000.000")  
Give a code snippet in #M2000_Interpreter Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#Fortran
Fortran
program basic_stats implicit none   integer, parameter :: i64 = selected_int_kind(18) integer, parameter :: r64 = selected_real_kind(15) integer(i64), parameter :: samples = 1000000000_i64   real(r64) :: r real(r64) :: mean, stddev real(r64) :: sumn = 0, sumnsq = 0 integer(i64) :: n = 0 integer(i64) ...
Give a code snippet in #Fortran Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
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 |...
#Harbour
Harbour
procedure Test( a, b ) ? "a+b", a + b ? "a-b", a - b ? "a*b", a * b // The quotient isn't integer, so we use the Int() function, which truncates it downward. ? "a/b", Int( a / b ) // Remainder: ? "a%b", a % b // Exponentiation is also a base arithmetic operation ? "a**b", a ** b return
Give a code snippet in #Harbour Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/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.   ...
#Racket
Racket
#lang racket   (require math/number-theory)   (define (sum-of-digits n (σ 0)) (if (zero? n) σ (let-values (((q r) (quotient/remainder n 10))) (sum-of-digits q (+ σ r)))))   (define (additive-prime? n) (and (prime? n) (prime? (sum-of-digits n))))   (define additive-primes<500 (filter additive-pri...
Give a code snippet in #Racket 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Yabasic
Yabasic
sub floor(x) return int(x + .05) end sub   SUB ASort$(matriz$()) local last, gap, first, tempi$, tempj$, i, j   last = arraysize(matriz$(), 1)   gap = floor(last / 10) + 1 while(TRUE) first = gap + 1 for i = first to last tempi$ = matriz$(i) j = i - gap while(TRUE) tempj$ =...
Give a code snippet in #Yabasic Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if ...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_integerness
Test integerness
Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Given a rational, real, or co...
#J
J
isInt =: (= <.) *. (= {.@+.)
Give a code snippet in #J Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Gi...
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...
#Batch_File
Batch File
:: Bulls and Cows Task from Rosetta Code :: Batch File Implementation   @echo off setlocal enabledelayedexpansion :: initialization :begin set "list_chars=123456789" set "list_length=9" set "code=" set "code_length=4" %== this should be less than 10 ==% set "tries=0" %== number of tries ==% :: generate the code t...
Give a code snippet in #Batch_File 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Ol
Ol
  (define (quibble . args) (display "{") (let loop ((args args)) (unless (null? args) (begin (display (car args)) (cond ((= 1 (length args)) #t) ((= 2 (length args)) (display " and ")) (else (display ", "))) (loop (...
Give a code snippet in #Ol Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#BaCon
BaCon
PRAGMA INCLUDE <openssl/sha.h> PRAGMA LDFLAGS -lcrypto   OPTION MEMTYPE unsigned char   DECLARE result TYPE unsigned char*   result = SHA256("Rosetta code", 12, 0)   FOR i = 0 TO SHA256_DIGEST_LENGTH-1 PRINT PEEK(result+i) FORMAT "%02x" NEXT   PRINT
Give a code snippet in #BaCon SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b78...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Scala
Scala
object TextFileSlurper extends App { val fileLines = try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch { case e: java.io.FileNotFoundException => e.getLocalizedMessage() } }
Give a code snippet in #Scala Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Wren
Wren
import "/big" for BigInt, BigRat import "/fmt" for Fmt   var factorial = Fn.new { |n| if (n < 2) return BigInt.one var fact = BigInt.one for (i in 2..n) fact = fact * i return fact }   var almkvistGiullera = Fn.new { |n, print| var t1 = factorial.call(6*n) * 32 var t2 = 532*n*n + 126*n + 9 v...
Give a code snippet in #Wren The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#jq
jq
def naive_agm(a; g; tolerance): def abs: if . < 0 then -. else . end; def _agm: # state [an,gn] if ((.[0] - .[1])|abs) > tolerance then [add/2, ((.[0] * .[1])|sqrt)] | _agm else . end; [a, g] | _agm | .[0] ;
Give a code snippet in #jq This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to c...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#GAP
GAP
# GAP has built-in support for quaternions   A := QuaternionAlgebra(Rationals); # <algebra-with-one of dimension 4 over Rationals>   b := BasisVectors(Basis(A)); # [ e, i, j, k ]   q := [1, 2, 3, 4]*b; # e+(2)*i+(3)*j+(4)*k   # Conjugate ComplexConjugate(q); # e+(-2)*i+(-3)*j+(-4)*k   # Division 1/q; # (1/30)*e+(-1/15)...
Give a code snippet in #GAP Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number mi...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Maple
Maple
getDiff := proc(b1,b2) local r: r := frem(b2 - b1, 360): if r >= 180 then r := r - 360: fi: return r: end proc: getDiff(20,45); getDiff(-45,45); getDiff(-85,90); getDiff(-95,90); getDiff(-45,125); getDiff(-45,145); getDiff(29.4803, -88.6381); getDiff(-78.3251,-159.036); getDiff(-70099.74233810938,29840.67437876723)...
Give a code snippet in #Maple Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   ...
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...
#BASIC
BASIC
s$ = "alphaBETA" PRINT UCASE$(s$) PRINT LCASE$(s$)
Give a code snippet in #BASIC Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not r...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the widt...
#Perl
Perl
use strict; use warnings; use Data::IEEE754::Tools <nextUp nextDown>;   sub safe_add { my($a,$b) = @_; my $c = $a + $b; return $c, nextDown($c), nextUp($c) }   printf "%.17f (%.17f, %.17f)\n", safe_add (1/9,1/7);
Give a code snippet in #Perl Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additional...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#AppleScript
AppleScript
-- arithmetic_mean :: [Number] -> Number on arithmetic_mean(xs)   -- sum :: Number -> Number -> Number script sum on |λ|(accumulator, x) accumulator + x end |λ| end script   foldl(sum, 0, xs) / (length of xs) end arithmetic_mean   -- geometric_mean :: [Number] -> Number on ge...
Give a code snippet in #AppleScript Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th...
#C.2B.2B
C++
#include <iostream> #include <string.h>   int main() { std::string longLine, longestLines, newLine;   while (std::cin >> newLine) { auto isNewLineShorter = longLine.c_str(); auto isLongLineShorter = newLine.c_str(); while (*isNewLineShorter && *isLongLineShorter) { ...
Give a code snippet in #C.2B.2B Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the chall...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Vedit_macro_language
Vedit macro language
#11 = 0 // needspeeling = FALSE #12 = 0 // seedsremoved = FALSE Reg_Empty(21) // fullname Reg_Empty(22) // favouritefruit Reg_Empty(23) // otherfamily   File_Open("|(PATH_ONLY)\example.cfg")   if (Search("|<FULLNAME|s", BEGIN+ADVANCE+NOERR)) { Match("=",...
Give a code snippet in #Vedit_macro_language The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a...
christopher/rosetta-code
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Wren
Wren
import "/big" for BigInt import "/math" for Int import "/fmt" for Fmt   var vecprod = Fn.new { |primes| var le = primes.count if (le == 0) return BigInt.one var s = List.filled(le, null) for (i in 0...le) s[i] = BigInt.new(primes[i]) while (le > 1) { var c = (le/2).floor for(i in 0.....
Give a code snippet in #Wren Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primor...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Emacs_Lisp
Emacs Lisp
(vconcat '[1 2 3] '[4 5] '[6 7 8 9]) => [1 2 3 4 5 6 7 8 9]
Give a code snippet in #Emacs_Lisp Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Logo
Logo
to div.checked :a :b if :b = 0 [(throw "divzero 0)] output :a / :b end to div.safely :a :b output catch "divzero [div.checked :a :b] end
Give a code snippet in #Logo Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#UNIX_Shell
UNIX Shell
#!/bin/ksh # tested with ksh93s+   builtin printf   integer a=0 integer b=0   read a?"Enter value of a: " || { print -u2 "Input of a aborted." ; exit 1 ; } read b?"Enter value of b: " || { print -u2 "Input of b aborted." ; exit 1 ; }   if (( a < b )) ; then printf "%d is less than %d\n" a b fi if (( a == b )) ; the...
Give a code snippet in #UNIX_Shell Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringDrop["input string",1] StringDrop["input string",-1] StringTake["input string",{2,-2}]  
Give a code snippet in #Mathematica.2FWolfram_Language The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and la...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Rust
Rust
use std::collections::btree_map::BTreeMap; use std::{env, process}; use std::io::{self, Read, Write}; use std::fmt::Display; use std::fs::File;   fn main() { let filename = env::args().nth(1) .ok_or("Please supply a file name") .unwrap_or_else(|e| exit_err(e, 1));   let mut buf = String::new(); ...
Give a code snippet in #Rust Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assi...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Red
Red
Red [ Purpose: "100 Doors Problem (Perfect Squares)" Author: "Barry Arthur" Date: "07-Oct-2016" ] doors: make vector! [char! 8 100] repeat i 100 [change at doors i #"."]   repeat i 100 [ j: i while [j <= 100] [ door: at doors j change door either #"O" = first door [#"."] [#"O"] j: j + i ...
Give a code snippet in #Red There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...)...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Perl
Perl
#! /usr/bin/perl   use strict;   use Image::Imlib2;   # create the "canvas" my $img = Image::Imlib2->new(200,200);   # fill with a plain RGB(A) color $img->set_color(255, 0, 0, 255); $img->fill_rectangle(0,0, 200, 200);   # set a pixel to green (at 40,40) $img->set_color(0, 255, 0, 255); $img->draw_point(40,40);   # "g...
Give a code snippet in #Perl Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB col...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Haskell
Haskell
class Shape a where perimeter :: a -> Double area :: a -> Double {- A type class Shape. Types belonging to Shape must support two methods, perimeter and area. -}   data Rectangle = Rectangle Double Double {- A new type with a single constructor. In the case of data types which have only one constructor, we...
Give a code snippet in #Haskell In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the c...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#VBScript
VBScript
  Function IsSelfDescribing(n) IsSelfDescribing = False Set digit = CreateObject("Scripting.Dictionary") For i = 1 To Len(n) k = Mid(n,i,1) If digit.Exists(k) Then digit.Item(k) = digit.Item(k) + 1 Else digit.Add k,1 End If Next c = 0 For j = 0 To Len(n)-1 l = Mid(n,j+1,1) If digit.Exists(CStr(...
Give a code snippet in #VBScript Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Java
Java
loop1: while (x != 0) { loop2: for (int i = 0; i < 10; i++) { loop3: do { //some calculations... if (/*some condition*/) { //this continue will skip the rest of the while loop code and start it over at the next iteration continue loop1; } ...
Give a code snippet in #Java Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#OCaml
OCaml
#load "unix.cma";; let seconds = read_int ();; print_endline "Sleeping...";; Unix.sleep seconds;; (* number is integer in seconds *) print_endline "Awake!";;
Give a code snippet in #OCaml Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#F.23
F#
let isqrt n = let rec iter t = let d = n - t*t if (0 <= d) && (d < t+t+1) // t*t <= n < (t+1)*(t+1) then t else iter ((t+(n/t))/2) iter 1   let rec gcd a b = let t = a % b if t = 0 then b else gcd b t   let coprime a b = gcd a b = 1   let num_to ms = let mutable ctr = 0 l...
Give a code snippet in #F.23 A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Stata
Stata
import "/sort" for Cmp, Sort   var data = [ ["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"] ]   // for sorting by country var cmp = Fn.new { |p1, p2| Cmp.string.call(p1[0], p2[0]) }   // for sorting by city var cmp2 = Fn.new { |p1, p2| Cmp.string.call(p1[1], p2[1]) }   System.print("Ini...
Give a code snippet in #Stata 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Factor
Factor
USING: arrays fry kernel make sequences ;   IN: rosetta-code.multisplit   : ?pair ( ? x -- {?,x}/f ) over [ 2array ] [ 2drop f ] if ;   : best-separator ( seq -- pos index ) dup [ first ] map infimum '[ first _ = ] find nip first2 ;   : first-subseq ( separators seq -- n separator ) dupd [ swap [ subseq-sta...
Give a code snippet in #Factor It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task ...
christopher/rosetta-code
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a self-balancing binary search tree....
#Haskell
Haskell
data Tree a = Leaf | Node Int (Tree a) a (Tree a) deriving (Show, Eq)   foldTree :: Ord a => [a] -> Tree a foldTree = foldr insert Leaf   height :: Tree a -> Int height Leaf = -1 height (Node h _ _ _) = h   depth :: Tree a -> Tree a -> Int depth a b = succ (max (height a) (height b))   ins...
Give a code snippet in #Haskell This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#BlitzMax
BlitzMax
SuperStrict   Framework BRL.StandardIO   spellIt( 99) spellIt( 300) spellIt( 310) spellIt( 1501) spellIt( 12609) spellIt( 512609) spellIt( 43112609) spellIt(1234567890)     Type TSpell   Field smallNumbers:String[] = ["zero", "one", "two", "three", "four", "five", .. "six", "seven", "...
Give a code snippet in #BlitzMax Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than p...
christopher/rosetta-code