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/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
| #Slate | Slate | {1. 2. 3} reduce: [|:x :y| y squared + x].
{} reduce: [|:x :y| y squared + x] ifEmpty: [0]. | Give a code snippet in #Slate
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/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to ... | #ALGOL_68 | ALGOL 68 | main:
(
# Just get a random price between 0 and 1 #
# srand(time(NIL)); #
REAL price := random;
REAL tops := 0.06;
REAL std val := 0.10;
# Conditionals are a little odd here "(price-0.001 < tops AND
price+0.001 > tops)" is to check if they are equal. Stupid
C floats, right? :) #
... | Give a code snippet in #ALGOL_68
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 a... | 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... | #Forth | Forth | include random.hsf
\ parser routines
: totag
[char] < PARSE pad place \ parse input up to '<' char
-1 >in +! \ move the interpreter pointer back 1 char
pad count type ;
: '"' [char] " emit ;
: '"..' '"' space ; ... | Give a code snippet in #Forth
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 wit... | 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... | #Clojure | Clojure |
;; Incorporated some improvements from the alternative implementation below
(defn ro2ar [r]
(->> (reverse (.toUpperCase r))
(map {\M 1000 \D 500 \C 100 \L 50 \X 10 \V 5 \I 1})
(partition-by identity)
(map (partial apply +))
(reduce #(if (< %1 %2) (+ %1 %2) (- %1 %2)))))
;; alternative
... | Give a code snippet in #Clojure
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/Horizontal_sundial_calculations | Horizontal sundial calculations | Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const float: radianToDegrees is 57.295779513082320876798154814114;
const float: degreesToRadian is 0.017453292519943295769236907684883;
const proc: main is func
local
var float: lat is 0.0;
var float: slat is 0.0;
var float: lng is... | Give a code snippet in #Seed7
Task
Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location.
For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Rust | Rust | use std::process::Command;
use std::io::{Write, self};
fn main() {
let output = Command::new("/bin/cat")
.arg("/etc/fstab")
.output()
.expect("failed to execute process");
io::stdout().write(&output.stdout);
} | Give a code snippet in #Rust
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Image_noise | Image noise | Generate a random black and white 320x240 image continuously,
showing FPS (frames per second).
A sample image
| #FreeBASIC | FreeBASIC | ' version 13-07-2018
' compile with: fbc -s console
' or: fbc -s gui
' hit any to key to stop program
Randomize Timer
Screen 13
If ScreenPtr = 0 Then
Print "Error setting video mode!"
End
End If
Palette 0, 0 ' black
Palette 1, RGB(255, 255, 255) ' white
Dim As UInteger c, x,... | Give a code snippet in #FreeBASIC
Generate a random black and white 320x240 image continuously,
showing FPS (frames per second).
A sample image
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #8086_Assembly | 8086 Assembly | MOV AX,0345h
MOV BX,0444h
AND AX,BX | Give a code snippet in #8086_Assembly
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 Ope... | christopher/rosetta-code | |
http://rosettacode.org/wiki/A%2BB | A+B | A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separated by space(s):
(
−
1000
≤... | #ANTLR | ANTLR |
static Integer sumOfTwoNums(Integer A, Integer B) {
return A + B;
}
System.debug('A = 50 and B = 25: ' + sumOfTwoNums(50, 25));
System.debug('A = -50 and B = 25: ' +sumOfTwoNums(-50, 25));
System.debug('A = -50 and B = -25: ' +sumOfTwoNums(-50, -25));
System.debug('A = 50 and B = -25: ' +sumOfTwoNums(50, -25)... | Give a code snippet in #ANTLR
A+B ─── a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.
Task
Given two integers, A and B.
Their sum needs to be calculated.
Input data
Two integers are written in the input stream, separate... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
... | #Erlang | Erlang | -module(sierpinski).
-export([triangle/1]).
triangle(N) ->
F = fun(X) -> io:format("~s~n",[X]) end,
lists:foreach(F, triangle(N, ["*"], " ")).
triangle(0, Down, _) -> Down;
triangle(N, Down, Sp) ->
NewDown = [Sp++X++Sp || X<-Down]++[X++" "++X || X <- Down],
triangle(N-1, NewDown, Sp++Sp). | Give a code snippet in #Erlang
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Quackery | Quackery |
[ 2 ] is maybe ( --> t )
[ table 2 0 1 ] is jiggle ( t --> n )
[ jiggle 1+ ]this[ swap peek do ]done[ ] is 1-trit ( t --> t )
[ swap jiggle 1+ ]this[
swap peek
swap jiggle peek do ]done[ ] is 2-trits ... | Give a code snippet in #Quackery
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (a... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bit... | #Sidef | Sidef | func entropy(s) {
var counts = Hash.new;
s.each { |c| counts{c} := 0 ++ };
var len = s.len;
[0, counts.values.map {|count|
var freq = count/len; freq * freq.log2 }...
]«-»;
}
say entropy("1223334444"); | Give a code snippet in #Sidef
Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Matrix_chain_multiplication | Matrix chain multiplication | Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on whe... | #Haskell | Haskell | import Data.List (elemIndex)
import Data.Char (chr, ord)
import Data.Maybe (fromJust)
mats :: [[Int]]
mats =
[ [5, 6, 3, 1]
, [1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2]
, [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10]
]
cost :: [Int] -> Int -> Int -> (Int, Int)
cost a i j
| i < j =
let m =... | Give a code snippet in #Haskell
Problem
Using the most straightfoward algorithm (which we assume here), computing the product of two matrices of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 FMA operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of mat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armie... | #SQL_PL | SQL PL |
-- A column of a matrix.
CREATE TYPE INTEGER_ARRAY AS INTEGER ARRAY[]@
-- The whole matrix of any size.
CREATE TYPE INTEGER_MATRIX AS INTEGER_ARRAY ARRAY[]@
/**
* Retrieves the value from a matrix at a specific position.
*
* IN X: Row number.
* IN Y: Column number.
* IN M: Matrix.
* RETURN the integer value ... | Give a code snippet in #SQL_PL
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Plot_coordinate_pairs | Plot coordinate pairs | Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.... | #PostScript | PostScript |
/x [0 1 2 3 4 5 6 7 8 9] def
/y [2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0] def
/i 1 def
newpath
x 0 get y 0 get moveto
x length 1 sub{
x i get y i get lineto
/i i 1 add def
}repeat
stroke
| Give a code snippet in #PostScript
Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #XLISP | XLISP | (if (eq s "Rosetta Code")
"The well-known programming chrestomathy site"
"Some other website, maybe, I dunno" ) | Give a code snippet in #XLISP
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\di... | #REXX | REXX | /*REXX program lists the prime factors of a specified integer (or a range of integers).*/
@.=left('', 8); @.0="{unity} "; @.1='[prime] ' /*some tags and handy-dandy literals.*/
parse arg LO HI @ . /*get optional arguments from the C.L. */
if LO=='' | LO=="," then do; LO=1; HI=40; end... | Give a code snippet in #REXX
Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutations_by_swapping | Permutations by swapping | Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Show the permutations and signs ... | #Lua | Lua | _JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
setmetatable(n,{__index=_JT})
for i=1,dim do
n.values[i]=i
n.positions[i]=i
n.directions[i]=-1
end
return n
end
function _JT:largestMobile()
for i=#self.values,1,-1 do
local loc=self.positions[i]+self.direct... | Give a code snippet in #Lua
Task
Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
Sho... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
... | #jq | jq | # Angles are in degrees; the result is rounded to 4 decimal places:
def subtract($b1; $b2):
10000 as $scale
| (($scale * ($b2 - $b1)) % (360 * $scale)) | round / $scale
| if . < -180 then . + 360
elif . >= 180 then . - 360
else .
end;
def pairs:
[ 20, 45],
[-45, 45],
[-85, 90],
... | Give a code snippet in #jq
Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -18... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #Quackery | Quackery | [ factors size dup 3 4 clamp = ] is semiprime ( n --> b )
say "Semiprimes less than 100:" cr
100 times [ i^ semiprime if [ i^ echo sp ] ] | Give a code snippet in #Quackery
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Dimensions | Terminal control/Dimensions | Determine the height and width of the terminal, and store this information into variables for subsequent use.
| #Batch_File | Batch File | @echo off
for /f "tokens=1,2 delims= " %%A in ('mode con') do (
if "%%A"=="Lines:" set line=%%B
if "%%A"=="Columns:" set cols=%%B
)
echo Lines: %line%
echo Columns: %cols%
exit /b 0 | Give a code snippet in #Batch_File
Determine the height and width of the terminal, and store this information into variables for subsequent use.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #GlovePIE | GlovePIE | debug = "SPAM" | Give a code snippet in #GlovePIE
Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
L... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Pascal | Pascal | isOdd := odd(someIntegerNumber); | Give a code snippet in #Pascal
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.
Div... | christopher/rosetta-code | |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write ... | #K | K | `output.txt 0:0:`input.txt | Give a code snippet in #K
File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/I_before_E_except_after_C | I before E except after C | The phrase "I before E, except after C" is a
widely known mnemonic which is supposed to help when spelling English words.
Task
Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible individually:
"I before E when not pre... | #11l | 11l | V PLAUSIBILITY_RATIO = 2
F plausibility_check(comment, x, y)
print("\n Checking plausibility of: #.".format(comment))
I x > :PLAUSIBILITY_RATIO * y
print(‘ PLAUSIBLE. As we have counts of #. vs #., a ratio of #2.1 times’.format(x, y, Float(x) / y))
E
I x > y
print(‘ IMPLAUSIBLE. A... | Give a code snippet in #11l
The phrase "I before E, except after C" is a
widely known mnemonic which is supposed to help when spelling English words.
Task
Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible individually:... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Kotlin | Kotlin | import java.io.File
fun main(args: Array<String>) {
val file = File("unixdict.txt")
val result = mutableListOf<String>()
file.forEachLine {
if (it.toCharArray().sorted().joinToString(separator = "") == it) {
result += it
}
}
result.sortByDescending { it.length }
... | Give a code snippet in #Kotlin
An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file local... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Get_system_command_output | Get system command output | Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| #Amazing_Hopper | Amazing Hopper |
/* JAMBO language - a flavour of Hopper */
#include <jambo.h>
Main
sys = `cat jm/sys1.jambo`
Set( sys ) Prnl
End
| Give a code snippet in #Amazing_Hopper
Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).
Related task
Execute a system command
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_triangle | Sierpinski triangle | Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
* * * *
... | #Tcl | Tcl | package require Tcl 8.5
proc map {lambda list} {
foreach elem $list {
lappend result [apply $lambda $elem]
}
return $result
}
proc sierpinski_triangle n {
set down [list *]
set space " "
for {set i 1} {$i <= $n} {incr i} {
set down [concat \
[map [subst -nocommand... | Give a code snippet in #Tcl
Task
Produce an ASCII representation of a Sierpinski triangle of order N.
Example
The Sierpinski triangle of order 4 should look like this:
*
* *
* *
* * * *
* *
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #ArnoldC | ArnoldC | IT'S SHOWTIME
YOU HAVE BEEN TERMINATED | Give a code snippet in #ArnoldC
Task
Create the simplest possible program that is still considered "correct."
| 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 ... | #JavaScript | JavaScript | var args = process.argv.slice(2);
function time_to_seconds( hms ) {
var parts = hms.split(':');
var h = parseInt(parts[0]);
var m = parseInt(parts[1]);
var s = parseInt(parts[2]);
if ( h < 12 ) {
h += 24;
}
var seconds = parseInt(parts[0]) * 60 * 60 + parseInt(parts[1]) * 60 + par... | Give a code snippet in #JavaScript
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 i... | 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... | #Raku | Raku | use Image::PNG::Portable;
my ($w, $h) = 400, 400;
my $out = Image::PNG::Portable.new: :width($w), :height($h);
plasma($out);
$out.write: 'Plasma-perl6.png';
sub plasma ($png) {
(^$w).race.map: -> $x {
for ^$h -> $y {
my $hue = 4 + sin($x / 19) + sin($y / 9) + sin(($x + $y) / 25) + sin(sq... | Give a code snippet in #Raku
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
C... | 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... | #8080_Assembly | 8080 Assembly | bdos equ 5
putchar equ 2
rawio equ 6
puts equ 9
cstat equ 11
reads equ 10
org 100h
mvi c,puts
lxi d,signon ; Print name
call bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Initialize the RNG with keyboard input
mvi c,puts
lxi d,entropy ; Ask for randomness
call bdos
mvi b,9 ; 9 times,
randloo... | Give a code snippet in #8080_Assembly
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... | 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... | #Brainf.2A.2A.2A | Brainf*** | width = 3
height = 3
rounds = 3
universe = [[0 1 0]
[0 1 0]
[0 1 0]]
next = height.of({width.of(0)})
cell = { x, y |
true? x < width && { x >= 0 && { y >= 0 && { y < height }}}
{
universe[y][x]
}
{ 0 }
}
neighbors = { x, y |
cell(x - 1, y - 1) +
cell(x, y - 1) +
cell(x ... | Give a code snippet in #Brainf.2A.2A.2A
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 wh... | christopher/rosetta-code | |
http://rosettacode.org/wiki/M%C3%B6bius_function | Möbius function | The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha... | #D | D | import std.math;
import std.stdio;
immutable MU_MAX = 1_000_000;
int mobiusFunction(int n) {
static initialized = false;
static int[MU_MAX + 1] MU;
if (initialized) {
return MU[n];
}
// populate array
MU[] = 1;
int root = cast(int) sqrt(cast(real) MU_MAX);
for (int i = ... | Give a code snippet in #D
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics.
There are several ways to implement a Möbius function.
A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_prepend | String prepend |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Delphi | Delphi |
program String_preappend;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TStringHelper = record helper for string
procedure Preappend(str: string);
end;
{ TStringHelper }
procedure TStringHelper.Preappend(str: string);
begin
Self := str + self;
end;
begin
var h: string;
// with + operator... | Give a code snippet in #Delphi
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 | |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Racket | Racket | #lang racket
(define (rep-string str)
(define len (string-length str))
(for/or ([n (in-range 1 len)])
(and (let loop ([from n])
(or (>= from len)
(let ([m (min (- len from) n)])
(and (equal? (substring str from (+ from m))
(substring str... | Give a code snippet in #Racket
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at lea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Input_loop | Input loop | Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| #Haskell | Haskell | import System.IO
readLines :: Handle -> IO [String]
readLines h = do
s <- hGetContents h
return $ lines s
readWords :: Handle -> IO [String]
readWords h = do
s <- hGetContents h
return $ words s | Give a code snippet in #Haskell
Input loop is part of Short Circuit's Console Program Basics selection.
Task
Read from a text stream either word-by-word or line-by-line until the stream runs out of data.
The stream will have an unknown amount of data on it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #BBC_BASIC | BBC BASIC | BOOL = 1
NAME = 2
ARRAY = 3
optfile$ = "options.cfg"
fullname$ = FNoption(optfile$, "FULLNAME", NAME)
favouritefruit$ = FNoption(optfile$, "FAVOURITEFRUIT", NAME)
needspeeling% = FNoption(optfile$, "NEEDSPEELING", BOOL)
seedsremoved% = FNoption(optfile$, "SEEDSREMOVED... | Give a code snippet in #BBC_BASIC
The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #OCaml | OCaml | type trit = True | False | Maybe
let t_not = function
| True -> False
| False -> True
| Maybe -> Maybe
let t_and a b = match (a,b) with
| (True,True) -> True
| (False,_) | (_,False) -> False
| _ -> Maybe
let t_or a b = t_not (t_and (t_not a) (t_not b))
let t_eq a b = match (a,b) with
| (True,... | Give a code snippet in #OCaml
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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
| #Casio_BASIC | Casio BASIC | ViewWindow 1,127,1,1,63,1
AxesOff
CoordOff
GridOff
LabelOff | Give a code snippet in #Casio_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/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)
... | #Standard_ML | Standard ML | local
fun check (c, p as (m, n)) =
if Char.isDigit c then
(not m, (if m then 3 * (ord c - 48) else ord c - 48) + n)
else
p
in
fun checkISBN s =
Int.rem (#2 (CharVector.foldl check (false, 0) s), 10) = 0
end
val test = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]... | Give a code snippet in #Standard_ML
Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Haversine_formula | Haversine formula |
This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equation important in navigation, g... | #Rust | Rust |
use std::f64;
static R: f64 = 6372.8;
struct Point {
lat: f64,
lon: f64,
}
fn haversine(mut origin: Point, mut destination: Point) -> f64 {
origin.lon -= destination.lon;
origin.lon = origin.lon.to_radians();
origin.lat = origin.lat.to_radians();
destination.lat = destination.lat.to_radi... | Give a code snippet in #Rust
This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Set_of_real_numbers | Set of real numbers | All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x and x ≤ b }
(a, b): {x | ... | #D | D | struct Set(T) {
const pure nothrow bool delegate(in T) contains;
bool opIn_r(in T x) const pure nothrow {
return contains(x);
}
Set opBinary(string op)(in Set set)
const pure nothrow if (op == "+" || op == "-") {
static if (op == "+")
return Set(x => contains(x) || se... | Give a code snippet in #D
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary:
[a, b]: {x | a ≤ x... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Walk_a_directory/Recursively | Walk a directory/Recursively | Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk a directory/Non-recursively ... | #Pop11 | Pop11 | lvars repp, fil;
;;; create path repeater
sys_file_match('.../*.p', '', false, 0) -> repp;
;;; iterate over paths
while (repp() ->> fil) /= termin do
;;; print the path
printf(fil, '%s\n');
endwhile; | Give a code snippet in #Pop11
Task
Walk a given directory tree and print files matching a given pattern.
Note: This task is for recursive methods. These tasks should read an entire directory tree, not a single directory.
Note: Please be careful when running any code examples found here.
Related task
Walk... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knuth%27s_power_tree | Knuth's power tree | (Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact values of (at least) the integer po... | #Groovy | Groovy | class PowerTree {
private static Map<Integer, Integer> p = new HashMap<>()
private static List<List<Integer>> lvl = new ArrayList<>()
static {
p[1] = 0
List<Integer> temp = new ArrayList<Integer>()
temp.add 1
lvl.add temp
}
private static List<Integer> path(int ... | Give a code snippet in #Groovy
(Knuth's power tree is used for computing xn efficiently.)
Task
Compute and show the list of Knuth's power tree integers necessary for the computation of:
xn for any real x and any non-negative integer n.
Then, using those integers, calculate and show the exact val... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #jq | jq | M | setpath([i,j]; e)
| Give a code snippet in #jq
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Linear_congruential_generator | Linear congruential generator | The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r_{0}}
is a seed.
r
1
... | #Swift | Swift | import Cocoa
class LinearCongruntialGenerator {
var state = 0 //seed of 0 by default
let a, c, m, shift: Int
//we will use microsoft random by default
init() {
self.a = 214013
self.c = 2531011
self.m = Int(pow(2.0, 31.0)) //2^31 or 2147483648
self.shift = 16
}
... | Give a code snippet in #Swift
The linear congruential generator is a very simple example of a random number generator.
All linear congruential generators use this formula:
r
n
+
1
=
a
×
r
n
+
c
(
mod
m
)
{\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}}
Where:
r
0
{\displaystyle r... | christopher/rosetta-code | |
http://rosettacode.org/wiki/21_game | 21 game | 21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the running total
to reach exactly ... | #C | C | /**
* Game 21 - an example in C language for Rosseta Code.
*
* A simple game program whose rules are described below
* - see DESCRIPTION string.
*
* This program should be compatible with C89 and up.
*/
/*
* Turn off MS Visual Studio panic warnings which disable to use old gold
* library functions like pri... | Give a code snippet in #C
21 game
You are encouraged to solve this task according to the task description, using any language you may know.
21 is a two player game, the game is played by choosing
a number (1, 2, or 3) to be added to the running total.
The game is won by the player whose chosen number causes the runn... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Test_integerness | Test integerness | Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
Given a rational, real, or co... | #Lua | Lua | function isInt (x) return type(x) == "number" and x == math.floor(x) end
print("Value\tInteger?")
print("=====\t========")
local testCases = {2, 0, -1, 3.5, "String!", true}
for _, input in pairs(testCases) do print(input, isInt(input)) end | Give a code snippet in #Lua
Mathematically,
the integers Z are included in the rational numbers Q,
which are included in the real numbers R,
which can be generalized to the complex numbers C.
This means that each of those larger sets, and the data types used to represent them, include some integers.
Task[edit]
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #JavaScript | JavaScript |
<html>
<head>
<title>Simple Window Application</title>
</head>
<body>
<br>        
<script type="text/javascript">
var box = document.createElement('input')
box.style.position = 'absolute'; // position it
box.style.left = '10px';
box.style.top = '6... | Give a code snippet in #JavaScript
Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Uni... | #jq | jq | def permutations:
if length == 0 then []
else
range(0;length) as $i
| [.[$i]] + (del(.[$i])|permutations)
end ;
| Give a code snippet in #jq
Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterat... | #C | C | int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
| Give a code snippet in #C
Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a numbe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Variable-length_quantity | Variable-length quantity | Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert these two numbers 0x200000 (209... | #PL.2FI | PL/I |
test: procedure options(main);
declare s character (20) varying;
declare c character (1);
declare v fixed binary (31);
declare (i, k) fixed binary;
get edit (s) (L);
s = trim (s);
v = 0;
do i = 1 to length(s);
c = substr(s, i, 1);
k = index('0123456789abcdef', c);
if k > 0 ... | Give a code snippet in #PL.2FI
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable.
Task
With above operations,
convert... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Simple_database | Simple database | Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be a collection (CDs, coins, base... | #C.23 | C# |
using System;
using System.IO;
namespace Simple_database
{
class Program
{
public static void Main(string[] args)
{
//
// For appropriate use of this program
// use standard Windows Command Processor or cmd.exe
//
// Create cmd.bat file at the same folder with executive version
// of program... | Give a code snippet in #C.23
Task
Write a simple tool to track a small set of data.
The tool should have a command-line interface to enter at least two different values.
The entered data should be stored in a structured format and saved to disk.
It does not matter what kind of data is being tracked. It could be ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Tcl | Tcl | foreach expression {5**3**2 (5**3)**2 5**(3**2)} {
puts "${expression}:\t[expr $expression]"
} | Give a code snippet in #Tcl
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 th... | 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... | #Factor | Factor | 0 [ dup 6 mod 0 = not ] [ [ . ] [ 1 + ] bi ] do while drop | Give a code snippet in #Factor
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/... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Entropy | Entropy | Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), the Shannon entropy of X in bit... | #Nim | Nim | import tables, math
proc entropy(s: string): float =
var t = initCountTable[char]()
for c in s: t.inc(c)
for x in t.values: result -= x/s.len * log2(x/s.len)
echo entropy("1223334444") | Give a code snippet in #Nim
Task
Calculate the Shannon entropy H of a given input string.
Given the discrete random variable
X
{\displaystyle X}
that is a string of
N
{\displaystyle N}
"symbols" (total characters) consisting of
n
{\displaystyle n}
different characters (n=2 for binary), th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 7... | #Java | Java | import java.util.BitSet;
public class Main {
public static void main(String[] args){
final int MAX = 1000000;
//Sieve of Eratosthenes (using BitSet only for odd numbers)
BitSet primeList = new BitSet(MAX>>1);
primeList.set(0,primeList.size(),true);
int sqroot = (int) Math.sqrt(MAX);
primeList.... | Give a code snippet in #Java
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatabl... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Quoting_constructs | Quoting constructs | Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati... | #jq | jq | def data:
"A string", 1, {"a":0}, [1,2,[3]]
;
| Give a code snippet in #jq
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof.
Show examples of the quoting constructs in your language. Explain where they would likely be used, what their p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #zkl | zkl | fcn multiply(x,y){x*y} | Give a code snippet in #zkl
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract fr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Use_another_language_to_call_a_function | Use another language to call a function | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, size_t * Length);
int main (i... | #zkl | zkl | // query.c
// export zklRoot=/home/ZKL
// clang query.c -I $zklRoot/VM -L $zklRoot/Lib -lzkl -pthread -lncurses -o query
// LD_LIBRARY_PATH=$zklRoot/Lib ./query
#include <stdio.h>
#include <string.h>
#include "zklObject.h"
#include "zklImports.h"
#include "zklClass.h"
#include "zklFcn.h"
#include "zklString.h"
in... | Give a code snippet in #zkl
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
This task is inverse to the task Call foreign language function. Consider the following C program:
#include <stdio.h>
extern int Query (char * Data, si... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Erd%C3%B6s-Selfridge_categorization_of_primes | Erdös-Selfridge categorization of primes | A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.
The task is first to display the first 200 primes allocated to their category, then assign the firs... | #Sidef | Sidef | func Erdös_Selfridge_class(n, s=1) is cached {
var f = factor_exp(n+s)
f.last.head > 3 || return 1
f.map {|p| __FUNC__(p.head, s) }.max + 1
}
say "First two hundred primes; Erdös-Selfridge categorized:"
200.pn_primes.group_by(Erdös_Selfridge_class).sort_by{.to_i}.each_2d {|k,v|
say "#{k} => #{v}"
}
... | Give a code snippet in #Sidef
A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1.
The task is first to display the first 200 primes allocated to their... | 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
)
)
,
... | #Python | Python | def F(n): return 1 if n == 0 else n - M(F(n-1))
def M(n): return 0 if n == 0 else n - F(M(n-1))
print ([ F(n) for n in range(20) ])
print ([ M(n) for n in range(20) ]) | Give a code snippet in #Python
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/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) ... | #CoffeeScript | CoffeeScript |
sorenson = require('sieve').primes # Sorenson's extensible sieve from task: Extensible Prime Generator
# put in outer scope to avoid recomputing the cache
memoPhi = {}
primes = []
isqrt = (x) -> Math.floor Math.sqrt x
pi = (n) ->
phi = (x, a) ->
y = memoPhi[[x,a]]
return y unless y is undef... | Give a code snippet in #CoffeeScript
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have download... | #Aime | Aime | integer
ordered(data s)
{
integer a, c, p;
a = 1;
p = -1;
for (, c in s) {
if (c < p) {
a = 0;
break;
} else {
p = c;
}
}
a;
}
integer
main(void)
{
file f;
text s;
index x;
f.affix("unixdict.txt");
while ... | Give a code snippet in #Aime
An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell | Terminal control/Ringing the terminal bell |
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal. It is usua... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Print["\007"] | Give a code snippet in #Mathematica.2FWolfram_Language
Task
Make the terminal running the program ring its "bell".
On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was class... | 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... | #langur | langur | .x()
# call user-defined function | Give a code snippet in #langur
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 v... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Convert_decimal_number_to_rational | Convert decimal number to rational | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
The task is to write a program to transform a decimal number into a fraction in lowest terms.
It is not always possible to do this... | #J | J | x: 0.9054054 0.518518 0.75 NB. find "exact" rational representation
127424481939351r140737488355328 866492568306r1671094481399 3r4 | Give a code snippet in #J
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
The task is to write a program to transform a decimal number into a fraction in lowest terms.
It is not... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Achilles_numbers | Achilles numbers |
This page uses content from Wikipedia. The original article was at Achilles number. 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)
An Achilles number is a number that is powerful but imperfect. Na... | #XPL0 | XPL0 | func GCD(N, D); \Return the greatest common divisor of N and D
int N, D; \numerator and denominator
int R;
[if D > N then
[R:= D; D:= N; N:= R]; \swap D and N
while D > 0 do
[R:= rem(N/D);
N:= D;
D:= R;
];
return N;
]; \GCD
func Totient(N); \Return the totie... | Give a code snippet in #XPL0
This page uses content from Wikipedia. The original article was at Achilles number. 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)
An Achilles number is a number that... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Function_definition | Function definition | A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from showing how functions are ... | #Q | Q | multiply:{[a;b] a*b} | Give a code snippet in #Q
A function is a body of code that returns a value.
The value returned may depend on arguments provided to the function.
Task
Write a definition of a function called "multiply" that takes two arguments and returns their product.
(Argument types should be chosen so as not to distract from... | christopher/rosetta-code | |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and m... | #Tcl | Tcl | package require Tcl 8.5
proc 1ofN {n} {
for {set line 1} {$line <= $n} {incr line} {
if {rand() < 1.0/[incr fraction]} {
set result $line
}
}
return $result
}
for {set i 0} {$i < 1000000} {incr i} {
incr count([1ofN 10])
}
parray count; # Alphabetic order, but convenient | Give a code snippet in #Tcl
A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #LOLCODE | LOLCODE | HAI 1.3
I HAS A foo BTW, INISHULIZD TO NOOB
DIFFRINT foo AN FAIL, O RLY?
YA RLY, VISIBLE "FAIL != NOOB"
OIC
I HAS A bar ITZ 42
bar, O RLY?
YA RLY, VISIBLE "bar IZ DEFIND"
OIC
bar R NOOB BTW, UNDEF bar
bar, O RLY?
YA RLY, VISIBLE "SHUD NEVAR C DIS"
OIC
KTHXBYE | Give a code snippet in #LOLCODE
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Java | Java | import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new ... | Give a code snippet in #Java
A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a su... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Dc | Dc | [ # move(from, to)
n # print from
[ --> ]n # print " --> "
p # print to\n
sw # p doesn't pop, so get rid of the value
]sm
[ # init(n)
sw # tuck n away temporarily
9 # sentinel as bottom of stack
lw # bring n back
1 ... | Give a code snippet in #Dc
Task
Solve the Towers of Hanoi problem with recursion.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #Liberty_BASIC | Liberty BASIC |
'the method used here uses the base-conversion from RC Non-decimal radices/Convert
'to terminate hit <CTRL<BRK>
global alphanum$
alphanum$ ="01234567"
i =0
while 1
print toBase$( 8, i)
i =i +1
wend
end
function toBase$( base, number) ' Convert dec... | Give a code snippet in #Liberty_BASIC
Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is re... | 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
| #Nanoquery | Nanoquery | a = true
b = false
if a
println "a is true"
else if b
println "b is true"
end | Give a code snippet in #Nanoquery
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/Knuth%27s_algorithm_S | Knuth's algorithm S | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam... | #D | D | import std.stdio, std.random;
auto sofN_creator(in int n) {
size_t i;
int[] sample;
return (in int item) {
i++;
if (i <= n)
sample ~= item;
else if (uniform01 < (double(n) / i))
sample[uniform(0, n)] = item;
return sample;
};
}
void main() {
... | Give a code snippet in #D
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fusc_sequence | Fusc sequence |
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition starts with unity, not zero. Th... | #Ada | Ada | with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Show_Fusc is
generic
Precalculate : Natural;
package Fusc_Sequences is
function Fusc (N : in Natural) return Natural;
end Fusc_Sequences;
package body Fusc_Sequences is
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
... | Give a code snippet in #Ada
Definitions
The fusc integer sequence is defined as:
fusc(0) = 0
fusc(1) = 1
for n>1, the nth term is defined as:
if n is even; fusc(n) = fusc(n/2)
if n is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)
Note that MathWorld's definition star... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification | Ramer-Douglas-Peucker line simplification | Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Task
Using the Ramer–Douglas–P... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::MoreUtils qw(firstidx minmax);
my $epsilon = 1;
sub norm {
my(@list) = @_;
my $sum;
$sum += $_**2 for @list;
sqrt($sum)
}
sub perpendicular_distance {
our(@start,@end,@point);
local(*start,*end,*point) = (shift, shift, shift);
retu... | Give a code snippet in #Perl
Ramer-Douglas-Peucker line simplification
You are encouraged to solve this task according to the task description, using any language you may know.
The Ramer–Douglas–Peucker algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
Tas... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Semiprime | Semiprime | Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chosen as the length of the Arecib... | #Raku | Raku | sub is-semiprime (Int $n --> Bool) {
not $n.is-prime and
.is-prime given
$n div first $n %% *, flat grep &is-prime, 2 .. *;
}
use Test;
my @primes = flat grep &is-prime, 2 .. 100;
for ^5 {
nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1;
ok is-semiprime([*] my @f2 = @primes.roll(2))... | Give a code snippet in #Raku
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers.
Semiprimes are also known as:
semi-primes
biprimes
bi-primes
2-almost primes
or simply: P2
Example
1679 = 23 × 73
(This particular number was chos... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Associative_array/Creation | Associative array/Creation | Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element ins... | #Futhark | Futhark | let associative_array = {key1=1,key2=2} | Give a code snippet in #Futhark
Task
The goal is to create an associative array (also known as a dictionary, map, or hash).
Related tasks:
Associative arrays/Iteration
Hash from two arrays
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition... | christopher/rosetta-code | |
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a st... | #Objeck | Objeck | use System.IO.File;
use Data.CSV;
class CsvToHtml {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
table := CsvTable->New(FileReader->ReadFile(args[0]));
if(table->IsParsed()) {
buffer := "<html><body><table>";
Header(table->GetHeaders(), buffer);
for(i := 1;... | Give a code snippet in #Objeck
Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
C... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Befunge | Befunge | >>" :NABI">:#,_>:~:"`"`48**-:55+-#v_$0::6g0>>8g-!\7g18g-!*!v>v>>
<<_#v:#78#`8#+<^+!!*-*84\-9:g8:p8\<oo>1#$-#<0$>>>#v_"dilav" ^#<<
>>^ >*-:20p9`9*1+55+**20g+"a"%10g1+00g%:4-!|^g6::_v#-*88:+1_vv>>
<<^+`"Z"\+`\"0"\*`\"A"\`"9":::\-*86:g8p01:<<40p00_v#!--+99g5<v<<
>>" si rebmun tahT">:#,_ 55+".",,@ >0"dilavni... | Give a code snippet in #Befunge
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/Fractal_tree | Fractal tree | Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| #Processing | Processing | void setup() {
size(600, 600);
background(0);
stroke(255);
drawTree(300, 550, 9);
}
void drawTree(float x, float y, int depth) {
float forkAngle = radians(20);
float baseLen = 10.0;
if (depth > 0) {
pushMatrix();
translate(x, y - baseLen * depth);
line(0, baseLen * depth, 0, 0);
rotate... | Give a code snippet in #Processing
Generate and draw a fractal tree.
Draw the trunk
At the end of the trunk, split by some angle and draw two branches
Repeat at the end of each branch until a sufficient level of branching is reached
Related tasks
Pythagoras Tree
| 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,... | #6502_Assembly | 6502 Assembly | Array:
db 5,10,15,20,25,30,35,40,45,50 | Give a code snippet in #6502_Assembly
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/Fork | Fork | Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
| #C.23 | C# | using System;
using System.Threading;
namespace Fork {
class Program {
static void Fork() {
Console.WriteLine("Spawned Thread");
}
static void Main(string[] args) {
Thread t = new Thread(new ThreadStart(Fork));
t.Start();
Console.WriteLin... | Give a code snippet in #C.23
Task
Spawn a new process which can run simultaneously with, and independently of, the original parent process.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm | Xiaolin Wu's line algorithm | Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| #Java | Java | import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;
public class XiaolinWu extends JPanel {
public XiaolinWu() {
Dimension dim = new Dimension(640, 640);
setPreferredSize(dim);
setBackground(Color.white);
}
void plot(Graphics2D g, double x, double y, double... | Give a code snippet in #Java
Task
Implement the Xiaolin Wu's line algorithm described in Wikipedia.
This algorithm draws anti-aliased lines.
Related task
See Bresenham's line algorithm for aliased lines.
| 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... | #Forth | Forth | 42 dup
2 base !
. \ 101010
hex
. \ 2A
decimal | Give a code snippet in #Forth
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/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #ERRE | ERRE | PROGRAM HAMMING
!$DOUBLE
DIM H[2000]
PROCEDURE HAMMING(L%->RES)
LOCAL I%,J%,K%,N%,M,X2,X3,X5
H[0]=1
X2=2 X3=3 X5=5
FOR N%=1 TO L%-1 DO
M=X2
IF M>X3 THEN M=X3 END IF
IF M>X5 THEN M=X5 END IF
H[N%]=M
IF M=X2 THEN I%+=1 X2=2*H[I%] END IF
IF ... | Give a code snippet in #ERRE
Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_carpet | Sierpinski carpet | Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ## # # ## # # #
### ###### ... | #Befunge | Befunge | 311>*#3\>#-:#1_$:00p00g-#@_010p0>:20p10g30v
>p>40p"#"30g40g*!#v_$48*30g3%1-v^ >$55+,1v>
0 ^p03/3g03/3g04$_v#!*!-1%3g04!<^_^#- g00 <
^3g01p02:0p01_@#-g>#0,#02#:0#+g#11#g+#0:#<^ | Give a code snippet in #Befunge
Task
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this:
###########################
# ## ## ## ## ## ## ## ## #
###########################
### ###### ###### ###
# # # ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | rle:
if not dup:
drop
return []
swap ]
local :source chars
pop-from source
1
for c in source:
if = c over:
++
else:
1 c &
&
return [
rld:
)
for pair in swap:
repeat &< pair:
&> pair
concat(
rle "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
!. dup
!. rld | Give a code snippet in #D.C3.A9j.C3.A0_Vu
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and pr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #EchoLisp | EchoLisp |
(define my-collection ' ( 🌱 ☀️ ☔️ ))
(set! my-collection (cons '🎥 my-collection))
(set! my-collection (cons '🐧 my-collection))
my-collection
→ (🐧 🎥 🌱 ☀️ ☔️)
;; save it
(local-put 'my-collection)
→ my-collection
| Give a code snippet in #EchoLisp
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
... | 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.
| #Lingo | Lingo | global gOpenGL -- RavOpenGL xtra instance
global GL -- OpenGL constants
on startMovie
-- Load the OpenGL script xtra
gOpenGL = xtra("RavOpenGL").new()
-- Load GL DLL
gOpenGL.RavLoadGL("", "")
-- Function omitted in demo code: loads OpenGL constants into namespace GL
loadGLConstants()
... | Give a code snippet in #Lingo
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/Sorting_algorithms/Comb_sort | Sorting algorithms/Comb sort | Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
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 algor... | #Swift | Swift | func combSort(inout list:[Int]) {
var swapped = true
var gap = list.count
while gap > 1 || swapped {
gap = gap * 10 / 13
if gap == 9 || gap == 10 {
gap = 11
} else if gap < 1 {
gap = 1
}
swapped = false
for var i = 0, j = gap; j... | Give a code snippet in #Swift
Sorting algorithms/Comb sort
You are encouraged to solve this task according to the task description, using any language you may know.
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 s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Array_concatenation | Array concatenation | Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| #Raku | Raku | my @array1 = 1, 2, 3;
my @array2 = 4, 5, 6;
# If you want to concatenate two array to form a third,
# either use the slip operator "|", to flatten each array.
my @array3 = |@array1, |@array2;
say @array3;
# or just flatten both arrays in one fell swoop
@array3 = flat @array1, @array2;
say @array3;
# On the ot... | Give a code snippet in #Raku
Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2, so be it.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #Prolog | Prolog | dutch_flag(N) :-
length(L, N),
repeat,
maplist(init,L),
\+is_dutch_flag(L) ,
writeln(L),
test_sorted(L),
sort_dutch_flag(L, TmpFlag),
append(TmpFlag, Flag),
writeln(Flag),
test_sorted(Flag).
sort_dutch_flag([], [[], [], []]).
sort_dutch_flag([blue | T], [R, W, [blue|B]]) :-
sort_dutch_flag(T, [R, W, ... | Give a code snippet in #Prolog
The Dutch national flag is composed of three coloured bands in the order:
red (top)
then white, and
lastly blue (at the bottom).
The problem posed by Edsger Dijkstra is:
Given a number of red, blue and white balls in random order, arrange them in the order of the c... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Intersecting_number_wheels | Intersecting number wheels | A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel"... | #Raku | Raku |
#| advance rotates a named wheel $n by consuming an item from an infinite sequence. It is called
#| from within a gather block and so can use take in order to construct an infinite, lazy sequence
#| of result values
sub advance($g, $n) {
given $g{$n}.pull-one {
when /\d/ { take $_ }
default { samewith $g, $_ }... | Give a code snippet in #Raku
A number wheel has:
A name which is an uppercase letter.
A set of ordered values which are either numbers or names.
A number is generated/yielded from a named wheel by:
1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Num... | #Icon_and_Unicon | Icon and Unicon | procedure main()
StraddlingCheckerBoard("setup","HOLMESRTABCDFGIJKNPQUVWXYZ./", 3,7)
text := "One night. it was on the twentieth of March, 1888. I was returning"
write("text = ",image(text))
write("encode = ",image(en := StraddlingCheckerBoard("encode",text)))
write("decode = ",image(StraddlingCheckerBoard("decode"... | Give a code snippet in #Icon_and_Unicon
Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutations/Derangements | Permutations/Derangements | A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n, sometimes written as !n.
The... | #GAP | GAP | # All of this is built-in
Derangements([1 .. 4]);
# [ [ 2, 1, 4, 3 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 3, 1, 4, 2 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ],
# [ 4, 1, 2, 3 ], [ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ] ]
Size(last);
# 9
NrDerangements([1 .. 4]);
# 9
# An imple... | Give a code snippet in #GAP
A derangement is a permutation of the order of distinct items in which no item appears in its original place.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of n distinct items is known as the subfactorial of n,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Quackery | Quackery | [ 0 swap
[ dup 0 != while
dup 1 & if
[ dip 1+ ]
1 >> again ]
drop ] is bits ( n --> n )
[ [] unrot
bit times
[ i bits
over = if
[ dip
[ i join ] ] ]
drop ] is combnums ( n n --> [ )
[ [] 0... | Give a code snippet in #Quackery
Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 ... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.