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/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#360_Assembly
360 Assembly
* Do-While DOWHILE CSECT , This program's control section BAKR 14,0 Caller's registers to linkage stack LR 12,15 load entry point address into Reg 12 USING DOWHILE,12 tell assembler we use Reg 12 as base XR 9,9 ...
Give a code snippet in #360_Assembly Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Peripheral_drift_illusion
Peripheral drift illusion
Task Generate and display a Peripheral Drift Illusion The image appears to be moving even though it is perfectly static. Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host. References Codepen demo.
#Action.21
Action!
PROC DrawTile(INT x BYTE y,flip,c1,c2) BYTE i   Color=1 FOR i=y+2 TO y+11 DO Plot(x+1,i) DrawTo(x+5,i) OD Color=c1 IF flip THEN Plot(x,y+12) DrawTo(x,y) DrawTo(x+6,y) ELSE Plot(x,y) DrawTo(x+6,y) DrawTo(x+6,y+12) FI Plot(x+1,y+1) DrawTo(x+5,y+1) Color=c2 IF flip THEN Plot(x,y+13)...
Give a code snippet in #Action.21 Task Generate and display a Peripheral Drift Illusion The image appears to be moving even though it is perfectly static. Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host. References Codepen demo.
christopher/rosetta-code
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#Python
Python
#!/usr/bin/env python #-*- coding: utf-8 -*-   from OpenGL.GL import * from OpenGL.GLUT import *   def paint(): glClearColor(0.3,0.3,0.3,0.0) glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)   glShadeModel(GL_SMOOTH)   glLoadIdentity() glTranslatef(-15.0, -15.0, 0.0)   glBegin(GL_TRIANGLES) ...
Give a code snippet in #Python Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
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...
#Kotlin
Kotlin
// version 1.0.6 fun main(args: Array<String>) { val s = "José" println("The char length is ${s.length}") println("The byte length is ${Character.BYTES * s.length}") }
Give a code snippet in #Kotlin 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 con...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#ALGOL_68
ALGOL 68
print( ( "5**3**2: ", 5**3**2, newline ) ); print( ( "(5**3)**2: ", (5**3)**2, newline ) ); print( ( "5**(3**2): ", 5**(3**2), newline ) )
Give a code snippet in #ALGOL_68 This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of...
#Rust
Rust
fn egyptian_divide(dividend: u32, divisor: u32) -> (u32, u32) { let dividend = dividend as u64; let divisor = divisor as u64;   let pows = (0..32).map(|p| 1 << p); let doublings = (0..32).map(|p| divisor << p);   let (answer, sum) = doublings .zip(pows) .rev() .skip_while(|(i...
Give a code snippet in #Rust Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, an...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game/Player
Pig the dice game/Player
Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strategies involved. Show play dur...
#Sidef
Sidef
var (games=100) = ARGV.map{.to_i}...   define DIE = 1..6; define GOAL = 100;   class Player(score=0, ante=0, rolls=0, strategy={false}) { method turn { rolls = 0; ante = 0; loop { rolls++; given (var roll = DIE.rand) { when (1) { a...
Give a code snippet in #Sidef Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play stra...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#PowerShell
PowerShell
$n = 0 do { $n++ $n } while ($n % 6 -ne 0)
Give a code snippet in #PowerShell Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Lua
Lua
a = 1 -- Here we declare a numeric variable fruit = "banana" -- Here we declare a string datatype needspeeling = True -- This is a boolean local b = 2 -- This variable declaration is prefixed with a scope modifier
Give a code snippet in #Lua Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Nim
Nim
  proc accumulator[T: SomeNumber](x: T): auto = var sum = float(x) result = proc (n: float): float = sum += n result = sum   let acc = accumulator(1) echo acc(5) # 6 discard accumulator(3) # Create another accumulator. echo acc(2.3) # 8.3  
Give a code snippet in #Nim A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passe...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#VBScript
VBScript
  Set objXMLDoc = CreateObject("msxml2.domdocument")   Set objRoot = objXMLDoc.createElement("CharacterRemarks") objXMLDoc.appendChild objRoot   Call CreateNode("April","Bubbly: I'm > Tam and <= Emily") Call CreateNode("Tam O'Shanter","Burns: ""When chapman billies leave the street ...""") Call CreateNode("Emily","Shor...
Give a code snippet in #VBScript Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks>...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#Cowgol
Cowgol
include "cowgol.coh";   # Comparator interface, on the model of C, i.e: # foo < bar => -1, foo == bar => 0, foo > bar => 1 typedef CompRslt is int(-1, 1); interface Comparator(foo: intptr, bar: intptr): (rslt: CompRslt);   # Quicksort an array of pointer-sized integers given a comparator function # (This is the closest...
Give a code snippet in #Cowgol Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Erlang
Erlang
% create the list: L = lists:seq(1, 10).   % and compute its sum: S = lists:sum(L). P = lists:foldl(fun (X, P) -> X * P end, 1, L).
Give a code snippet in #Erlang Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Vedit_macro_language
Vedit macro language
for (#1 = 1; #1 <= 5; #1++) { for (#2 = 1; #2 <= #1; #2++) { Type_Char('*') } Type_Newline }
Give a code snippet in #Vedit_macro_language “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over a...
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...
#zkl
zkl
const RED=0, WHITE=1, BLUE=2; var BALLS=T(RED,WHITE,BLUE); fcn colorBalls(balls){ balls.apply(T("red","white","blue").get).concat(", "); }   reg balls, sortedBalls; do{ balls=(0).pump(12,List,fcn{ BALLS[(0).random(3)] }); // create list of 12 random balls sortedBalls=balls.sort(); // balls is read only, sort crea...
Give a code snippet in #zkl 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 colo...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
$ vu <1:1> f str1 str2 sep: <1:2> join sep [ str2 "" str1 ] <1:3> <2:1> . f "Rosetta" "Code" ":" "Rosetta::Code"
Give a code snippet in #D.C3.A9j.C3.A0_Vu Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#BASIC
BASIC
10 DEFINT A-Z 20 INPUT "Lower limit? ",L 30 INPUT "Upper limit? ",H 40 IF L>H THEN PRINT "Invalid input": END 50 PRINT "My guess is ";(H-L)\2+L 55 T=T+1 60 INPUT "Too low (L), too high (H), or correct (C)? ",R$ 70 ON INSTR("LlHhCc",R$) GOTO 90,90,100,100,110,110 80 PRINT "Invalid input": GOTO 50 90 L=(H-L)\2+L: GOTO 40...
Give a code snippet in #BASIC Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#EchoLisp
EchoLisp
  (lib 'struct) ;; tables are based upon structures (lib 'sql) ;; sql-select function   ;; input table (define emps (make-table (struct emp (name id salary dept)))) ;; output table (define high (make-table (struct out (dept name salary))))   ;; sort/group procedure (define (get-high num-records: N into: high) (sql-s...
Give a code snippet in #EchoLisp Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ...
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.
#PureBasic
PureBasic
Procedure handleError(x, msg.s) If Not x MessageRequester("Error", msg) End EndIf EndProcedure   #ScreenW = 320 #ScreenH = 210 handleError(OpenWindow(0, 0, 0, #ScreenW, #ScreenH, "Animated Pendulum", #PB_Window_SystemMenu), "Can't open window.") handleError(InitSprite(), "Can't setup sprite display.") handl...
Give a code snippet in #PureBasic 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Liberty_BASIC
Liberty BASIC
  dim Array(10)   Array(0) = -1 Array(10) = 1   print Array( 0), Array( 10)   REDIM Array( 100)   print Array( 0), Array( 10)   Array( 0) = -1 print Array( 0), Array( 10)    
Give a code snippet in #Liberty_BASIC This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, a...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#Perl
Perl
package Automaton { sub new { my $class = shift; my $rule = [ reverse split //, sprintf "%08b", shift ]; return bless { rule => $rule, cells => [ @_ ] }, $class; } sub next { my $this = shift; my @previous = @{$this->{cells}}; $this->{cells} = [ @{$this->{rule}}[ map ...
Give a code snippet in #Perl Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting suc...
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...
#ALGOL_68
ALGOL 68
STRING digits = "123456789";   [4]CHAR chosen; STRING available := digits; FOR i TO UPB chosen DO INT c = ENTIER(random*UPB available)+1; chosen[i] := available[c]; available := available[:c-1]+available[c+1:] OD;   COMMENT print((chosen, new line)); # Debug # END COMMENT   OP D = (INT d)STRING: whole(d,...
Give a code snippet in #ALGOL_68 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Ruby
Ruby
File.open("tape.file", "w") do |fh| fh.syswrite("This code should be able to write a file to magnetic tape.\n") end
Give a code snippet in #Ruby The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
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...
#Pascal
Pascal
{ # a class is a package (i.e. a namespace) with methods in it package MyClass;   # a constructor is a function that returns a blessed reference sub new { my $class = shift; bless {variable => 0}, $class; # the instance object is a hashref in disguise. # (it can be a ...
Give a code snippet in #Pascal In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the cl...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Vlang
Vlang
fn k_prime(n int, k int) bool { mut nf := 0 mut nn := n for i in 2 .. nn+1 { for nn % i == 0 { if nf == k { return false } nf++ nn/=i } } return nf == k }   fn gen(k int, n int) []int { mut r := []int{len:n} mut ...
Give a code snippet in #Vlang A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#C
C
  #include<stdio.h>   typedef struct{ int a; }layer1;   typedef struct{ layer1 l1; float b,c; }layer2;   typedef struct{ layer2 l2; layer1 l1; int d,e; }layer3;   void showCake(layer3 cake){ printf("\ncake.d = %d",cake.d); printf("\ncake.e = %d",cake.e); printf("\ncake.l1.a = %d",cake.l1.a); printf("\ncake.l2...
Give a code snippet in #C Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facili...
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)   ...
#BCPL
BCPL
get "libhdr"   let checkISBN(s) = valof $( let tally = 0 unless s%0 = 14 resultis false unless s%4 = '-' resultis false   for i=1 to 3 $( let digit = s%i-'0' test i rem 2 = 0 do tally := tally + 3 * digit or tally := tally + digit $)   for i=5 to 14 $( le...
Give a code snippet in #BCPL 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:   9...
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
#8086_Assembly
8086 Assembly
;;; Sum of squares cpu 8086 bits 16 section .text org 100h jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Calculate the sum of the squares of the array in SI. ;;; The array should contain 16-bit unsigned integers. ;;; The output will be 32-bit. ;;; Input: (DS:)SI = arr...
Give a code snippet in #8086_Assembly 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/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Java
Java
public class VigenereCipher { public static void main(String[] args) { String key = "VIGENERECIPHER"; String ori = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; String enc = encrypt(ori, key); System.out.println(enc); System.out.println(decrypt(e...
Give a code snippet in #Java Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it....
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Scala
Scala
object FixCodeTags extends App { val rx = // See for regex explanation: https://regex101.com/r/N8X4x7/3/ // Flags ignore case, dot matching line breaks, unicode support s"(?is)<(?:(?:code\\s+)?(${langs.mkString("|")}))>(.+?|)<\\/(?:code|\\1)>".r   def langs = // Real list of langs goes here Seq("...
Give a code snippet in #Scala Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
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.   ...
#Perl
Perl
use strict; use warnings; use ntheory 'is_prime'; use List::Util <sum max>;   sub pp { my $format = ('%' . (my $cw = 1+length max @_) . 'd') x @_; my $width = ".{@{[$cw * int 60/$cw]}}"; (sprintf($format, @_)) =~ s/($width)/$1\n/gr; }   my($limit, @ap) = 500; is_prime($_) and is_prime(sum(split '',$_)) and...
Give a code snippet in #Perl 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/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#C.23
C#
using System; using System.Drawing; using System.Windows.Forms; static class Program { static void Main() { Application.Run(new FullScreen()); } } public sealed class FullScreen : Form { const int ColorCount = 256; public FullScreen() { FormBorderStyle = FormBorderStyle.None; WindowState = F...
Give a code snippet in #C.23 The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we ha...
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...
#Quackery
Quackery
[ over size over size != iff [ 2drop false ] done over sort over sort != iff [ 2drop false ] done true unrot witheach [ dip behead = if [ dip not conclude ] ] drop ] is deranged ( $ $ --> b )   $ 'rosetta/unixdict.txt' sharefile drop nest$ [] temp pu...
Give a code snippet in #Quackery 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. T...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Lasso
Lasso
42 0x2a
Give a code snippet in #Lasso Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should 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 |...
#LIL
LIL
# Logical operations, in LIL set first [expr 1 == 1] set second [expr 1 == 0]   func and-or-not {a b} { print a $a b $b print "a AND b" [expr $a && $b] print "a OR b " [expr $a || $b] print "NOT a " [expr !$a] }   and-or-not $first $second
Give a code snippet in #LIL 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/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Prolog
Prolog
  mean(List, Mean) :- length(List, Length), sumlist(List, Sum), Mean is Sum / Length.  
Give a code snippet in #Prolog Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an est...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Oforth
Oforth
import: math   [ 676.5203681218851, -1259.1392167224028, 771.32342877765313, -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 ] const: Gamma.Lanczos   : gamma(z) | i t | z 0.5 < ifTrue: [ Pi dup z * sin 1.0 z - gamma * / return ] z 1.0 - ->z ...
Give a code snippet in #Oforth Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/li...
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 |...
#jq
jq
def logic(a; b): "\(a) and \(b) => \(a and b)", "\(a) or \(b) => \(a or b)", "\(a) | not => \(a | not)", "if \(a) then true else false end => \(if a then true else false end)" ;
Give a code snippet in #jq 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/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Swift
Swift
enum errors: Error { //Occurs when a start or end position is given that is outside of bounds case IndexOutsideMazeBoundary } ///Used to solve any maze generated by the swift implementation of maze generator at: ///https://www.rosettacode.org/wiki/Maze_generation#Swift class MazeSolver { ///your starting in...
Give a code snippet in #Swift Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Kotlin
Kotlin
// version 1.1.2   import java.security.SecureRandom   fun main(args: Array<String>) { val rng = SecureRandom() val rn1 = rng.nextInt() val rn2 = rng.nextInt() val newSeed = rn1.toLong() * rn2 rng.setSeed(newSeed) // reseed using the previous 2 random numbers println(rng.nextInt()) // get ra...
Give a code snippet in #Kotlin Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
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 ...
#Ada
Ada
with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_Io; use Ada.Text_Io;   procedure Traversal_Example is package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); use Int_List; procedure Print(Position : Cursor) is begin Put_Line(Integer'Image(Element(Position))); end Print; The_L...
Give a code snippet in #Ada 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: Definitio...
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#PowerShell
PowerShell
  do { $keyPress = [System.Console]::ReadKey() } until ($keyPress.Key -eq "Y" -or $keyPress.Key -eq "N")   $keyPress | Format-Table -AutoSize  
Give a code snippet in #PowerShell Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pr...
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...
#Go
Go
package main   import "fmt"   var name, lyric, animals = 0, 1, [][]string{ {"fly", "I don't know why she swallowed a fly. Perhaps she'll die."}, {"spider", "That wiggled and jiggled and tickled inside her."}, {"bird", "How absurd, to swallow a bird."}, {"cat", "Imagine that, she swallowed a cat."}, {"dog", "What a...
Give a code snippet in #Go 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/QR_decomposition
QR decomposition
Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , as described in QR decompositi...
#Ada
Ada
  with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays; with Ada.Numerics.Generic_Elementary_Functions; procedure QR is   procedure Show (mat : Real_Matrix) is package FIO is new Ada.Text_IO.Float_IO (Float); begin for row in mat'Range (1) loop for co...
Give a code snippet in #Ada Any rectangular m × n {\displaystyle m\times n} matrix A {\displaystyle {\mathit {A}}} can be decomposed to a product of an orthogonal matrix Q {\displaystyle {\mathit {Q}}} and an upper (right) triangular matrix R {\displaystyle {\mathit {R}}} , a...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#ALGOL_68
ALGOL 68
# Note functions and subroutines are called procedures (or PROCs) in Algol 68 # # A function called without arguments: # f; # Algol 68 does not expect an empty parameter list for calls with no arguments, "f()" is a syntax error # # A function with a fixed number of arguments: # f(1, x);   # variable number of arguments...
Give a code snippet in #ALGOL_68 Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a...
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 ) ) , ...
#Prolog
Prolog
female(0,1). female(N,F) :- N>0, N1 is N-1, female(N1,R), male(R, R1), F is N-R1.   male(0,0). male(N,F) :- N>0, N1 is N-1, male(N1,R), female(R, R1), F is N-R1.
Give a code snippet in #Prolog 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/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Haskell
Haskell
import Data.Array (Array, Ix, (!), listArray, bounds)   -- BINARY SEARCH -------------------------------------------------------------- bSearch :: Integral a => (a -> Ordering) -> (a, a) -> Maybe a bSearch p (low, high) | high < low = Nothing | otherwise = let mid = (low + high) `div` 2 in case p mid of...
Give a code snippet in #Haskell A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#MATLAB_.2F_Octave
MATLAB / Octave
> 11 ans = 11
Give a code snippet in #MATLAB_.2F_Octave Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, b...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Luck
Luck
import "stdio.h";; import "string.h";;   let s1:string = "Hello World!";; let s2:char* = strdup(cstring(s1));; puts(s2);; free(s2 as void*)
Give a code snippet in #Luck Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can b...
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...
#Lingo
Lingo
---------------------------------------- -- @desc Class "MyClass" -- @file parent script "MyClass" ----------------------------------------   -- instance variable property _myvar   -- constructor on new (me) me._myvar = 23 return me end   -- a method on doubleAndPrint (me) me._myvar = me._myvar * 2 pu...
Give a code snippet in #Lingo 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/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#PHP
PHP
  <?php function get_subset($binary, $arr) { // based on true/false values in $binary array, include/exclude // values from $arr $subset = array(); foreach (range(0, count($arr)-1) as $i) { if ($binary[$i]) { $subset[] = $arr[count($arr) - $i - 1]; } } return $subset; }   function print_array...
Give a code snippet in #PHP A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Avail
Avail
For each row from 1 to 5 do [ For each length from 1 to row do [Print: "*";]; Print: "\n"; ];
Give a code snippet in #Avail “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structu...
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...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SORTSALIB" Sort% = FN_sortSAinit(1, 0) : REM Descending   nItems% = 9 maxWeight = 15.0   DIM items{(nItems%-1) name$, weight, price, worth} FOR item% = 0 TO nItems%-1 READ items{(item%)}.name$, items{(item%)}.weight, items{(item%)}.price items{(item%)}....
Give a code snippet in #BBC_BASIC 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;  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Peano_curve
Peano curve
Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
#Action.21
Action!
DEFINE MAXSIZE="12"   INT ARRAY angleStack(MAXSIZE) BYTE ARRAY depthStack(MAXSIZE),stageStack(MAXSIZE) BYTE stacksize=[0]   BYTE FUNC IsEmpty() IF stacksize=0 THEN RETURN (1) FI RETURN (0)   BYTE FUNC IsFull() IF stacksize=MAXSIZE THEN RETURN (1) FI RETURN (0)   PROC Push(INT angle BYTE depth,stage) IF IsFull...
Give a code snippet in #Action.21 Task Produce a graphical or ASCII-art representation of a Peano curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  {Baker, Cooper, Fletcher, Miller, Smith}; (Unequal @@ %) && (And @@ (0 < # < 6 & /@ %)) && Baker < 5 && Cooper > 1 && 1 < Fletcher < 5 && Miller > Cooper && Abs[Smith - Fletcher] > 1 && Abs[Cooper - Fletcher] > 1 // Reduce[#, %, Integers] &  
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what change...
christopher/rosetta-code
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Quackery
Quackery
[ ' [ [ 1 ] ] ' [ 1 ] rot 1 - times [ dup -1 peek nested swap witheach [ over -1 peek + join ] tuck nested join swap ] drop ] is bell's-triangle ( n --> [ )   [ bell's-triangle [] swap witheach [ 0 peek join ] ] is bell-numbers ( n --> [ )...
Give a code snippet in #Quackery Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.:...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Scala
Scala
object ChowlaNumbers { def main(args: Array[String]): Unit = { println("Chowla Numbers...") for(n <- 1 to 37){println(s"$n: ${chowlaNum(n)}")} println("\nPrime Counts...") for(i <- (2 to 7).map(math.pow(10, _).toInt)){println(f"$i%,d: ${primesPar(i).size}%,d")} println("\nPerfect Numbers...") ...
Give a code snippet in #Scala Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n ...
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...
#Erlang
Erlang
  %%% For details of the algorithms used see %%% https://en.wikipedia.org/wiki/Modular_exponentiation   -module modexp_rosetta. -export [mod_exp/3,binary_exp/2,test/0].   mod_exp(Base,Exp,Mod) when is_integer(Base), is_integer(Exp), is_integer(Mod), Base > 0, Exp > 0, Mod > 0 -> ...
Give a code snippet in #Erlang 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/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Prolog
Prolog
% SWI-Prolog has transpose/2 in its clpfd library :- use_module(library(clpfd)).   % N is the dot product of lists V1 and V2. dot(V1, V2, N) :- maplist(product,V1,V2,P), sumlist(P,N). product(N1,N2,N3) :- N3 is N1*N2.   % Matrix multiplication with matrices represented % as lists of lists. M3 is the product of M1 and M...
Give a code snippet in #Prolog Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC K2C(REAL POINTER k,c) REAL tmp   ValR("273.15",tmp) RealSub(k,tmp,c) RETURN   PROC K2F(REAL POINTER k,f) REAL tmp1,tmp2,tmp3   ValR("1.8",tmp1) ValR("459.67",tmp2) RealMult(k,tmp1,tmp3) RealSub(tmp3,tmp2,f) RETURN   PROC K2R(REAL POINTER k,f) REA...
Give a code snippet in #Action.21 There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#MAD
MAD
NORMAL MODE IS INTEGER BOOLEAN NUGGET DIMENSION NUGGET(101)   THROUGH CLEAR, FOR I=0, 1, I.G.100 CLEAR NUGGET(I) = 0B   THROUGH MARK, FOR A=0, 6, A.G.100 THROUGH MARK, FOR B=A, 9, B.G.100 THROUGH MARK, FOR C=B, 20, C.G.100 MARK ...
Give a code snippet in #MAD Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugg...
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
#D
D
#t // <boolean> true #f // <boolean> false
Give a code snippet in #D 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/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)...
#OCaml
OCaml
open Complex   let fac k n = let m2pi = -4.0 *. acos 0.0 in polar 1.0 (m2pi*.(float k)/.(float n))   let merge l r n = let f (k,t) x = (succ k, (mul (fac k n) x) :: t) in let z = List.rev (snd (List.fold_left f (0,[]) r)) in (List.map2 add l z) @ (List.map2 sub l z)   let fft lst = let rec ditfft2 a n...
Give a code snippet in #OCaml 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 magni...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Swift
Swift
import Foundation   func vampire<T>(n: T) -> [(T, T)] where T: BinaryInteger, T.Stride: SignedInteger { let strN = String(n).sorted() let fangLength = strN.count / 2 let start = T(pow(10, Double(fangLength - 1))) let end = T(Double(n).squareRoot())   var fangs = [(T, T)]()   for i in start...end where n % i...
Give a code snippet in #Swift A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#E
E
def isSorted(list) { if (list.size() == 0) { return true } var a := list[0] for i in 1..!(list.size()) { var b := list[i] if (a > b) { return false } a := b } return true }   def bogosort(list, random) { while (!isSorted(list)) { shuffle(list, random) } }
Give a code snippet in #E 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Octave
Octave
for i = 10:-1:0 % ... endfor
Give a code snippet in #Octave Task Write a   for   loop which writes a countdown from   10   to   0. 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/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#zkl
zkl
foreach n in ([10..0,-1]){ println(n) } [10..0,-1].apply() //-->L(10,9,8,7,6,5,4,3,2,1,0) // tail recursion fcn(n){ n.println(); if(n==0)return(); return(self.fcn(n-1)) }(10)
Give a code snippet in #zkl Task Write a   for   loop which writes a countdown from   10   to   0. 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/Incremen...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Astro
Astro
fun mergesort(m): if m.lenght <= 1: return m let middle = floor m.lenght / 2 let left = merge(m[:middle]) let right = merge(m[middle-1:]);   fun merge(left, right): let result = [] while not (left.isempty or right.isempty): if left[1] <= right[1]: result.push! left.shift!() ...
Give a code snippet in #Astro 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/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#PARI.2FGP
PARI/GP
program ScriptName; var prog : String; begin prog := ParamStr(0); write('Program: '); writeln(prog) end.
Give a code snippet in #PARI.2FGP The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the scr...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#360_Assembly
360 Assembly
* Create an HTML table 19/02/2017 CREHTML CSECT USING CREHTML,R13 B 72(R15) DC 17F'0' STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 end of prolog LA R8,RND XPRNT PGBODY,64 ...
Give a code snippet in #360_Assembly Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is fil...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#C.2B.2B
C++
  #include <algorithm> #include <iostream> #include <iterator> /*Generate multifactorials to 9   Nigel_Galloway November 14th., 2012. */ int main(void) { for (int g = 1; g < 10; g++) { int v[11], n=0; generate_n(std::ostream_iterator<int>(std::cout, " "), 10, [&]{n++; return v[n]=(g<n)? v[n-g]*n : n;})...
Give a code snippet in #C.2B.2B The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\d...
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
#Q
Q
ssq:{sum x*x}
Give a code snippet in #Q 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/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Elena
Elena
import extensions; import system'routines;   public program() { var dataset := new object[] { new { Name = "Lagos"; Population = 21.0r; }, new { Name = "Cairo"; Population = 15.2r; }, new { Name = "Kinshasa-Brazzaville"; Population = 11.3r; }, new { Name = "Greater Johannesbur...
Give a code snippet in #Elena Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[e...
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...
#Haskell
Haskell
import qualified Data.Char as Char   urlDecode :: String -> Maybe String urlDecode [] = Just [] urlDecode ('%':xs) = case xs of (a:b:xss) -> urlDecode xss >>= return . ((Char.chr . read $ "0x" ++ [a,b]) :) _ -> Nothing urlDecode ('+':xs) = urlDecode xs >>= return . (' ' :) urlDecode (x:xs) = urlDe...
Give a code snippet in #Haskell 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 unencode...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#PHP
PHP
<?php for($i=2008; $i<2121; $i++) { $datetime = new DateTime("$i-12-25 00:00:00"); if ( $datetime->format("w") == 0 ) { echo "25 Dec $i is Sunday\n"; } } ?>
Give a code snippet in #PHP A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 20...
christopher/rosetta-code
http://rosettacode.org/wiki/Legendre_prime_counting_function
Legendre prime counting function
The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number. then π(n) ...
#Python
Python
from primesieve import primes from math import isqrt from functools import cache   p = primes(isqrt(1_000_000_000))   @cache def phi(x, a): res = 0 while True: if not a or not x: return x + res   a -= 1 res -= phi(x//p[a], a) # partial tail recursion   def legpi(n): if n ...
Give a code snippet in #Python The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is th...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ Inventories may have keys or keys/values \\ here keys are values too Inventory Alfa="Apple", "Banana", "Coconut" \\ key 30 has value 25, other keys have value same as key. Inventory Beta=100, 30:=25, 20, 5 Print "Parallel" k=Each(Alfa) k1=Each(Alfa E...
Give a code snippet in #M2000_Interpreter 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/Conti...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Tcl
Tcl
% info object methods ::oo::class -all -private <cloned> create createWithNamespace destroy eval new unknown variable varname
Give a code snippet in #Tcl Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
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 ...
#TSE_SAL
TSE SAL
// library: math: get: ackermann: recursive <description></description> <version>1.0.0.0.5</version> <version control></version control> (filenamemacro=getmaare.s) [kn, ri, tu, 27-12-2011 14:46:59] INTEGER PROC FNMathGetAckermannRecursiveI( INTEGER mI, INTEGER nI ) IF ( mI == 0 ) RETURN( nI + 1 ) ENDIF IF ( nI == ...
Give a code snippet in #TSE_SAL 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/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#PL.2FSQL
PL/SQL
  /***************************************************************** * $Author: Atanas Kebedjiev $ ***************************************************************** * PL/SQL code can be run as anonymous block. * To test, execute the whole script or create the functions and then e.g. 'select rdecode('2012') from dua...
Give a code snippet in #PL.2FSQL Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Nim
Nim
import os, strutils, random   randomize() var w, h: int if paramCount() >= 2: w = parseInt(paramStr(1)) h = parseInt(paramStr(2)) if w <= 0: w = 30 if h <= 0: h = 30   # Initialize var univ, utmp = newSeq[seq[bool]](h) for y in 0..<h: univ[y].newSeq w utmp[y].newSeq w for x in 0 ..< w: if rand(9) < 1: ...
Give a code snippet in #Nim The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#Phix
Phix
with javascript_semantics integer seed = 675248 function random() seed = remainder(floor(seed*seed/1000),1e6) -- seed = to_integer(sprintf("%012d",seed*seed)[4..9]) return seed end function for i=1 to 5 do ?random() end for
Give a code snippet in #Phix Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the res...
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 ...
#Tcl
Tcl
proc factors {x} { # list the prime factors of x in ascending order set result [list] while {$x % 2 == 0} { lappend result 2 set x [expr {$x / 2}] } for {set i 3} {$i*$i <= $x} {incr i 2} { while {$x % $i == 0} { lappend result $i set x [expr {$x / $i}...
Give a code snippet in #Tcl 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 pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#BASIC
BASIC
charCode = 97 char = "a" PRINT CHR$(charCode) 'prints a PRINT ASC(char) 'prints 97
Give a code snippet in #BASIC Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
christopher/rosetta-code
http://rosettacode.org/wiki/ASCII_art_diagram_converter
ASCII art diagram converter
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RC...
#Vlang
Vlang
import math.big import strings   struct Result { name string size int start int end int }   fn (r Result) str() string { return "${r.name:-7} ${r.size:2} ${r.start:3} ${r.end:3}" }   fn validate(diagram string) ?[]string { mut lines := []string{} for mut line in diagram.split("\n"...
Give a code snippet in #Vlang Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opco...
christopher/rosetta-code
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function IndexOf(n As Integer, s As Integer()) As Integer For ii = 1 To s.Length Dim i = ii - 1 If s(i) = n Then Return i End If Next Return -1 End Function   Function GetDigits(n As Integer, le As Integer, digits A...
Give a code snippet in #Visual_Basic_.NET There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
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 ...
#Tcl
Tcl
set result [lsort -integer $unsorted_list]
Give a code snippet in #Tcl Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#EchoLisp
EchoLisp
  (define (modes L) (define G (group* L)) ;; sorts and group equal items (define cardmax (for/max [(g G)] (length g))) (map first (filter (lambda(g) (= cardmax (length g))) G)))   (modes '( a b c a d e f)) → (a) (modes (iota 6)) → (0 1 2 3 4 5) (modes '(x)) → (x) (modes '(🎾 🏉 ☕️ 🎾 🎲 🎯 🎺 ☕️ 🎲 🎸 🎻...
Give a code snippet in #EchoLisp 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/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#zkl
zkl
fcn mergeStreams(s1,s2,etc){ //-->Walker streams:=vm.arglist.pump(List(),fcn(s){ // prime and prune if( (w:=s.walker())._next() ) return(w); Void.Skip // stream is dry }); Walker().tweak(fcn(streams){ if(not streams) return(Void.Stop); // all streams are dry values:=streams.apply("va...
Give a code snippet in #zkl 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which t...
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...
#Sidef
Sidef
var l = ''; # Sample longest string seen. var a = ''; # Accumulator to save longest strings.   STDIN.each { |n| n.substr(l.len) ? (a = n; l = n)  : (!l.substr(n.len) && a.concat!(n)); }   print a;
Give a code snippet in #Sidef 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 challen...
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...
#M2000_Interpreter
M2000 Interpreter
  Module QBASIC_Based { supervisor: GOSUB initialize GOSUB guessing GOTO continue   initialize: \\ Not need to RANDOMIZE TIMER \\ we can use Random(1, 100) to get a number from 1 to 100 n = 0: r = INT(RND * 100 + 1): g = 0: c$ = "" RETURN   guessing: WHI...
Give a code snippet in #M2000_Interpreter 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 wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and computer science, the Levenshtein ...
#Scheme
Scheme
  (define (levenshtein s t) (define (%levenshtein s sl t tl) (cond ((zero? sl) tl) ((zero? tl) sl) (else (min (+ (%levenshtein (cdr s) (- sl 1) t tl) 1) (+ (%levenshtein s sl (cdr t) (- tl 1)) 1) (+ (%levenshtein (cdr s) (- sl 1) (cdr t) (- tl 1)) (...
Give a code snippet in #Scheme This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and co...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#R
R
stirling <- function(z) sqrt(2*pi/z) * (exp(-1)*z)^z   nemes <- function(z) sqrt(2*pi/z) * (exp(-1)*(z + (12*z - (10*z)^-1)^-1))^z   lanczos <- function(z) { if(length(z) > 1) { sapply(z, lanczos) } else { g <- 7 p <- c(0.99999999999980993, 676.5203681218851, -1259.1392167224028, 77...
Give a code snippet in #R Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library...
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#Common_Lisp
Common Lisp
  (ql:quickload :cffi)   (defconstant +SIGINT+ 2)   (defmacro set-signal-handler (signo &body body) (let ((handler (gensym "HANDLER"))) `(progn (cffi:defcallback ,handler :void ((signo :int)) (declare (ignore signo)) ,@body) (cffi:foreign-funcall "signal" :int ,signo :pointer (cffi...
Give a code snippet in #Common_Lisp Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so th...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Pascal
Pascal
my $dec = "0123459"; my $hex_noprefix = "abcf123"; my $hex_withprefix = "0xabcf123"; my $oct_noprefix = "7651"; my $oct_withprefix = "07651"; my $bin_withprefix = "0b101011001";   print 0 + $dec, "\n"; # => 123459 print hex($hex_noprefix), "\n"; # => 180154659 print hex($hex_withprefix), "\n"; # => 180154659 pr...
Give a code snippet in #Pascal It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of...
christopher/rosetta-code
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#C.2B.2B
C++
#include <string> #include <iostream> #include <boost/algorithm/string.hpp> #include <map> #include <algorithm> #include <cctype>   using namespace boost::algorithm;   bool isValid(const std::string &ibanstring) { static std::map<std::string, int> countrycodes { {"AL", 28}, {"AD", 24}, {"AT", 20}, {"AZ", 28...
Give a code snippet in #C.2B.2B This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IB...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#REXX
REXX
/* Rexx */   Parse source . . pgmPath Say pgmPath  
Give a code snippet in #REXX The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script n...
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...
#K
K
/ anagram clusters a:{x g@&1<#:'g:={x@<x}'x}@0:"unixdict.txt";   / derangements in these clusters b@&c=|/c:{#x[0]}'b:a@&{0=+//{x=y}':x}'a ("excitation" "intoxicate")
Give a code snippet in #K 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[edi...
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...
#PARI.2FGP
PARI/GP
q)3*2+1 9 q)(3*2)+1 / Brackets give the usual order of precedence 7 q)x:5 q)(x+5; x:20; x-5) 25 20 0
Give a code snippet in #PARI.2FGP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Icon_and_Unicon
Icon and Unicon
procedure main() write("P(4,2) = ",P(4,2)) write("P(8,2) = ",P(8,2)) write("P(10,8) = ",P(10,8)) write("C(10,8) = ",C(10,8)) write("C(20,8) = ",C(20,8)) write("C(60,58) = ",C(60,58)) write("P(1000,10) = ",P(1000,10)) write("P(1000,20) = ",P(1000,20)) write("P(15000,2) = ",P(15000,2))...
Give a code snippet in #Icon_and_Unicon This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from...
christopher/rosetta-code