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/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...
#COBOL
COBOL
IDENTIFICATION DIVISION. CLASS-ID. my-class INHERITS base.   *> The 'INHERITS base' and the following ENVIRONMENT DIVISION *> are optional (in Visual COBOL). ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. CLASS base.   *> There is no way (...
Give a code snippet in #COBOL 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 cla...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Maxima
Maxima
a: 2988348162058574136915891421498819466320163312926952423791023078876139$ b: 2351399303373464486466122544523690094744975233415544072992656881240319$ power_mod(a, b, 10^40); /* 1527229998585248450016808958343740453059 */
Give a code snippet in #Maxima Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Fortran
Fortran
IT = ICHAR(TEXT(I:I)) - ICHAR("a") !More symbols precede "a" than "A". IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A")) !In a-z? Convert!
Give a code snippet in #Fortran File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of exte...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#Arturo
Arturo
bases: ["A" "T" "G" "C"] dna: map 1..200 => [sample bases]   prettyPrint: function [in][ count: #[ A: 0, T: 0, G: 0, C: 0 ]   loop.with:'i split.every:50 in 'line [ prints [pad to :string i*50 3 ":"] print map split.every:10 line => join   loop split line 'ch [ case [ch=] ...
Give a code snippet in #Arturo Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C...
christopher/rosetta-code
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#Racket
Racket
  #lang racket   (define dutch-colors '(red white blue))   (define (dutch-order? balls)  ;; drop each color from the front, should end up empty (null? (for/fold ([r balls]) ([color dutch-colors]) (dropf r (curry eq? color)))))   (define (random-balls) (define balls (for/list ([i (random 20)]) ...
Give a code snippet in #Racket The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the c...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#TXR
TXR
#include <stdio.h>   int query(int (*callback)(char *, size_t *)) { char buffer[1024]; size_t size = sizeof buffer;   if (callback(buffer, &size) == 0) { puts("query: callback failed"); } else { char *ptr = buffer;   while (size-- > 0) putchar (*ptr++); putchar('\n'); } }
Give a code snippet in #TXR This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, si...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
SetAttributes[drawcircle, HoldFirst]; drawcircle[img_, {x0_, y0_}, r_, color_: White] := Module[{f = 1 - r, ddfx = 1, ddfy = -2 r, x = 0, y = r, pixels = {{0, r}, {0, -r}, {r, 0}, {-r, 0}}}, While[x < y, If[f >= 0, y--; ddfy += 2; f += ddfy]; x++; ddfx += 2; f += ddfx; pixels = Join[pixels, {{x, y}, {x, ...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
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 ...
#Maxima
Maxima
/* fib(n) is built-in; here is an implementation */ fib2(n) := (matrix([0, 1], [1, 1])^^n)[1, 2]$   fib2(100)-fib(100); 0   fib2(-10); -55
Give a code snippet in #Maxima The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AutoHotkey
AutoHotkey
StoogeSort(L, i:=1, j:=""){ if !j j := L.MaxIndex() if (L[j] < L[i]){ temp := L[i] L[i] := L[j] L[j] := temp } if (j - i > 1){ t := floor((j - i + 1)/3) StoogeSort(L, i, j-t) StoogeSort(L, i+t, j) StoogeSort(L, i, j-t) } return L }
Give a code snippet in #AutoHotkey Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your p...
#Common_Lisp
Common Lisp
(defpackage #:parallel-brute-force (:use #:cl #:lparallel))   (in-package #:parallel-brute-force)   (defparameter *alphabet* "abcdefghijklmnopqrstuvwxyz") (defparameter *hash0* "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad") (defparameter *hash1* "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d...
Give a code snippet in #Common_Lisp Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0,0)   DIM dict$(26000), sort$(26000), indx%(26000)   REM Load the dictionary: dict% = OPENIN("C:\unixdict.txt") IF dict%=0 ERROR 100, "No dictionary file" index% = 0 REPEAT index% += 1 dict$(index%) = GET$#dict%...
Give a code snippet in #BBC_BASIC Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Oz
Oz
declare %% Read width and height from stdin class TextFile from Open.file Open.text end StdIn = {New TextFile init(name:stdin)} Width = {String.toInt {StdIn getS($)}} Height = {String.toInt {StdIn getS($)}} %% create array Arr = {Array.new 1 Width unit} in for X in 1..Width do Arr.X := {Array.new 1...
Give a code snippet in #Oz 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#PowerShell
PowerShell
  function Get-HuffmanEncodingTable ( $String ) { # Create leaf nodes $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol'  ; Expression = { $_.Name } }, @{ Label = 'Count'  ; Expression = { $_.Count } }, ...
Give a code snippet in #PowerShell Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#C
C
#include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h>   #define MAX(x,y) ((x) > (y) ? (x) : (y)) #define MIN(x,y) ((x) < (y) ? (x) : (y))   /* Find base-20 digits. */ size_t base20(unsigned int n, uint8_t *out) { /* generate digits */ uint8_t *start = out; do {*out++ = n % 20;} whi...
Give a code snippet in #C Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─r...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#zkl
zkl
const Diamonds=1, Spades=3, Clubs=0, Hearts=2, Ace=1; // informational var suits=T(0x1F0D1,0x1F0C1,0x1F0B1,0x1F0A1); //unicode 🃑,🃁,🂱,🂡   class Card{ fcn init(pip,suit){ // or 0..51 reg p,s; if(vm.numArgs==1){ s=pip/13; p=pip%13; } else { p=pip; s=suit } var [const] _pip=p, _suit=s; } fcn...
Give a code snippet in #zkl Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current con...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#C.2B.2B
C++
#include<iostream> #include<algorithm> #include<string.h>   using namespace std; double result; double capacity = 15; int NumberOfItems; int number;   struct items { char name[32]; double weight; double price; double m; } item[256];   bool cmp(items a,items b) { return a.price/a.weight > b.price/b.w...
Give a code snippet in #C.2B.2B A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   t...
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...
#x86_Assembly
x86 Assembly
  .data string: .asciz "Test"   .text .globl main   main: pushl  %ebp movl  %esp, %ebp   pushl  %edi xorb  %al, %al movl $-1, %ecx movl $string, %edi cld repne scasb not  %ecx dec  %ecx popl  %edi   ...
Give a code snippet in #x86_Assembly 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 graphe...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#XPL0
XPL0
include c:\cxpl\codes;   func Ackermann(M, N); int M, N; [if M=0 then return N+1; if N=0 then return Ackermann(M-1, 1); return Ackermann(M-1, Ackermann(M, N-1)); ]; \Ackermann   int M, N; [for M:= 0 to 3 do [for N:= 0 to 7 do [IntOut(0, Ackermann(M, N)); ChOut(0,9\tab\)]; CrLf(0); ]; ]
Give a code snippet in #XPL0 The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Forth
Forth
vocabulary note-words get-current also note-words definitions   \ -- notes.txt variable file : open s" notes.txt" r/w open-file if s" notes.txt" r/w create-file throw then file ! ; : appending file @ file-size throw file @ reposition-file throw ; : write file @ write-file throw ; : close ...
Give a code snippet in #Forth Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#friendly_interactive_shell
friendly interactive shell
for path in $PATH echo You have $path in PATH. end
Give a code snippet in #friendly_interactive_shell Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#AutoHotkey
AutoHotkey
move(n, from, to, via) ;n = # of disks, from = start pole, to = end pole, via = remaining pole { if (n = 1) { msgbox , Move disk from pole %from% to pole %to% } else { move(n-1, from, via, to) move(1, from, to, via) move(n-1, via, to, from) } } move(64, 1, 3, 2)
Give a code snippet in #AutoHotkey Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. 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: Def...
#Kotlin
Kotlin
// version 1.1.2   class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append...
Give a code snippet in #Kotlin Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element ...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#K
K
gcd:{:[~x;y;_f[y;x!y]]} lcm:{_abs _ x*y%gcd[x;y]}   lcm .'(12 18; -6 14; 35 0) 36 42 0   lcm/1+!20 232792560
Give a code snippet in #K Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has bot...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#m4
m4
divert(-1) define(`gcd', `ifelse(eval(`0 <= (' $1 `)'),`0',`gcd(eval(`-(' $1 `)'),eval(`(' $2 `)'))', eval(`0 <= (' $2 `)'),`0',`gcd(eval(`(' $1 `)'),eval(`-(' $2 `)'))', eval(`(' $1 `) == 0'),`0',`gcd(eval(`(' $2 `) % (' $1 `)'),eval(`(' $1 `)'))', eval(`(' $2 `)'))') divert`'dnl dnl gc...
Give a code snippet in #m4 Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest co...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Kotlin
Kotlin
// Kotlin Native v0.6.2   import kotlinx.cinterop.* import platform.posix.*   fun talk(s: String) { val pid = fork() if (pid < 0) { perror("fork") exit(1) } if (pid == 0) { execlp("espeak", "espeak", s, null) perror("espeak") _exit(1) } memScoped { val ...
Give a code snippet in #Kotlin Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Inform_7
Inform 7
Higher Order Functions is a room.   To decide which number is (N - number) added to (M - number) (this is addition): decide on N + M.   To decide which number is multiply (N - number) by (M - number) (this is multiplication): decide on N * M.   To demonstrate (P - phrase (number, number) -> number) as (title - text):...
Give a code snippet in #Inform_7 Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Ruby
Ruby
class NumberWithUncertainty def initialize(number, error) @num = number @err = error.abs end attr_reader :num, :err   def +(other) if other.kind_of?(self.class) self.class.new(num + other.num, Math::hypot(err, other.err)) else self.class.new(num + other, err) end end   def -(...
Give a code snippet in #Ruby If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Ada
Ada
declare Data : Storage_Array (1..20); -- Data created begin Data := (others => 0); -- Assign all zeros if Data = (1..10 => 0) then -- Compare with 10 zeros declare Copy : Storage_Array := Data; -- Copy Data begin if Data'Length = 0 then -- If empty ... end if;...
Give a code snippet in #Ada Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accordi...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#X86_Assembly
X86 Assembly
section .data msg db 'Goodbye, World!', 0AH len equ $-msg   section .text global _start _start: mov edx, len mov ecx, msg mov ebx, 2 mov eax, 4 int 80h   mov ebx, 1 mov eax, 1 int 80h
Give a code snippet in #X86_Assembly Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standa...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Erlang
Erlang
  -module( mean_angle ). -export( [from_degrees/1, task/0] ).   from_degrees( Angles ) -> Radians = [radians(X) || X <- Angles], Sines = [math:sin(X) || X <- Radians], Coses = [math:cos(X) || X <- Radians], degrees( math:atan2( average(Sines), average(Coses) ) ).   task() -> Angles = [[350, 10], [90, 180, 270, 360...
Give a code snippet in #Erlang When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int, Nums import "/sort" for Find   var humble = Fn.new { |n| var h = List.filled(n, 0) h[0] = 1 var next2 = 2 var next3 = 3 var next5 = 5 var next7 = 7 var i = 0 var j = 0 var k = 0 var l = 0 for (m in 1...n) { h[m] = Nums.min...
Give a code snippet in #Wren Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above ...
christopher/rosetta-code
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#C
C
#include <stdio.h> static char const *animals[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" }; static char const *verses[] = { "I don't know why she swallowed that fly.\nPerhaps she'll die\n", "That wiggled and jiggled and tickled inside her", "H...
Give a code snippet in #C Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#F.23
F#
let toFloat x = x |> int |> fun n -> n - 48 |> float let power x = toFloat x ** toFloat x |> int let isMunchausen n = n = (string n |> Seq.map char |> Seq.map power |> Seq.sum)   printfn "%A" ([1..5000] |> List.filter isMunchausen)
Give a code snippet in #F.23 A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Lua
Lua
local json = require("json")   local json_data = [=[[ 42, 3.14159, [ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ], { "H": 1, "He": 2, "X": null, "Li": 3 }, null, true, false ]]=]   print("Original JSON: " .. json_data) local data = json.decode(json_data) json.util.printValue(data, ...
Give a code snippet in #Lua Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Ruby
Ruby
require 'tk'   $root = TkRoot.new("title" => "Pendulum Animation") $canvas = TkCanvas.new($root) do width 320 height 200 create TkcLine, 0,25,320,25, 'tags' => 'plate', 'width' => 2, 'fill' => 'grey50' create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => "", 'fill' => 'grey50' create TkcLine, 1,1,...
Give a code snippet in #Ruby One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and an...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#R
R
  thue_morse <- function(steps) { sb1 <- "0" sb2 <- "1" for (idx in 1:steps) { tmp <- sb1 sb1 <- paste0(sb1, sb2) sb2 <- paste0(sb2, tmp) } sb1 } cat(thue_morse(6), "\n")  
Give a code snippet in #R Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#J
J
lcg=: adverb define 0 m lcg y NB. default seed of 0 : 'a c mod'=. x: m }. (mod | c + a * ])^:(<y+1) x )   rand_bsd=: (1103515245 12345 , <.2^31) lcg rand_ms=: (2^16) <.@:%~ (214013 2531011 , <.2^31) lcg
Give a code snippet in #J The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Purity
Purity
  data compose = f => g => $f . $g  
Give a code snippet in #Purity Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT i=1024 LOOP PRINT i i=i/2 IF (i==0) EXIT ENDLOOP
Give a code snippet in #TUSCRIPT Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Down...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Racket
Racket
  #lang racket  
Give a code snippet in #Racket Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#PARI.2FGP
PARI/GP
matrref(M)= { my(s=matsize(M),t=s[1]); for(i=1,s[2], if(M[t,i]==0, next); M[t,] /= M[t,i]; for(j=1,t-1, M[j,] -= M[j,i]*M[t,] ); for(j=t+1,s[1], M[j,] -= M[j,i]*M[t,] ); if(t--<1,break) ); M; } addhelp(matrref, "matrref(M): Returns the reduced row-echelon form of the matrix M.");
Give a code snippet in #PARI.2FGP Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is conve...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#11l
11l
dc.l TrapString_Bus dc.l TrapString_Addr dc.l TrapString_Illegal dc.l TrapString_Div0 dc.l TrapString_chk dc.l TrapString_v dc.l TrapString_priv dc.l TrapString_trace   TrapString_Bus: dc.b "Bus error",255 even TrapString_Addr: dc.b "Address error",255 even TrapString_Illegal: dc.b "Illegal Instruction",25...
Give a code snippet in #11l This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Crea...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#11l
11l
V majors = ‘north east south west’.split(‘ ’) majors *= 2 V quarter1 = ‘N,N by E,N-NE,NE by N,NE,NE by E,E-NE,E by N’.split(‘,’) V quarter2 = quarter1.map(p -> p.replace(‘NE’, ‘EN’))   F degrees2compasspoint(=d) d = (d % 360) + 360 / 64 V majorindex = Int(d / 90) V minorindex = Int((d % 90 * 4) I/ 45) V p1 ...
Give a code snippet in #11l There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Percentage_difference_between_images
Percentage difference between images
basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The expected difference for these two...
#Fortran
Fortran
program ImageDifference   use RCImageBasic use RCImageIO   implicit none   integer, parameter :: input1_u = 20, & input2_u = 21   type(rgbimage) :: lenna1, lenna2 real :: totaldiff     open(input1_u, file="Lenna100.ppm", action="read") open(input2_u, file="Lenna50.ppm",...
Give a code snippet in #Fortran basic bitmap storage Useful for comparing two JPEG images saved with a different compression ratios. You can use these pictures for testing (use the full-size version of each): 50% quality JPEG 100% quality JPEG link to full size 50% image link to full size 100% image The ...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Coq
Coq
  Require Import Coq.Lists.List. (* https://coq.inria.fr/library/Coq.Lists.List.html *)   Require Import Coq.Strings.String. (* https://coq.inria.fr/library/Coq.Strings.String.html *)   Require Import Coq.Strings.Ascii. (* https://coq.inria.fr/library/Coq.Strings.Ascii.html *)   Require Import Coq.Init.Nat. (* https://...
Give a code snippet in #Coq Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#Ada
Ada
generic type Element_Type is private; Zero : Element_Type; with function "-" (Left, Right : in Element_Type) return Element_Type is <>; with function "*" (Left, Right : in Element_Type) return Element_Type is <>; with function "/" (Left, Right : in Element_Type) return Element_Type is <>; package Matrice...
Give a code snippet in #Ada Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient ...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#PowerShell
PowerShell
  <# .Synopsis Creates a new "Deck" which is a hashtable converted to a dictionary This is only used for creating the deck, to view/list the deck contents use Get-Deck. .DESCRIPTION Casts the string value that the user inputs to the name of the variable that holds the "deck" Creates a global variable, allow...
Give a code snippet in #PowerShell Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the curr...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#TorqueScript
TorqueScript
// numbers and objects if(%num == 1) { foo(); } else if(%obj == MyObject.getID()) { bar(); } else { deusEx(); }   // strings if(%str $= "Hello World") { foo(); } else if(%str $= "Bye World") { bar(); } else { deusEx(); }
Give a code snippet in #TorqueScript Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#VBScript
VBScript
Dim grid(9, 9) Dim gridSolved(9, 9)   Public Sub Solve(i, j) If i > 9 Then 'exit with gridSolved = Grid For r = 1 To 9 For c = 1 To 9 gridSolved(r, c) = grid(r, c) Next 'c Next 'r Exit Sub End If For n = 1 To 9 If isSafe(i, j, n) Then nTm...
Give a code snippet in #VBScript Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
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 |...
#Common_Lisp
Common Lisp
(let ((a (read *standard-input*)) (b (read *standard-input*))) (cond ((not (numberp a)) (format t "~A is not a number." a)) ((not (numberp b)) (format t "~A is not a number." b)) ((< a b) (format t "~A is less than ~A." a b)) ((> a b) (format t "~A is greater than ~A." a b)) ((= ...
Give a code snippet in #Common_Lisp Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Logo
Logo
to dotprod :a :b output apply "sum (map "product :a :b) end   show dotprod [1 3 -5] [4 -2 -1]  ; 3
Give a code snippet in #Logo Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1]...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Java
Java
import java.util.HashMap; import java.util.Map;   public class orderedSequence { public static void main(String[] args) { Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACG...
Give a code snippet in #Java Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATG...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#BASIC
BASIC
  100 INPUT "MATRIX SIZE:"; SIZE% 110 GOSUB 200"IDENTITYMATRIX 120 FOR R = 0 TO SIZE% 130 FOR C = 0 TO SIZE% 140 LET S$ = CHR$(13) 150 IF C < SIZE% THEN S$ = " " 160 PRINT IM(R, C) S$; : NEXT C, R 170 END   200 REMIDENTITYMATRIX SIZE% 210 LET SIZE% = SIZE% - 1 220 DIM IM(SIZE%, SIZE%) 230 FO...
Give a code snippet in #BASIC Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#APL
APL
damm←{⎕IO←0 tbl←⍉⍪0 3 1 7 5 9 8 6 4 2 tbl⍪← 7 0 9 2 1 5 4 8 6 3 tbl⍪← 4 2 0 6 8 7 1 3 5 9 tbl⍪← 1 7 5 0 9 8 3 7 2 6 tbl⍪← 6 1 2 3 0 4 5 9 7 8 tbl⍪← 3 6 7 4 2 0 9 5 8 1 tbl⍪← 5 8 6 9 7 2 0 1 3 4 tbl⍪← 8 9 4 5 3 6 2 0 1 7 tbl⍪← 9 4 3 8 6 1 7 2 0 5 tbl⍪← 2 5 8 1 4 3 6 7 9 0 0={...
Give a code snippet in #APL The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.23
C#
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b)...
Give a code snippet in #C.23 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Multi-base_primes
Multi-base primes
Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different base. 107 base 10 converted...
#Rust
Rust
// [dependencies] // primal = "0.3"   fn digits(mut n: u32, dig: &mut [u32]) { for i in 0..dig.len() { dig[i] = n % 10; n /= 10; } }   fn evalpoly(x: u64, p: &[u32]) -> u64 { let mut result = 0; for y in p.iter().rev() { result *= x; result += *y as u64; } result ...
Give a code snippet in #Rust Prime numbers are prime no matter what base they are represented in. A prime number in a base other than 10 may not look prime at first glance. For instance: 19 base 10 is 25 in base 7. Several different prime numbers may be expressed as the "same" string when converted to a different...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#PL.2FI
PL/I
declare x(5) initial (1,3,5,7,8); x = sqrt(x); x = sin(x);
Give a code snippet in #PL.2FI Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#PHP
PHP
  <?php   session_start();   if(isset($_SESSION['number'])) { $number = $_SESSION['number']; } else { $_SESSION['number'] = rand(1,10); }     if($_POST["guess"]){ $guess = htmlspecialchars($_POST['guess']);   echo $guess . "<br />"; if ($guess < $number) { echo "Your guess is too low"; } ...
Give a code snippet in #PHP Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: high...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#FreeBASIC
FreeBASIC
' version 20-06-2015 ' compile with: fbc -s console   Function reverse(norm As String) As String   Dim As String rev Dim As Integer i, l = Len(norm) -1   rev = norm For i = 0 To l rev[l-i] = norm[i] Next   Return rev   End Function   ' ------=< MAIN >=------   Dim As Integer i, j, count,...
Give a code snippet in #FreeBASIC A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#ALGOL_68
ALGOL 68
  BEGIN COMMENT Algol 68 Genie checks for integer overflow whereas the reference language leaves the result undefined so for portability we need to see how wide a variable must be to hold the maximum possible value before range reduction. This occurs in the BSD RNG when rseed=2147483647 and is therefore ...
Give a code snippet in #ALGOL_68 The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyl...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Rust
Rust
// alternatively, fn dot_product(a: &Vec<u32>, b: &Vec<u32>) // but using slices is more general and rustic fn dot_product(a: &[i32], b: &[i32]) -> Option<i32> { if a.len() != b.len() { return None } Some( a.iter() .zip( b.iter() ) .fold(0, |sum, (el_a, el_b)| sum + el_a*el_b) ...
Give a code snippet in #Rust Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1]...
christopher/rosetta-code
http://rosettacode.org/wiki/Consecutive_primes_with_ascending_or_descending_differences
Consecutive primes with ascending or descending differences
Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for primes   <   1,000,000. If there...
#Pari.2FGP
Pari/GP
showPrecPrimes(p, n)= { my(v=vector(n)); v[n]=p; forstep(i=n-1,1,-1, v[i]=precprime(v[i+1]-1) ); for(i=1,n, print1(v[i]" ")); } list(lim)= { my(p=3,asc,dec,ar,dr,arAt=3,drAt=3,last=2); forprime(q=5,lim, my(g=q-p); if(g<last, asc=0; if(desc++>dr, dr=desc; drAt=q ...
Give a code snippet in #Pari.2FGP Task Find and display here on this page, the longest sequence of consecutive prime numbers where the differences between the primes are strictly ascending. Do the same for sequences of primes where the differences are strictly descending. In both cases, show the sequence for ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Maxima
Maxima
originalMatrix : matrix([1, 1, 1, 1], [2, 4, 8, 16], [3, 9, 27, 81], [4, 16, 64, 256], [5, 25, 125, 625]); transposedMatrix : transpose(originalMatrix);
Give a code snippet in #Maxima Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   precedence   and   associativity...
#Go
Go
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F ...
Give a code snippet in #Go This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   prec...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Lua
Lua
function analyze(s) print(string.format("Examining [%s] which has a length of %d:", s, string.len(s))) if string.len(s) > 1 then local last = string.byte(string.sub(s,1,1)) for i=1,string.len(s) do local c = string.byte(string.sub(s,i,i)) if last ~= c then ...
Give a code snippet in #Lua Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each st...
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#Java
Java
import java.util.*; import java.util.stream.*;   public class StateNamePuzzle {   static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "hawaii", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kans...
Give a code snippet in #Java Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#ERRE
ERRE
  PROGRAM FFT   CONST CNT=8   !$DYNAMIC DIM REL[0],IMG[0],CMP[0],V[0]   BEGIN SIG=INT(LOG(CNT)/LOG(2)+0.9999) REAL1=2^SIG   REAL=REAL1-1 REAL2=INT(REAL1/2) REAL4=INT(REAL1/4) REAL3=REAL4+REAL2   !$DIM REL[REAL1],IMG[REAL1],CMP[REAL3]   FOR I=0 TO CNT-1 DO READ(REL[I],IMG[I]) END FOR   DATA(1,0,1,0,...
Give a code snippet in #ERRE Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnit...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Clojure
Clojure
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
Give a code snippet in #Clojure Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Phix
Phix
atom addr = allocate(512) -- limit is 1,610,612,728 bytes on 32-bit systems ... free(addr) atom addr2 = allocate(512,1) -- automatically freed when addr2 drops out of scope or re-assigned atom addr3 = allocate_string("a string",1) -- automatically freed when addr3 drops out of scope or re...
Give a code snippet in #Phix Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
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...
#PowerBASIC
PowerBASIC
FUNCTION int2Text (number AS QUAD) AS STRING IF 0 = number THEN FUNCTION = "zero" EXIT FUNCTION END IF   DIM num AS QUAD, outP AS STRING, unit AS LONG DIM tmpLng1 AS QUAD   DIM small(1 TO 19) AS STRING, tens(7) AS STRING, big(5) AS STRING   DIM tmpInt AS LONG, dcnt AS LONG   ...
Give a code snippet in #PowerBASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Comefrom0x10
Comefrom0x10
fizzbuzz mod_three = 3 mod_five = 5 comefrom fizzbuzz n comefrom fizzbuzz if n is mod_three comefrom fizzbuzz if n is mod_five n = n + 1   fizz comefrom fizzbuzz if n is mod_three 'Fizz'... mod_three = mod_three + 3 linebreak # would like to write "unless mod_three is mod_five" ...
Give a code snippet in #Comefrom0x10 Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   F...
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...
#J
J
}. 'knight' NB. drop first item night }: 'socks' NB. drop last item sock }: }. 'brooms' NB. drop first and last items room
Give a code snippet in #J 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifi...
#Lua
Lua
#!/usr/bin/lua   require "crypto"   print(crypto.digest("MD4", "Rosetta Code"))
Give a code snippet in #Lua Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Python
Python
import os   pid = os.fork() if pid > 0: # parent code else: # child code
Give a code snippet in #Python Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
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...
#Delphi
Delphi
  program Tokenize_a_string;   {$APPTYPE CONSOLE}   uses System.SysUtils;   var Words: TArray<string>;   begin Words := 'Hello,How,Are,You,Today'.Split([',']); Writeln(string.Join(#10, Words));   Readln; end.    
Give a code snippet in #Delphi 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 r...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#PL.2FI
PL/I
(subscriptrange): Hamming: procedure options (main); /* 14 November 2013 with fixes 2021 */ declare (H(2000), p2, p3, p5, twoTo31, Hm, tenP(11)) decimal(12)fixed; declare (i, j, k, m, d, w) fixed binary;   /* Quicksorts in-place the array of integers H, from lb to ub */ quicksortH: procedure( lb, ub ) recur...
Give a code snippet in #PL.2FI Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming num...
christopher/rosetta-code
http://rosettacode.org/wiki/ISBN13_check_digit
ISBN13 check digit
Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:   978-1734314502       (good)   ...
#langur
langur
val .isbn13checkdigit = f(var .s) { .s = replace(.s, RE/[\- ]/) matching(re/^[0-9]{13}$/, .s) and fold(f{+}, map [_, f{x 3}], s2n .s) div 10 }   val .tests = h{ "978-1734314502": true, "978-1734314509": false, "978-1788399081": true, "978-1788399083": false, }   for .key of .tests { ...
Give a code snippet in #langur Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ALGOL_68
ALGOL 68
DO printf($"SPAM"l$) OD
Give a code snippet in #ALGOL_68 Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   L...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#Groovy
Groovy
  import javax.mail.* import javax.mail.internet.*   public static void simpleMail(String from, String password, String to, String subject, String body) throws Exception {   String host = "smtp.gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable",true); /* mai...
Give a code snippet in #Groovy Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given....
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#PureBasic
PureBasic
Procedure.s RLDecode(toDecode.s) Protected.s repCount, output, currChar, tmp Protected *c.Character = @toDecode   While *c\c <> #Null currChar = Chr(*c\c) Select *c\c Case '0' To '9' repCount + currChar Default If repCount tmp = Space(Val(repCount)) ReplaceS...
Give a code snippet in #PureBasic Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT url_encoded="http%3A%2F%2Ffoo%20bar%2F" BUILD S_TABLE hex=":%><:><2<>2<%:" hex=STRINGS (url_encoded,hex), hex=SPLIT(hex) hex=DECODE (hex,hex) url_decoded=SUBSTITUTE(url_encoded,":%><2<>2<%:",0,0,hex) PRINT "encoded: ", url_encoded PRINT "decoded: ", url_decoded  
Give a code snippet in #TUSCRIPT This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencod...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#Elixir
Elixir
base = %{name: "Rocket Skates", price: 12.75, color: "yellow"} update = %{price: 15.25, color: "red", year: 1974} result = Map.merge(base, update) IO.inspect(result)
Give a code snippet in #Elixir Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 M...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#Groovy
Groovy
def largestInt = { c -> c.sort { v2, v1 -> "$v1$v2" <=> "$v2$v1" }.join('') as BigInteger }
Give a code snippet in #Groovy Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#MAD
MAD
R DISCORDIAN DATE CALCULATION R R PUNCH CARD SHOULD CONTAIN - R MM/DD/YYYY R IN GREGORIAN CALENDAR   NORMAL MODE IS INTEGER   VECTOR VALUES MLENGT = 0 0,0,31,59,90,120,151,181,212,243,273,304,334 VECTOR VALUES TI...
Give a code snippet in #MAD Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Visual_Basic
Visual Basic
Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function 'small Helper-Function Sub Main() Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5 Dim P&, I&, G&, A&, M, Cur(Value To Volume) Dim S As New Collection: S.Add Array(0) '<- init Solutions-Coll. Const SackW = 25, SackV = 0.25 Dim Panacea: Pana...
Give a code snippet in #Visual_Basic A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Common_Lisp
Common Lisp
(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
Give a code snippet in #Common_Lisp Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Vlang
Vlang
fn tokenize_string(s string, sep u8, escape u8) ?[]string { mut tokens := []string{} mut runes := []u8{} mut in_escape := false for r in s { if in_escape { in_escape = false runes << r } else if r == escape { in_escape = true } else if r == sep { tokens << runes.bytestr() rune...
Give a code snippet in #Vlang Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for spli...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#J
J
require 'printf' 'Mary had a %s lamb.' sprintf <'little' Mary had a little lamb.   require 'strings' ('%s';'little') stringreplace 'Mary had a %s lamb.' Mary had a little lamb. 'Mary had a %s lamb.' rplc '%s';'little' Mary had a little lamb.
Give a code snippet in #J 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Excel
Excel
sierpinskiTriangle =LAMBDA(c, LAMBDA(n, IF(0 = n, c, LET( prev, sierpinskiTriangle(c)(n - 1),   APPENDROWS( sierpCentered(prev) )( sierpDoubled(prev) ) ) ) ...
Give a code snippet in #Excel Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given f...
#Nim
Nim
import posix   let MAP_ANONYMOUS {.importc: "MAP_ANONYMOUS", header: "<sys/mman.h>".}: cint   proc test(a, b: cint): cint = # mov EAX, [ESP+4] # add EAX, [ESP+8] # ret var code = [0x8B'u8, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3]   # create an executable buffer var buf = mmap(nil, sizeof(code), PROT_REA...
Give a code snippet in #Nim The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembl...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Go
Go
package main   import ( "container/heap" "fmt" "strings" )   type CubeSum struct { x, y uint16 value uint64 }   func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] }   type CubeSumHeap []*CubeSum   func (h CubeSumHeap) Len() int { return len(h) } func (h CubeSumHeap) Less(i, j int) bool {...
Give a code snippet in #Go A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Euphoria
Euphoria
  printf(1,"Exponential:\t%e, %e, %e, %e\n",{-10.1246,10.2356,16.123456789,64.12}) printf(1,"Floating Point\t%03.3f, %04.3f, %+3.3f, %3.3f\n",{-10.1246,10.2356,16.123456789,64.12}) printf(1,"Floating Point or Exponential:  %g, %g, %g, %g\n",{10,16.123456789,64,123456789.123})  
Give a code snippet in #Euphoria Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or B...
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 |...
#SenseTalk
SenseTalk
Ask "Provide Any Number"   Put It into A   Ask " Provide Another Number"   Put it into B   if A is less than B Put A&" Is less than " &B end if   if A is greater than B Put A& " is Greater than " &B end if   If A is Equal to B Put A& " is Equal to " &B End If
Give a code snippet in #SenseTalk 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#Excel
Excel
=LAMBDA(isUpper, LAMBDA(matrix, LET( nCols, COLUMNS(matrix), nRows, ROWS(matrix), ixs, SEQUENCE(nRows, nCols, 0, 1), x, MOD(ixs, nCols), y, QUOTIENT(ixs, nRows),   IF(nCols=nRows, LET( p, LAMBDA(x, y,...
Give a code snippet in #Excel Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
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. ...
#D
D
import std.stdio, core.thread;   void main() { write("Enter a time to sleep (in seconds): ");   long secs; readf(" %d", &secs);   writeln("Sleeping..."); Thread.sleep(dur!"seconds"(secs)); writeln("Awake!"); }
Give a code snippet in #D 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...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#Vlang
Vlang
import crypto.sha1   fn main() { println("${sha1.hexhash('Rosetta Code')}")//Rosetta code   mut h := sha1.new() h.write('Rosetta Code'.bytes()) ? println('${h.checksum().map(it.hex()).join('')}') }
Give a code snippet in #Vlang SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to ide...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Kotlin
Kotlin
// version 1.1.4-3   import javax.swing.JFrame import javax.swing.JPanel import java.awt.Graphics import java.awt.Graphics2D import java.awt.Color import java.awt.Dimension import java.awt.BorderLayout import java.awt.RenderingHints import javax.swing.SwingUtilities   class XorPattern : JPanel() {   init { ...
Give a code snippet in #Kotlin Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Maxima
Maxima
nums : [3,1,4,1,5,9]; sum(nums[i]^2,i,1,length(nums));
Give a code snippet in #Maxima Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#CoffeeScript
CoffeeScript
heronArea = (a, b, c) -> s = (a + b + c) / 2 Math.sqrt s * (s - a) * (s - b) * (s - c)   isHeron = (h) -> h % 1 == 0 and h > 0   gcd = (a, b) -> leftover = 1 dividend = if a > b then a else b divisor = if a > b then b else a until leftover == 0 leftover = dividend % divisor if le...
Give a code snippet in #CoffeeScript Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#BaCon
BaCon
s$ = "prepend" s$ = "String " & s$ PRINT s$
Give a code snippet in #BaCon Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code