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/Index_finite_lists_of_positive_integers
Index finite lists of positive integers
It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns an integer to any finite, arbi...
#Phix
Phix
without javascript_semantics include mpfr.e procedure rank(mpz r, sequence s) s = deep_copy(s) for i=1 to length(s) do s[i] = sprintf("%d",s[i]) end for mpz_set_str(r,join(s,'a'),11) end procedure function unrank(mpz i) sequence res = split(mpz_get_str(i,11),'a') for j=1 to length(r...
Give a code snippet in #Phix It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns ...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Oforth
Oforth
: nextGen( l ) | i s | l byteSize dup ->s String newSize s loop: i [ i 1 if=: [ 0 ] else: [ i 1- l byteAt '#' = ] i l byteAt '#' = + i s if=: [ 0 ] else: [ i 1+ l byteAt '#' = ] + 2 if=: [ '#' ] else: [ '_' ] over add ] ;   : gen( l n -- ) l dup .cr #[ nextGen dup .cr ] times(...
Give a code snippet in #Oforth Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the curren...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#C.2B.2B
C++
double fib(double n) { if(n < 0) { throw "Invalid argument passed to fib"; } else { struct actual_fib { static double calc(double n) { if(n < 2) { return n; } else { return calc(n-1) + calc(n-2); } ...
Give a code snippet in #C.2B.2B While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwa...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Scheme
Scheme
  (import (scheme base) (scheme write))   ;; -- given two sets represented as lists, return (A \ B) (define (a-without-b a b) (cond ((null? a) '()) ((member (car a) (cdr a)) ; drop head of a if it's a duplicate (a-without-b (cdr a) b)) ((member (car a) b) ; head of a is in b...
Give a code snippet in #Scheme Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Kotlin
Kotlin
import java.util.Base64   fun main() { val data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=" val decoder = Base64.getDecoder() val decoded = decoder.decode(data) val decodedStr = String(decoded, Charsets.UTF_8) p...
Give a code snippet in #Kotlin See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output w...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#BCPL
BCPL
get "libhdr";   // Reverse a string let reverse(str) = valof $( let i = 1 let j = str%0 while i<j $( let c = str%i str%i := str%j str%j := c i := i+1 j := j-1 $) resultis str $)   // Convert number to string given base let itoa(n, base, buf) = valof $( let digitcha...
Give a code snippet in #BCPL Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary,...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Scala
Scala
object Cusip extends App {   val candidates = Seq("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")   for (candidate <- candidates) printf(f"$candidate%s -> ${if (isCusip(candidate)) "correct" else "incorrect"}%s%n")   private def isCusip(s: String): Boolean = { if (s.length !=...
Give a code snippet in #Scala This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) A   CUSIP   is a nine-character alphanumeric...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Nim
Nim
import nativesockets echo getHostName()
Give a code snippet in #Nim Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Astro
Astro
fun maxpathsum(t): #: Array{Array{I}} let a = val t for i in a.length-1..-1..1, c in linearindices a[r]: a[r, c] += max(a[r+1, c], a[r=1, c+1]) return a[1, 1]   let test = [ [55], [94, 48], [95, 30, 96], [77, 71, 26, 67], [97, 13, 76, 38, 45], [07, 36, 79, 16, 37, 68], [4...
Give a code snippet in #Astro Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Pascal
Pascal
  sub insertion_sort { my (@list) = @_; foreach my $i (1 .. $#list) { my $j = $i; my $k = $list[$i]; while ( $j > 0 && $k < $list[$j - 1]) { $list[$j] = $list[$j - 1]; $j--; } $list[$j] = $k; } return @list; }   my @a = insertion_sort(4, 65...
Give a code snippet in #Pascal 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/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Factor
Factor
USING: io math.combinatorics sequences sets ;   "ABCD" all-permutations lines diff first print
Give a code snippet in #Factor ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Groovy
Groovy
println 1.00f // float (IEEE-32) println 1.00d // double (IEEE-64) println 1.00 // BigDecimal (scaled BigInteger) println 1.00g // BigDecimal println 1.00e0 // BigDecimal   assert 1.00f instanceof Float assert 1.00d instanceof Double assert 1.00 instanceof BigDecimal assert 1.00g instanceof BigDecim...
Give a code snippet in #Groovy Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Commodore_BASIC_2
Commodore BASIC
  10 D=100: DIMD(D): P=1 20 PRINT CHR$(147);"PASS: ";P 22 FOR I=P TO D STEP P: D(I)=NOTD(I): NEXT 30 IF P=100 THEN 40 32 P=P+1: GOTO20 40 PRINT: PRINT"THE FOLLOWING DOORS ARE OPEN: " 42 FOR I=1 TO D: IF D(I)=-1 THEN PRINTI; 44 NEXT  
Give a code snippet in #Commodore_BASIC_2 There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Vedit_macro_language
Vedit macro language
:HISTOGRAM: #30 = Buf_Free // #30 = buffer to store histogram data for (#9=0; #9<256; #9++) { Out_Reg(21) TC(#9) Out_Reg(Clear) // @21 = intensity value to be counted Buf_Switch(#15) // switch to image buffer #8 = Search(@21, CASE+BEGIN+ALL+NOERR) // count intensity values Buf_Switch(#30) ...
Give a code snippet in #Vedit_macro_language Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the cou...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Scala
Scala
import java.awt._ import java.awt.event.ActionEvent import java.awt.image.BufferedImage   import javax.swing._   import scala.math.{sin, sqrt}   object PlasmaEffect extends App {   SwingUtilities.invokeLater(() => new JFrame("Plasma Effect") {   class PlasmaEffect extends JPanel { private val (w, h)...
Give a code snippet in #Scala The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Run_BASIC
Run BASIC
' do it with javascript html "<script>alert('Goodbye, World!');</script>"
Give a code snippet in #Run_BASIC Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#PureBasic
PureBasic
Structure RR a.f b.f EndStructure   Procedure.f MapRange(*a.RR, *b.RR, s) Protected.f a1, a2, b1, b2 a1=*a\a: a2=*a\b b1=*b\a: b2=*b\b ProcedureReturn b1 + ((s - a1) * (b2 - b1) / (a2 - a1)) EndProcedure     ;- Test the function If OpenConsole() Define.RR Range1, Range2 Range1\a=0: Range1\b=10 Rang...
Give a code snippet in #PureBasic Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linear...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#EchoLisp
EchoLisp
  (require 'list)   ;; a card is a vector [id color number symb shading], 0 <= id < 81 (define (make-deck (id -1)) (for*/vector( [ color '(red green purple)] [ number '(one two three)] [ symb '( oval squiggle diamond)] [ shading '(solid open striped)]) (++ id) (vector id color number symb shading))) (define DECK (...
Give a code snippet in #EchoLisp Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbo...
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...
#Nim
Nim
let list = ["lorem", "ipsum", "dolor"} for item in list: echo item
Give a code snippet in #Nim 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/D...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Perl
Perl
my @points; while (@points < 100) { my ($x, $y) = (int(rand(31))-15, int(rand(31)) - 15); my $r2 = $x*$x + $y*$y; next if $r2 < 100 || $r2 > 225; push @points, [$x, $y]; }   print << 'HEAD'; %!PS-Adobe-3.0 EPSF-3.0 %%BoundingBox 0 0 400 400 200 200 translate 10 10 scale 0 setlinewidth 1 ...
Give a code snippet in #Perl Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circ...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Neko
Neko
/* dns in neko */ var host_resolve = $loader.loadprim("std@host_resolve", 1); var host_to_string = $loader.loadprim("std@host_to_string", 1); var host_reverse = $loader.loadprim("std@host_reverse", 1);   var ip = host_resolve("www.kame.net");   $print("www.kame.net: ", ip, ", ", host_to_string(ip), "\n"); $print(host_t...
Give a code snippet in #Neko DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Oforth
Oforth
'a' 'z' seqFrom
Give a code snippet in #Oforth Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Lua
Lua
local socket = require 'socket' -- needed for socket.sleep local curses = require 'curses' -- used for graphics   local naptime = 0.02 -- seconds local world_x, world_y = 100, 100   local world = (function (x, y) local wrl = {} for i = 1, y do wrl[i] = {} for j = 1, x do wrl[i][j] = 0 end end return wrl en...
Give a code snippet in #Lua Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the f...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#XSLT_2.0
XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:m="http://rosettacode.org/wiki/Stable_marriage_problem" xmlns:t="http://rosettacode.org/wiki/Stable_marriage_problem/temp" ex...
Give a code snippet in #XSLT_2.0 Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable se...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#Perl
Perl
#!/usr/bin/perl -w use strict;   # This should probably be done in a loop rather than be recursive. sub add_with_carry { my $resultref = shift; my $addend = shift; my $addendpos = shift;   push @$resultref, (0) while (scalar @$resultref < $addendpos + 1); my $addend_result = $addend + $resultref->[$addendpos]...
Give a code snippet in #Perl Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#BaCon
BaCon
  x = 1 y$ = "hello"   SWAP x, y$ PRINT y$  
Give a code snippet in #BaCon Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericit...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#MATLAB_.2F_Octave
MATLAB / Octave
mystack = {};   % push mystack{end+1} = x;   %pop x = mystack{end}; mystack{end} = [];   %peek,top x = mystack{end};   % empty isempty(mystack)
Give a code snippet in #MATLAB_.2F_Octave Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#DWScript
DWScript
func Integer.Double() { this + this } print(8.Double())
Give a code snippet in #DWScript Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
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...
#PicoLisp
PicoLisp
(foo) (bar 1 'arg 2 'mumble)
Give a code snippet in #PicoLisp 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/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...
#Io
Io
collection foreach(println)
Give a code snippet in #Io 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#COBOL
COBOL
identification division. program-id. playing-cards.   environment division. configuration section. repository. function all intrinsic.   data division. working-storage section. 77 card usage index. 01 deck. 05 cards occurs 5...
Give a code snippet in #COBOL Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current c...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Standard_ML
Standard ML
val str_reverse = implode o rev o explode; val string = "asdf"; val reversed = str_reverse string;
Give a code snippet in #Standard_ML Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string ...
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 ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT PRINT "25th of December will be a Sunday in the following years: " LOOP year=2008,2121 SET dayofweek = DATE (number,25,12,year,nummer) IF (dayofweek==7) PRINT year ENDLOOP  
Give a code snippet in #TUSCRIPT 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 betwe...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Gambas
Gambas
' Gambas module file   Public Const bottlesofbeer As String = " bottles of beer." Public Const onthewall As String = " on the wall." Public Const takeonedown As String = "Take one down, pass it around." Public Const onebeer As String = "1 bottle of beer"   Public Sub Main()   Dim bottles As Byte   For bottles = 99 ...
Give a code snippet in #Gambas Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 9...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#PicoLisp
PicoLisp
(scl 80)   (de agm (A G) (do 7 (prog1 (/ (+ A G) 2) (setq G (sqrt A G) A @) ) ) )   (round (agm 1.0 (*/ 1.0 1.0 (sqrt 2.0 1.0))) 70 )
Give a code snippet in #PicoLisp This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a functio...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Modula-3
Modula-3
MODULE Main;   BEGIN END Main.
Give a code snippet in #Modula-3 Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Xfractint
Xfractint
Dragon3 { Angle 4 Axiom XF X=XF+Y Y=XF-Y }
Give a code snippet in #Xfractint Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followe...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Scala
Scala
object CF extends App { import Stream._ val sqrt2 = 1 #:: from(2,0) zip from(1,0) val napier = 2 #:: from(1) zip (1 #:: from(1)) val pi = 3 #:: from(6,0) zip (from(1,2) map {x=>x*x})   // reference values, source: wikipedia val refPi = "3.14159265358979323846264338327950288419716939937510" val refNapi...
Give a code snippet in #Scala continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wri...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#Go
Go
package main   import ( "encoding/xml" "fmt" )   const XML_Data = ` <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOf...
Give a code snippet in #Go Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M"...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your p...
#Julia
Julia
@everywhere using SHA   @everywhere function bruteForceRange(startSerial, numberToDo) targets = ["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad", "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c...
Give a code snippet in #Julia Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb5...
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...
#jq
jq
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || fo...
Give a code snippet in #jq This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a list of   prec...
christopher/rosetta-code
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping
Sutherland-Hodgman polygon clipping
The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a...
#BBC_BASIC
BBC BASIC
VDU 23,22,200;200;8,16,16,128 VDU 23,23,2;0;0;0;   DIM SubjPoly{(8) x, y} DIM ClipPoly{(3) x, y} FOR v% = 0 TO 8 : READ SubjPoly{(v%)}.x, SubjPoly{(v%)}.y : NEXT DATA 50,150,200,50,350,150,350,300,250,300,200,250,150,350,100,250,100,200 FOR v% = 0 TO 3 : READ ClipPoly{(v%)}.x, ...
Give a code snippet in #BBC_BASIC The   Sutherland-Hodgman clipping algorithm   finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#R
R
LETTERS # [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" letters # [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"
Give a code snippet in #R Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requ...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#VBA
VBA
  Public Sub ascii() Dim s As String, i As Integer, j As Integer For i = 0 To 15 For j = 32 + i To 127 Step 16 Select Case j Case 32: s = "Spc" Case 127: s = "Del" Case Else: s = Chr(j) End Select Debug.Print Tab(10 * (j...
Give a code snippet in #VBA Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I b...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#DCL
DCL
$ close /nolog sums_of_cubes $ on control_y then $ goto clean $ open /write sums_of_cubes sums_of_cubes.txt $ i = 1 $ loop1: $ write sys$output i $ j = 1 $ loop2: $ sum = i * i * i + j * j * j $ if sum .lt. 0 $ then $ write sys$output "overflow at ", j $ goto next_i $ endif $ write sums_of_cubes f$fa...
Give a code snippet in #DCL A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also know...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#AppleScript
AppleScript
-- gcd :: Int -> Int -> Int on gcd(a, b) if b ≠ 0 then gcd(b, a mod b) else if a < 0 then -a else a end if end if end gcd  
Give a code snippet in #AppleScript Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   gr...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Ruby
Ruby
class String def wrap(width) txt = gsub("\n", " ") para = [] i = 0 while i < length j = i + width j -= 1 while j != txt.length && j > i + 1 && !(txt[j] =~ /\s/) para << txt[i ... j] i = j + 1 end para end end   text = <<END In olden times when wishing still helped on...
Give a code snippet in #Ruby Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provi...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#LSE64
LSE64
"Hello world!" ,t nl
Give a code snippet in #LSE64 Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#C
C
#include <assert.h> #include <stdbool.h> #include <stdio.h>   typedef unsigned char byte;   struct Transition { byte a, b; unsigned int c; } transitions[100];   void init() { int i, j; for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { int idx = i * 10 + j; transitions...
Give a code snippet in #C A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#TIScript
TIScript
  function printAll(separator,argv..) { if(argv.length) stdout.print(argv[0]); for (var i=1; i < argv.length; i++) stdout.print(separator, argv[i]); } printAll(" ", 4, 3, 5, 6, 4, 3); printAll(",", 4, 3, 5); printAll("! ","Rosetta", "Code", "Is", "Awesome");
Give a code snippet in #TIScript Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#11l
11l
F f(x) R sqrt(abs(x)) + 5 * x ^ 3   V s = Array(1..11) s.reverse() L(x) s V result = f(x) I result > 400 print(‘#.: #.’.format(x, ‘TOO LARGE!’)) E print(‘#.: #.’.format(x, result)) print()
Give a code snippet in #11l The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, g...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Phix
Phix
atom a = prompt_number("first number:",{}), b = prompt_number("second number:",{}) printf(1,"%g is ",a) if a < b then puts(1,"less than") elsif a = b then puts(1,"equal to") elsif a > b then puts(1,"greater than") end if printf(1," %g",b)
Give a code snippet in #Phix Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Excel
Excel
nextHarshad =LAMBDA(n, UNTIL( LAMBDA(x, 0 = MOD(x, decDigitSum(x)) ) )( LAMBDA(x, 1 + x) )(1 + n) )   harshads =LAMBDA(n, UNTIL( LAMBDA(xs, n = ROWS(xs)) )( LAMBDA(xs, APPENDROWS(xs)( nextHarshad( IND...
Give a code snippet in #Excel The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Racket
Racket
  #lang at-exp racket (require scribble/text/wrap) (define text @(λ xs (regexp-replace* #rx" *\n *" (string-append* xs) " ")){ In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much,...
Give a code snippet in #Racket Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#EasyLang
EasyLang
a$ = "gHHH5YY++///\\" a$[] = strchars a$ cp$ = a$[0] for c$ in a$[] if c$ <> cp$ s$ &= ", " cp$ = c$ . s$ &= c$ . print s$
Give a code snippet in #EasyLang Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program zumkeller4.s */ /* new version 10/2020 */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constan...
Give a code snippet in #ARM_Assembly Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how th...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#REXX
REXX
/*REXX program (a game): reverse a jumbled set of decimal digits 'til they're in order.*/ signal on halt /*allows the CBLF to HALT the program.*/ ___= copies('─', 9); pad=left('', 9) /*a fence used for computer's messages.*/ say ___ "This game will show you nine random u...
Give a code snippet in #REXX Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sco...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#D
D
import std.stdio;   struct Subtractive { enum MOD = 1_000_000_000; private int[55] state; private int si, sj;   this(in int p1) pure nothrow { subrandSeed(p1); }   void subrandSeed(int p1) pure nothrow { int p2 = 1;   state[0] = p1 % MOD; for (int i = 1, j = 21; i...
Give a code snippet in #D A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}}...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#ooRexx
ooRexx
-- get an array of directory objects array = fillArrayWith(3, .directory) say "each object will have a different identityHash" say loop d over array say d d~identityHash end   ::routine fillArrayWith use arg size, class   array = .array~new(size) loop i = 1 to size -- Note, this assumes this object clas...
Give a code snippet in #ooRexx Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are conside...
christopher/rosetta-code
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the...
#Arturo
Arturo
wordset: map read.lines relative "unixdict.txt" => strip   validAnswer?: function [answer][ if not? contains? wordset answer [ prints "\tNot a valid dictionary word." return false ] if contains? pastWords answer [ prints "\tWord already used." return false ] if 1 <> l...
Give a code snippet in #Arturo Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#Factor
Factor
USING: layouts memory prettyprint ;   ! Show size in bytes { 1 2 3 } size .  ! 48 1231298302914891021239102 size .  ! 48   ! Doesn't work on fixnums and other immediate objects 10 size .  ! 0   ! Show number of bits in a fixnum fixnum-bits .  ! 60
Give a code snippet in #Factor Demonstrate how to get the size of a variable. See also: Host introspection
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Scala
Scala
import java.util.Calendar import java.text.SimpleDateFormat   object Fridays {   def lastFridayOfMonth(year:Int, month:Int)={ val cal=Calendar.getInstance cal.set(Calendar.YEAR, year) cal.set(Calendar.MONTH, month) cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY) cal.set(Calendar.DAY_OF_WEEK_IN_MONT...
Give a code snippet in #Scala Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Emacs_Lisp
Emacs Lisp
(make-frame)
Give a code snippet in #Emacs_Lisp Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Nim
Nim
import strutils   proc removeComments(line: string; sep: char): string = line.split(sep)[0].strip(leading = false)   const Str1 = "apples, pears # and bananas" Str2 = "apples, pears ; and bananas"   echo "Original: “$#”" % Str1 echo "Stripped: “$#”" % Str1.removeComments('#') echo "Original: “$#”" % Str2 echo "St...
Give a code snippet in #Nim Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whi...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#REBOL
REBOL
  ; This program works with REBOL version R2 and R3, to make it work with Red ; change the word func to function insertion-sort: func [ a [block!] /local i [integer!] j [integer!] n [integer!] value [integer! string! date!] ][ i: 2 n: length? a   while [i <= n][ value: a/:i j: i while [ all [ 1 < ...
Give a code snippet in #REBOL 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/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#JavaScript
JavaScript
example = new Object; example.foo = function(x) { return 42 + x; };   name = "foo"; example[name](5) # => 47
Give a code snippet in #JavaScript Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
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...
#Haskell
Haskell
mean :: (Fractional a) => [a] -> a mean [] = 0 mean xs = sum xs / Data.List.genericLength xs
Give a code snippet in #Haskell 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 es...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. 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 b...
#Octave
Octave
for i = 1:2:10 disp(i) endfor
Give a code snippet in #Octave Task Demonstrate a   for-loop   where the step-value is greater than one. 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/In...
christopher/rosetta-code
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#TXR
TXR
VAR # define or update VAR as a true-valued boolean VAR= # ensure "; VAR" in the config file. VAR=VAL # ensure "VAR VAL" in the config file
Give a code snippet in #TXR We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non co...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#REXX
REXX
╔═════════════════════════════════════════════════════════════════════════╗ ║ ☼☼☼☼☼☼☼☼☼☼☼ Functions of the List Manager ☼☼☼☼☼☼☼☼☼☼☼ ║ ║ @init ─── initializes the List. ║ ║ ...
Give a code snippet in #REXX Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type ...
christopher/rosetta-code
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#Factor
Factor
\ fetch and store usage examples VARIABLE MYINT1 VARIABLE MYINT2 2VARIABLE DOUBLE1 2VARIABLE DOUBLE2   MYINT1 @ MYINT2 ! MYDOUBLE 2@ MYDOUBLE 2!   \ record example using this convention   1000000 RECORDS PERSONEL   1 PERSONEL RECORD@ \ read Record 1 and put pointer on data stack   HR_RECORD 992 PERSONEL RECORD! \ sto...
Give a code snippet in #Factor Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#REXX
REXX
/* REXX *************************************************************** * Test digroot **********************************************************************/ /* n r p */ say right(7 ,12) d...
Give a code snippet in #REXX The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , r...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#Batch_File
Batch File
:: DNS Query Task from Rosetta Code Wiki :: Batch File Implementation   @echo off   set "domain=www.kame.net" echo DOMAIN: "%domain%" echo( call :DNS_Lookup "%domain%" pause exit /b ::Main Procedure ::Uses NSLOOKUP Command. Also uses a dirty "parsing" to detect IP addresses. :DNS_Lookup [domain] ::Define Variables an...
Give a code snippet in #Batch_File DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
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 ...
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Collections.NList;   module Quicksort { Qsort[T] (x : list[T]) : list[T] where T : IComparable { |[] => [] |x::xs => Qsort($[y|y in xs, (y.CompareTo(x) < 0)]) + [x] + Qsort($[y|y in xs, (y.CompareTo(x) > 0)]) }   Main() : void ...
Give a code snippet in #Nemerle Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Oberon-2
Oberon-2
  MODULE DayOfWeek; IMPORT NPCT:Dates, Out; VAR year: INTEGER; date: Dates.Date; BEGIN FOR year := 2008 TO 2121 DO date := Dates.NewDate(25,12,year); IF date.DayOfWeek() = Dates.sunday THEN Out.Int(date.year,4);Out.Ln END END END DayOfWeek.  
Give a code snippet in #Oberon-2 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 betwe...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#C
C
#include <stdlib.h> #include <math.h>   char* eratosthenes(int n, int *c) { char* sieve; int i, j, m;   if(n < 2) return NULL;   *c = n-1; /* primes count */ m = (int) sqrt((double) n);   /* calloc initializes to zero */ sieve = calloc(n+1,sizeof(char)); sieve[0] = 1; sieve[1] = 1; for(i = 2; i <= m; i+...
Give a code snippet in #C This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algor...
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.
#Visual_Basic_.NET
Visual Basic .NET
Module Program Sub Main() Dim arg As Integer() = {1, 2, 3, 4, 5} Dim sum = arg.Sum() Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor) End Sub End Module
Give a code snippet in #Visual_Basic_.NET Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin # whatever logic is required in your main procedure if some_condition then exit(PROGRAM); end if; end func;
Give a code snippet in #Seed7 Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclotomic_polynomial
Cyclotomic polynomial
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and print the order of the first 10...
#Raku
Raku
use Math::Polynomial::Cyclotomic:from<Perl5> <cyclo_poly_iterate cyclo_poly>;   say 'First 30 cyclotomic polynomials:'; my $iterator = cyclo_poly_iterate(1); say "Φ($_) = " ~ super $iterator().Str for 1..30;   say "\nSmallest cyclotomic polynomial with |n| as a coefficient:"; say "Φ(1) has a coefficient magnitude: 1"; ...
Give a code snippet in #Raku The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and p...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Stata
Stata
. mata magic(5) 1 2 3 4 5 +--------------------------+ 1 | 17 24 1 8 15 | 2 | 23 5 7 14 16 | 3 | 4 6 13 20 22 | 4 | 10 12 19 21 3 | 5 | 11 18 25 2 9 | +--------------------------+
Give a code snippet in #Stata A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#D
D
import std.stdio, std.range;   void main () { foreach (a, b, c; zip("abc", "ABC", [1, 2, 3])) writeln(a, b, c); }
Give a code snippet in #D Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example,...
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
#Object_Pascal
Object Pascal
type bool = false | true
Give a code snippet in #Object_Pascal 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/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algor...
#Phix
Phix
with javascript_semantics include mpfr.e function ts(string ns, ps) mpz n = mpz_init(ns), p = mpz_init(ps), t = mpz_init(), r = mpz_init(), pm1 = mpz_init(), pm2 = mpz_init() mpz_sub_ui(pm1,p,1) -- pm1 = p-1 mpz_fdiv_q_2exp(pm2,pm1,1) -- pm...
Give a code snippet in #Phix This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number th...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Ring
Ring
  see "The first 100 tau numbers are:" + nl + nl   n = 1 num = 0 limit = 100 while num < limit n = n + 1 tau = 0 for m = 1 to n if n%m = 0 tau = tau + 1 ok next if n%tau = 0 num = num + 1 if num%10 = 1 see nl ok ...
Give a code snippet in #Ring A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function ...
christopher/rosetta-code
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Logtalk
Logtalk
  :- object(set(_Type), extends(set)).   % the info/1 directive is the main directive for documenting an entity % its value is a list of Key-Value pairs; the set of keys is user-extendable :- info([ version is 1.2, author is 'A. Coder', date is 2013/10/13, comment is 'Set predicates with elements constraine...
Give a code snippet in #Logtalk See also Related task: Comments Related task: Here_document
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#Oberon-2
Oberon-2
  MODULE Columns; IMPORT NPCT:Tools, Object, Out;   TYPE Parts = ARRAY 32 OF STRING; Formatter = PROCEDURE (s: STRING; len: LONGINT): STRING; VAR lines: ARRAY 6 OF STRING; words: ARRAY 6 OF Parts; columnWidth: ARRAY 128 OF INTEGER; lineIdx: INTEGER;   (* * Size: returns de number of words in a l...
Give a code snippet in #Oberon-2 Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.23
C#
static void Main (string[] args) { do { Console.WriteLine ("Number:"); Int64 p = 0; do { try { p = Convert.ToInt64 (Console.ReadLine ()); break; } catch (Exception) { }   } while (true);   Console.WriteLine ("For 1 throu...
Give a code snippet in #C.23 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) a:=GSL.Matrix(6,6).set( 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.1...
Give a code snippet in #zkl Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#J
J
2 #.inv 12 1 1 0 0 3 #.inv 100 1 0 2 0 1 16 #.inv 180097588 10 11 12 1 2 3 4
Give a code snippet in #J Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routine...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#Ruby
Ruby
def make_change(amount, coins) @cache = Array.new(amount+1){|i| Array.new(coins.size, i.zero? ? 1 : nil)} @coins = coins do_count(amount, @coins.length - 1) end   def do_count(n, m) if n < 0 || m < 0 0 elsif @cache[n][m] @cache[n][m] else @cache[n][m] = do_count(n-@coins[m], m) + do_count(n, m-1...
Give a code snippet in #Ruby There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#Kotlin
Kotlin
// version 1.1.2   fun forwardDifference(ia: IntArray, order: Int): IntArray { if (order < 0) throw IllegalArgumentException("Order must be non-negative") if (order == 0) return ia val size = ia.size if (size == 0) return ia // same empty array if (order >= size) return intArrayOf() // new empty a...
Give a code snippet in #Kotlin Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List ...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#NetRexx
NetRexx
/*NetRexx program to display the 1st 8 (or specified arg) happy numbers*/ limit = arg[0] /*get argument for LIMIT. */ say limit if limit = null, limit ='' then limit=8 /*if not specified, set LIMIT to 8*/ haps = 0 /*count of happy numbers so far. */   loop ...
Give a code snippet in #NetRexx From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessl...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#Java
Java
  import java.math.BigInteger;   class MersenneFactorCheck {   private final static BigInteger TWO = BigInteger.valueOf(2);   public static boolean isPrime(long n) { if (n == 2) return true; if ((n < 2) || ((n & 1) == 0)) return false; long maxFactor = (long)Math.sqrt((double)n); for (...
Give a code snippet in #Java A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before st...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Frink
Frink
f = newJava["java.io.File", "FileModificationTime.frink"] f.setLastModified[(#2022-01-01 5:00 AM# - #1970 UTC#) / ms] println[f.lastModified[] ms + #1970 UTC#]
Give a code snippet in #Frink Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Quackery
Quackery
[ 1 & ] is odd ( n --> b )   [ odd not ] is even ( n --> b )
Give a code snippet in #Quackery Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. D...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#OCaml
OCaml
let pi_twice = 2.0 *. 3.14159_26535_89793_23846_2643 let day = float (24 * 60 * 60)   let rad_of_time t = t *. pi_twice /. day   let time_of_rad r = r *. day /. pi_twice   let mean_angle angles = let sum_sin = List.fold_left (fun sum a -> sum +. sin a) 0.0 angles and sum_cos = List.fold_left (fun sum a -> sum +...
Give a code snippet in #OCaml Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas ...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#OCaml
OCaml
$ ocaml -I +sha sha1.cma Objective Caml version 3.12.1   # Sha1.to_hex (Sha1.string "Rosetta Code") ;; - : string = "48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"
Give a code snippet in #OCaml SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to ide...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program binSearch64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#0815
0815
  |~>|~#:end:> <:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$ <:62:x<:3d:=<:20:$==$~$=${~>%<:a:~$$ <:61:x<:2b:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~+%<:a:~$ <:61:x<:2d:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~-%<:a:~$ <:61:x<:2a:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~*%<:a:~$ <:61:x<:2f:=<:20:$==...
Give a code snippet in #0815 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Pointers_and_references
Pointers and references
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 |...
#Python
Python
# Bind a literal string object to a name: a = "foo" # Bind an empty list to another name: b = [] # Classes are "factories" for creating new objects: invoke class name as a function: class Foo(object): pass c = Foo() # Again, but with optional initialization: class Bar(object): def __init__(self, init...
Give a code snippet in #Python Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code