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/String_interpolation_(included) | String interpolation (included) |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Run_BASIC | Run BASIC | "a$ = Mary had a X lamb."
a$ = word$(a$,1,"X")+"little"+word$(a$,2,"X")
print a$
| Give a code snippet in #Run_BASIC
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operati... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an avera... | #PureBasic | PureBasic | Procedure.d SMA(Number, Period=0)
Static P
Static NewList L()
Protected Sum=0
If Period<>0
P=Period
EndIf
LastElement(L())
AddElement(L())
L()=Number
While ListSize(L())>P
FirstElement(L())
DeleteElement(L(),1)
Wend
ForEach L()
sum+L()
Next
ProcedureReturn sum/ListSize(L())
En... | Give a code snippet in #PureBasic
Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Latitude | Latitude | myObject someMethod (arg1, arg2, arg3).
MyClass someMethod (arg1, arg2, arg3). | Give a code snippet in #Latitude
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is invol... | #C | C | #include <stdio.h>
#include <stdlib.h>
/* pick a random index from 0 to n-1, according to probablities listed
in p[] which is assumed to have a sum of 1. The values in the probablity
list matters up to the point where the sum goes over 1 */
int rand_idx(double *p, int n)
{
double s = rand() / (RAND_MAX + 1.0);... | Give a code snippet in #C
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floatin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pig_the_dice_game | Pig the dice game | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to their score for that turn and th... | #Python | Python | #!/usr/bin/python3
'''
See: http://en.wikipedia.org/wiki/Pig_(dice)
This program scores and throws the dice for a two player game of Pig
'''
from random import randint
playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0
while max(safescore) < maxscore:
rolling = input("Player... | Give a code snippet in #Python
The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either:
Rolling the dice: where a roll of two to six is added to ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #R | R | accumulatorFactory <- function(init) {
currentSum <- init
function(add) {
currentSum <<- currentSum + add
currentSum
}
} | Give a code snippet in #R
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Evolutionary_algorithm | Evolutionary algorithm | Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its argument to the target string.... | #REXX | REXX | /*REXX program demonstrates an evolutionary algorithm (by using mutation). */
parse arg children MR seed . /*get optional arguments from the C.L. */
if children=='' | children=="," then children=10 /*# children produced each generation. */
if MR =='' | MR =="," then MR= "4%" ... | Give a code snippet in #REXX
Starting with:
The target string: "METHINKS IT IS LIKE A WEASEL".
An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
A fitness function that computes the ‘closeness’ of its ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Literals/String | Literals/String | Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters
Here document
Other tasks r... | #Quackery | Quackery | /O> char X emit
... char Y emit
... char Z emit cr
... $ "This is a 'string'." echo$ cr
... $ 'This is a "string" too.' echo$ cr
... $ ~This is one with "quotes" and 'apostrophes'.~ echo$ cr
... $ \Any non-whitespace character can be the delimiter.\ echo$ cr
...
XYZ
This is a 'string'.
This is a "string" too.
This is ... | Give a code snippet in #Quackery
Task
Show literal specification of characters and strings.
If supported, show how the following work:
verbatim strings (quotes where escape sequences are quoted literally)
here-strings
Also, discuss which quotes expand variables.
Related tasks
Special characters... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
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
... | #Clean | Clean | import StdEnv
less s1 s2
| size s1 > size s2 = True
| size s1 < size s2 = False
| otherwise = lower s1 < lower s2
where
lower :: String -> String
lower s = {toLower c \\ c <-: s}
Start = sortBy less ["This", "is", "a", "set", "of", "strings", "to", "sort"] | Give a code snippet in #Clean
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/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.
| #Sparkling | Sparkling | var line;
while (line = getline()) != nil {
print(line);
} | Give a code snippet in #Sparkling
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/String_concatenation | String concatenation | String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another string literal.
To illustrate the operat... | #AutoHotkey | AutoHotkey | s := "hello"
Msgbox, %s%
s1 := s . " literal" ;the . is optional
Msgbox, %s1% | Give a code snippet in #AutoHotkey
String concatenation
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a string variable equal to any text value.
Create another string variable whose value is the original variable concatenated with another strin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Nautical_bell | Nautical bell |
Task
Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.
The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.
It is permissible for the program to daemonize, or to slave off a scheduler, and it is per... | #AWK | AWK |
# syntax: GAWK -f NAUTICAL_BELL.AWK
BEGIN {
# sleep_cmd = "sleep 55s" # Unix
sleep_cmd = "TIMEOUT /T 55 >NUL" # MS-Windows
split("Middle,Morning,Forenoon,Afternoon,Dog,First",watch_arr,",")
split("One,Two,Three,Four,Five,Six,Seven,Eight",bells_arr,",")
simulate1day()
while (1) {
t = systim... | Give a code snippet in #AWK
Task
Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.
The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.
It is permissible for the program to daemonize, or to slave o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Largest_proper_divisor_of_n | Largest proper divisor of n | Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| #AWK | AWK |
# syntax: GAWK -f LARGEST_PROPER_DIVISOR_OF_N.AWK
# converted from C
BEGIN {
start = 1
stop = 100
for (i=start; i<=stop; i++) {
printf("%3d%1s",largest_proper_divisor(i),++count%10?"":"\n")
}
printf("\nLargest proper divisor of n %d-%d\n",start,stop)
exit(0)
}
function largest_proper_div... | Give a code snippet in #AWK
Task
a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #PicoLisp | PicoLisp | (call 'mv "input.txt" "output.txt")
(call 'mv "docs" "mydocs")
(call 'mv "/input.txt" "/output.txt")
(call 'mv "/docs" "/mydocs") | Give a code snippet in #PicoLisp
Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Identity_matrix | Identity matrix | Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0
1
⋯
0
⋮
⋮
⋮
⋱
... | #Elena | Elena | import extensions;
import system'routines;
import system'collections;
public program()
{
var n := console.write:"Enter the matrix size:".readLine().toInt();
var identity := new Range(0, n).selectBy:(i => new Range(0,n).selectBy:(j => (i == j).iif(1,0) ).summarize(new ArrayList()))
... | Give a code snippet in #Elena
Task
Build an identity matrix of a size known at run-time.
An identity matrix is a square matrix of size n × n,
where the diagonal elements are all 1s (ones),
and all the other elements are all 0s (zeroes).
I
n
=
[
1
0
0
⋯
0
0
1
0
⋯
0
0
0... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Simulate_input/Keyboard | Simulate input/Keyboard | Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| #LabVIEW | LabVIEW | when defined(windows):
import winlean
else:
{.error: "not supported os".}
type
InputType = enum
itMouse itKeyboard itHardware
KeyEvent = enum
keExtendedKey = 0x0001
keKeyUp = 0x0002
keUnicode = 0x0004
keScanCode = 0x0008
MouseInput {.importc: "MOUSEINPUT".} = object
dx, dy: clong... | Give a code snippet in #LabVIEW
Task
Send simulated keystrokes to a GUI window, or terminal.
You should specify whether the target may be externally created
(i.e., if the keystrokes are going to an application
other than the application that is creating them).
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #MATLAB | MATLAB | function [theSet,realAxis,imaginaryAxis] = mandelbrotSet(start,gridSpacing,last,maxIteration)
%Define the escape time algorithm
function escapeTime = escapeTimeAlgorithm(z0)
escapeTime = 0;
z = 0;
while( (abs(z)<=2) && (escapeTime < maxIteration) )
z = (z + z0)^2; ... | Give a code snippet in #MATLAB
Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of ... | #Vlang | Vlang | fn divisors(n i64) []i64 {
mut divs := [i64(1)]
mut divs2 := []i64{}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
j := n / i
divs << i
if i != j {
divs2 << j
}
}
}
for i := divs2.len - 1; i >= 0; i-- {
divs << divs2... | Give a code snippet in #Vlang
An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alter... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pinstripe/Display | Pinstripe/Display | Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display, we can switch to a wider 2 pi... | #Scala | Scala | import java.awt._
import javax.swing._
object PinstripeDisplay extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Pinstripe") {
class Pinstripe_Display extends JPanel {
override def paintComponent(g: Graphics): Unit = {
val bands = 4
super.paintComponent(g)
... | Give a code snippet in #Scala
Sample image
The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display.
in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes
Quarter of the way down the display... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number | Continued fraction/Arithmetic/Construct from rational number | Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
r
a
c
t
i
o
n
{\displaystyle {\m... | #PARI.2FGP | PARI/GP | apply(contfrac,[1/2,3,23/8,13/11,22/7,-151/77]) | Give a code snippet in #PARI.2FGP
Continued fraction arithmetic
The purpose of this task is to write a function
r
2
c
f
(
i
n
t
{\displaystyle {\mathit {r2cf}}(\mathrm {int} }
N
1
,
i
n
t
{\displaystyle N_{1},\mathrm {int} }
N
2
)
{\displaystyle N_{2})}
, or
r
2
c
f
(
F
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Mandelbrot_set | Mandelbrot set | Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| #Racket | Racket |
#lang racket
(require racket/draw)
(define (iterations a z i)
(define z′ (+ (* z z) a))
(if (or (= i 255) (> (magnitude z′) 2))
i
(iterations a z′ (add1 i))))
(define (iter->color i)
(if (= i 255)
(make-object color% "black")
(make-object color% (* 5 (modulo i 15)) (* 32 (modulo i ... | Give a code snippet in #Racket
Mandelbrot set
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Generate and draw the Mandelbrot set.
Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯... | #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"strings"
)
func main() {
sample(100)
sample(1000)
sample(10000)
}
func sample(n int) {
// generate data
d := make([]float64, n)
for i := range d {
d[i] = rand.Float64()
}
// show mean, standard deviation
va... | Give a code snippet in #Go
Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Lua | Lua |
local c = 0
function Tail(proper)
c = c + 1
if proper then
if c < 9999999 then return Tail(proper) else return c end
else
return 1/c+Tail(proper) -- make the recursive call must keep previous stack
end
end
local ok,check = pcall(Tail,true)
print(c, ok, check)
c=0
ok,check = pcall(Tail,false)
print... | Give a code snippet in #Lua
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #XPL0 | XPL0 |
func Det(A, N); \Return value of determinate A, order N
int A, N;
int B, Sum, I, K, L, Term;
[if N = 1 then return A(0, 0);
B:= Reserve((N-1)*4\IntSize\);
Sum:= 0;
for I:= 0 to N-1 do
[L:= 0;
for K:= 0 to N-1 do
if K # I then
[B(L):= @A(K, 1); L:= L+1];
Term:= A(I, 0) * Det(B, N-1... | Give a code snippet in #XPL0
linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_... | christopher/rosetta-code | |
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously | First-class functions/Use numbers analogously | In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to create an ordered collection of a m... | #Clojure | Clojure | (def x 2.0)
(def xi 0.5)
(def y 4.0)
(def yi 0.25)
(def z (+ x y))
(def zi (/ 1.0 (+ x y)))
(def numbers [x y z])
(def invers [xi yi zi])
(defn multiplier [a b]
(fn [m] (* a b m)))
> (for [[n i] (zipmap numbers invers)]
((multiplier n i) 0.5))
(0.5 0.5 0.5) | Give a code snippet in #Clojure
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types.
This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
Write a program to cr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Aime | Aime | integer i;
i = 1024;
while (i) {
o_plan(i, "\n");
i /= 2;
} | Give a code snippet in #Aime
Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Fur... | #PL.2FI | PL/I | *process source attributes xref or(!);
arat: Proc Options(main);
/*--------------------------------------------------------------------
* Rational Arithmetic
* (Mis)use the Complex data type to represent fractions
* real(x) is used as numerator
* imag(x) is used as denominator
* Output:
* a=-3/7 b=9/2
* a*b=-2... | Give a code snippet in #PL.2FI
Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 ... | #DCL | DCL | $ p1 = f$integer( p1 )
$ max = p1 * p1
$
$ i = 0
$ r = 1
$ rd = 0
$ c = 1
$ cd = 1
$ loop:
$ a'r'_'c' = i
$ nr = r + rd
$ nc = c + cd
$ if nr .eq. 0 .or. nc .eq. 0 .or. nr .gt. p1 .or. nc .gt. p1 .or. f$type( a'nr'_'nc' ) .nes. ""
$ then
$ gosub change_directions
$ endif
$ r = r + rd
$ c = c + cd
$ i = i + 1... | Give a code snippet in #DCL
Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Negative_base_numbers | Negative base numbers | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the decimal number 146 as negaternary... | #Phix | Phix | with javascript_semantics
constant digits = "0123456789"&
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"&
"abcdefghijklmnopqrstuvwxyz"
type base(integer b)
return b<=-1 and b>=-length(digits)
end type
function encodeNegBase(atom n, base b)
string res = iff(n?"":"0")
while n!=0 do
... | Give a code snippet in #Phix
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2]
Task
Encode the decimal number 10 as negabinary (expect 11110)
Encode the dec... | 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... | #Forth | Forth | \ declare the configuration variables in the FORTH app
FORTH DEFINITIONS
32 CONSTANT $SIZE
VARIABLE FULLNAME $SIZE ALLOT
VARIABLE FAVOURITEFRUIT $SIZE ALLOT
VARIABLE NEEDSPEELING
VARIABLE SEEDSREMOVED
VARIABLE OTHERFAMILY(1) $SIZE ALLOT
VARIABLE OTHERFAMILY(2) $SIZE ALLOT
: -leading ( addr len -- addr' len... | Give a code snippet in #Forth
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 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substring/Top_and_tail | Substring/Top and tail | The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
If the program uses UTF-8 or UTF... | #Haskell | Haskell | -- We define the functions to return an empty string if the argument is too
-- short for the particular operation.
remFirst, remLast, remBoth :: String -> String
remFirst "" = ""
remFirst cs = tail cs
remLast "" = ""
remLast cs = init cs
remBoth (c:cs) = remLast cs
remBoth _ = ""
main :: IO ()
main = do
... | Give a code snippet in #Haskell
The task is to demonstrate how to remove the first and last characters from a string.
The solution should demonstrate how to obtain the following results:
String with first character removed
String with last character removed
String with both the first and last characters removed
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Interactive_programming_(repl) | Interactive programming (repl) | Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
Task
Show how to start this... | #Go | Go | package main
import "fmt"
func f(s1, s2, sep string) string {
return s1 + sep + sep + s2
}
func main() {
fmt.Println(f("Rosetta", "Code", ":"))
} | Give a code snippet in #Go
Many language implementations come with an interactive mode.
This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions.
An interactive mode may also be known as a command mode, a read-eval-print loop (REPL), or a shell.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
say
say 'Loops/While'
x_ = 1024
loop while x_ > 0
say x_.right(6)
x_ = x_ % 2 -- integer division
end | Give a code snippet in #NetRexx
Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downw... | 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... | #Yabasic | Yabasic | sub MapRange(s, a1, a2, b1, b2)
return b1+(s-a1)*(b2-b1)/(a2-a1)
end sub
for i = 0 to 10 step 2
print i, " : ", MapRange(i,0,10,-1,0)
next | Give a code snippet in #Yabasic
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... | 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... | #XPL0 | XPL0 | func IntLen(N); \Return number of digits in N
int N, L;
[L:= 0;
repeat N:= N/10;
L:= L+1;
until N = 0;
return L;
];
def Size = 1000000;
int Fusc(Size), N, Len, Max;
[Fusc(0):= 0; Fusc(1):= 1;
for N:= 2 to Size-1 do
Fusc(N):= if N&1 then Fusc((N-1)/2) + Fusc((N+1)/2) else Fusc(N/2);
for N:= 0 to 60 do... | Give a code snippet in #XPL0
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 sta... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Video_display_modes | Video display modes | The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| #ARM_Assembly | ARM Assembly |
MOV R1,#0x04000000
MOV R0,#0x403
STR r0,[r1] ;the game boy advance is little-endian, so I would have expected this not to work. However it does indeed work.
| Give a code snippet in #ARM_Assembly
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Vector_products | Vector products | A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would repr... | #Swift | Swift | import Foundation
infix operator • : MultiplicationPrecedence
infix operator × : MultiplicationPrecedence
public struct Vector {
public var x = 0.0
public var y = 0.0
public var z = 0.0
public init(x: Double, y: Double, z: Double) {
(self.x, self.y, self.z) = (x, y, z)
}
public static func • (lh... | Give a code snippet in #Swift
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of nu... | 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.
| #Kotlin | Kotlin | // version 1.1.3
import java.net.InetAddress
import java.net.Inet4Address
import java.net.Inet6Address
fun showIPAddresses(host: String) {
try {
val ipas = InetAddress.getAllByName(host)
println("The IP address(es) for '$host' is/are:\n")
for (ipa in ipas) {
print(when (ipa) ... | Give a code snippet in #Kotlin
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/Include_a_file | Include a file | Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| #Lua | Lua | require "myheader" | Give a code snippet in #Lua
Task
Demonstrate the language's ability to include source code from other files.
See Also
Compiler/Simple file inclusion pre processor
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Associative_array/Iteration | Associative array/Iteration | Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked ... | #Ring | Ring |
# Project : Associative array/Iteration
lst = [["hello", 13], ["world", 31], ["!", 71]]
for n = 1 to len(lst)
see lst[n][1] + " : " + lst[n][2] + nl
next
| Give a code snippet in #Ring
Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
See also
Array
Associative array: Creation, Iteration
Collections
Comp... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
// Only valid for n > 0 && base >= 2
var mult = Fn.new { |n, base|
var m = BigInt.one
while (m > BigInt.zero && n > BigInt.zero) {
var dm = n.divMod(base)
m = m * dm[1]
n = dm[0]
}
return m
}
// Only valid for n >= 0 && base >= 2... | Give a code snippet in #Wren
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Playfair_cipher | Playfair cipher | Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the encrypted and decrypted message ... | #ooRexx | ooRexx | /*---------------------------------------------------------------------
* REXX program implements a PLAYFAIR cipher (encryption & decryption).
* 11.11.2013 Walter Pachl revamped, for ooRexx, the REXX program
* the logic of which was devised by Gerard Schildberger
* Invoke as rexx pf O abcd efgh ( phrase ... | Give a code snippet in #ooRexx
Playfair cipher
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Implement a Playfair cipher for encryption and decryption.
The user must be able to choose J = I or no Q in the alphabet.
The output of the ... | 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... | #Swift | Swift | let setA : Set<String> = ["John", "Bob", "Mary", "Serena"]
let setB : Set<String> = ["Jim", "Mary", "John", "Bob"]
println(setA.exclusiveOr(setB)) // symmetric difference of A and B
println(setA.subtract(setB)) // elements in A that are not in B | Give a code snippet in #Swift
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
)
{\dis... | 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... | #Common_Lisp | Common Lisp | ;; Greedy wrap line
(defun greedy-wrap (str width)
(setq str (concatenate 'string str " ")) ; add sentinel
(do* ((len (length str))
(lines nil)
(begin-curr-line 0)
(prev-space 0 pos-space)
(pos-space (position #\Space str) (when (< (1+ prev-space) len) (position #\Space str :start ... | Give a code snippet in #Common_Lisp
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, o... | 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... | #Julia | Julia | using Printf
mutable struct VLQ
quant::Vector{UInt8}
end
function VLQ(n::T) where T <: Integer
quant = UInt8.(digits(n, 128))
@inbounds for i in 2:length(quant) quant[i] |= 0x80 end
VLQ(reverse(quant))
end
import Base.UInt64
function Base.UInt64(vlq::VLQ)
quant = reverse(vlq.quant)
n = shi... | Give a code snippet in #Julia
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/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The stora... | #ooRexx | ooRexx |
'==============
Class ArenaPool
'==============
string buf
sys pb,ii
method Setup(sys n) as sys {buf=nuls n : pb=strptr buf : ii=0 : return pb}
method Alloc(sys n) as sys {method=pb+ii : ii+=n}
method Empty() {buf="" : pb=0 : ii=0}
end class
macro Create(type,name,qty,pool)
type name[qty] at ... | Give a code snippet in #ooRexx
Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a ref... | christopher/rosetta-code | |
http://rosettacode.org/wiki/HTTPS | HTTPS | Task
Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console.
Checking the host certificate for validity is recommended.
Do not authenticate. That is the subject of other tasks.
Readers may wish to contrast with the HTTP Request task, and also the task on HTT... | #Ioke | Ioke |
connection = URL new("https://sourceforge.net") openConnection
scanner = Scanner new(connection getInputStream)
while(scanner hasNext,
scanner next println
)
| Give a code snippet in #Ioke
Task
Send a GET request to obtain the resource located at the URL "https://www.w3.org/", then print it to the console.
Checking the host certificate for validity is recommended.
Do not authenticate. That is the subject of other tasks.
Readers may wish to contrast with the HTTP Request ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Equilibrium_index | Equilibrium index | An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
=
1
{\displaystyle A_{1}=1}
... | #Scala | Scala | def getEquilibriumIndex(A: Array[Int]): Int = {
val bigA: Array[BigInt] = A.map(BigInt(_))
val partialSums: Array[BigInt] = bigA.scanLeft(BigInt(0))(_+_).tail
def lSum(i: Int): BigInt = if (i == 0) 0 else partialSums(i - 1)
def rSum(i: Int): BigInt = partialSums.last - partialSums(i)
def ... | Give a code snippet in #Scala
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
For example, in a sequence
A
{\displaystyle A}
:
A
0
=
−
7
{\displaystyle A_{0}=-7}
A
1
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Verhoeff_algorithm | Verhoeff algorithm | Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adjacent digits, which was at t... | #C | C | #include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
static const int d[][10] = {
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},
{2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},
{4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},
{... | Give a code snippet in #C
Description
The Verhoeff algorithm is a checksum formula for error detection developed by the Dutch mathematician Jacobus Verhoeff and first published in 1969. It was the first decimal check digit algorithm which detects all single-digit errors, and all transposition errors involving two adja... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is invol... | #Yabasic | Yabasic | dim letters$(7)
data "aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"
letters$(0) = "aleph"
letters$(1) = "beth"
letters$(2) = "gimel"
letters$(3) = "daleth"
letters$(4) = "he"
letters$(5) = "waw"
letters$(6) = "zayin"
letters$(7) = "heth"
dim actual(7)
dim probs(7)
probs(0) = 1/5.0
probs(1) = 1/6.0
pro... | Give a code snippet in #Yabasic
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Here_document | Here document | A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a here document is constructed using a command followed by "<<" (or some other symbol) followed by a token string.
The text ... | #Common_Lisp | Common Lisp | ;; load cl-heredoc with QuickLisp
(ql:quickload 'cl-heredoc)
;; use #>xxx>yyyyyyyy!xxx as read-macro for heredoc
(set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
;; example:
(format t "~A~%" #>eof1>Write whatever (you) "want",
no matter how many lines or what characters until
the magic end sequenc... | Give a code snippet in #Common_Lisp
A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a here document is constructed using a command followed by "<<" (or some other symbol) f... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor | Terminal control/Hiding the cursor | The task is to hide the cursor and show it again.
| #Common_Lisp | Common Lisp |
(defun sh (cmd)
#+clisp (shell cmd)
#+ecl (si:system cmd)
#+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)
#+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*))
(defun show-cursor (x)
(if x (sh "tput cvvis") (sh "tput civis"))... | Give a code snippet in #Common_Lisp
The task is to hide the cursor and show it again.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #BASIC | BASIC | DECLARE SUB addVal (value AS INTEGER)
DECLARE FUNCTION findMax% ()
REDIM SHARED vals(0) AS INTEGER
DIM SHARED valCount AS INTEGER
DIM x AS INTEGER, y AS INTEGER
valCount = -1
'''''begin test run
RANDOMIZE TIMER
FOR x = 1 TO 10
y = INT(RND * 100)
addVal y
PRINT y; " ";
NEXT
PRINT ": "; findMax
'''''end... | Give a code snippet in #BASIC
Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #NewLISP | NewLISP | (let (sentence "She was a soul stripper. She took my heart!")
(replace "[aei]" sentence "" 0)) | Give a code snippet in #NewLISP
Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #Raku | Raku | my @list;
my $longest = 0;
my %seen;
for 1 .. 1000000 -> $m {
next unless $m ~~ /0/; # seed must have a zero
my $j = join '', $m.comb.sort;
next if %seen{$j}:exists; # already tested a permutation
%seen{$j} = '';
my @seq = converging($m);
my %elems;
my $count;
for @seq[] -... | Give a code snippet in #Raku
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 31131... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #NewLISP | NewLISP | (let (i 1024)
(while (> i 0)
(println i)
(setq i (/ i 2)))) | Give a code snippet in #NewLISP
Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downw... | 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... | #VBScript | VBScript | buffer = ""
For i = 2 To 8 Step 2
buffer = buffer & i & " "
Next
WScript.Echo buffer | Give a code snippet in #VBScript
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/... | 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... | #hexiscript | hexiscript | for let i 0; i <= 50; let i (i + 5)
println i
endfor | Give a code snippet in #hexiscript
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
Loop... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Least_common_multiple | Least common multiple | Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has both m and n as factor... | #Excel | Excel | =LCM(A1:J1) | Give a code snippet in #Excel
Least common multiple
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Compute the least common multiple (LCM) of two integers.
Given m and n, the least common multiple is the smallest positive integer that has... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #Go | Go | package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
... | Give a code snippet in #Go
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 3113112... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jewels_and_stones | Jewels and stones | Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case ... | #Go | Go | package main
import (
"fmt"
"strings"
)
func js(stones, jewels string) (n int) {
for _, b := range []byte(stones) {
if strings.IndexByte(jewels, b) >= 0 {
n++
}
}
return
}
func main() {
fmt.Println(js("aAAbbbb", "aA"))
} | Give a code snippet in #Go
Jewels and stones
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case le... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Two_bullet_roulette | Two bullet roulette | The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:
A revolver handgun has a revolving cylinder with six chambers for bullets.
It is loaded with the following procedure:
1. Check the first chamber to the right of the trigger for a bullet. If a bullet
is seen, the cyli... | #Python | Python | """ Russian roulette problem """
import numpy as np
class Revolver:
""" simulates 6-shot revolving cylinger pistol """
def __init__(self):
""" start unloaded """
self.cylinder = np.array([False] * 6)
def unload(self):
""" empty all chambers of cylinder """
self.cylinder... | Give a code snippet in #Python
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:
A revolver handgun has a revolving cylinder with six chambers for bullets.
It is loaded with the following procedure:
1. Check the first chamber to the right of the trigger for a bulle... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #Rust | Rust | use std::fmt;
#[derive(Clone,Copy)]
struct Point {
x: f64,
y: f64
}
fn distance (p1: Point, p2: Point) -> f64 {
((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt()
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:.4}, {:.4})", self.x, ... | Give a code snippet in #Rust
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abundant_odd_numbers | Abundant odd numbers | An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alternately, has the sigma sum of ... | #Julia | Julia | using Primes
function propfact(n)
f = [one(n)]
for (p, x) in factor(n)
f = reduce(vcat, [f*p^i for i in 1:x], init=f)
end
pop!(f)
sort(f)
end
isabundant(n) = sum(propfact(n)) > n
prettyprintfactors(n) = (a = propfact(n); println("$n has proper divisors $a, these sum to $(sum(a))."))
fu... | Give a code snippet in #Julia
An Abundant number is a number n for which the sum of divisors σ(n) > 2n,
or, equivalently, the sum of proper divisors (or aliquot sum) s(n) > n.
E.G.
12 is abundant, it has the proper divisors 1,2,3,4 & 6 which sum to 16 ( > 12 or n);
or alter... | christopher/rosetta-code | |
http://rosettacode.org/wiki/HTTPS/Authenticated | HTTPS/Authenticated | The goal of this task is to demonstrate HTTPS requests with authentication.
Implementations of this task should not use client certificates for this: that is the subject of another task.
| #Go | Go | package main
import (
"encoding/base64"
"io"
"log"
"net/http"
"strings"
)
const userPass = "rosetta:code"
const unauth = http.StatusUnauthorized
func hw(w http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Basic ") {
l... | Give a code snippet in #Go
The goal of this task is to demonstrate HTTPS requests with authentication.
Implementations of this task should not use client certificates for this: that is the subject of another task.
| 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
| #Ada | Ada | with Lumen.Image;
package Noise is
function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor;
end Noise; | Give a code snippet in #Ada
Generate a random black and white 320x240 image continuously,
showing FPS (frames per second).
A sample image
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Undefined_values | Undefined values | #PARI.2FGP | PARI/GP | v == 'v | Give a code snippet in #PARI.2FGP
| christopher/rosetta-code | ||
http://rosettacode.org/wiki/Accumulator_factory | Accumulator factory | A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat... | #Elixir | Elixir | defmodule AccumulatorFactory do
def new(initial) do
{:ok, pid} = Agent.start_link(fn() -> initial end)
fn (a) ->
Agent.get_and_update(pid, fn(old) -> {a + old, a + old} end)
end
end
end | Give a code snippet in #Elixir
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Iterated_digits_squaring | Iterated digits squaring | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else i... | #C | C | #include <stdio.h>
typedef unsigned long long ull;
int is89(int x)
{
while (1) {
int s = 0;
do s += (x%10)*(x%10); while ((x /= 10));
if (s == 89) return 1;
if (s == 1) return 0;
x = s;
}
}
int main(void)
{
// array bounds is sort of random here, it's big enough for 64bit unsigned.
ull sums[32*8... | Give a code snippet in #C
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Combinations_with_repetitions | Combinations with repetitions | The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of those sets is chosen from
S... | #R | R | library(gtools)
combinations(3, 2, c("iced", "jam", "plain"), set = FALSE, repeats.allowed = TRUE)
nrow(combinations(10, 3, repeats.allowed = TRUE)) | Give a code snippet in #R
The set of combinations with repetitions is computed from a set,
S
{\displaystyle S}
(of cardinality
n
{\displaystyle n}
), and a size of resulting selection,
k
{\displaystyle k}
, by reporting the sets of cardinality
k
{\displaystyle k}
where each member of thos... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Host_introspection | Host introspection | Print the word size and endianness of the host machine.
See also: Variable size/Get
| #Neko | Neko | /* Return wordsize to Neko */
/* From Rosetta Code, C entry, with Neko marshalling */
#include <stdio.h>
#include <stddef.h> /* for size_t */
#include <limits.h> /* for CHAR_BIT */
#include <neko.h>
value wordsize(void) {
/*
* Best bet: size_t typically is exactly one word.
*/
return alloc_int((in... | Give a code snippet in #Neko
Print the word size and endianness of the host machine.
See also: Variable size/Get
| 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:
... | #PowerBASIC | PowerBASIC | FUNCTION PBMAIN () AS LONG
DIM x(2), y(2) AS STRING * 1
DIM z(2) AS LONG
'data
ARRAY ASSIGN x() = ("a", "b", "c")
ARRAY ASSIGN y() = ("A", "B", "C")
ARRAY ASSIGN z() = (1, 2, 3)
'set upper bound
C& = UBOUND(x)
IF UBOUND(y) > C& THEN C& = UBOUND(y)
IF UBOUND(z) > C& THEN C& = ... | Give a code snippet in #PowerBASIC
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... | 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... | #Rust | Rust | use std::{ops, fmt};
#[derive(Copy, Clone, Debug)]
enum Trit {
True,
Maybe,
False,
}
impl ops::Not for Trit {
type Output = Self;
fn not(self) -> Self {
match self {
Trit::True => Trit::False,
Trit::Maybe => Trit::Maybe,
Trit::False => Trit::True,
... | Give a code snippet in #Rust
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/Self-describing_numbers | Self-describing numbers | Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ... | #MATLAB_.2F_Octave | MATLAB / Octave | function z = isSelfDescribing(n)
s = int2str(n)-'0'; % convert to vector of digits
y = hist(s,0:9);
z = all(y(1:length(s))==s);
end; | Give a code snippet in #MATLAB_.2F_Octave
Self-describing numbers
You are encouraged to solve this task according to the task description, using any language you may know.
There are several so-called "self-describing" or "self-descriptive" integers.
An integer is said to be "self-describing" if it has the property t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting 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
... | #Java | Java | public static void countingSort(int[] array, int min, int max){
int[] count= new int[max - min + 1];
for(int number : array){
count[number - min]++;
}
int z= 0;
for(int i= min;i <= max;i++){
while(count[i - min] > 0){
array[z]= i;
z++;
count[i - min]--;
}
}
} | Give a code snippet in #Java
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 sor... | 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... | #Factor | Factor | swap | Give a code snippet in #Factor
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 generici... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Infinity | Infinity | Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible po... | #BBC_BASIC | BBC BASIC | *FLOAT 64
PRINT FNinfinity
END
DEF FNinfinity
LOCAL supported%, maxpos, prev, inct
supported% = TRUE
ON ERROR LOCAL supported% = FALSE
IF supported% THEN = 1/0
RESTORE ERROR
inct = 1E10
REPEAT
prev = maxpos
inct *= 2
ON ERROR LO... | Give a code snippet in #BBC_BASIC
Task
Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherw... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #FreeBASIC | FreeBASIC | If Len(Command) Then
Open "notes.txt" For Append As #1
Print #1, Date, Time
Print #1, Chr(9); Command
Close
Else
If Open("notes.txt" For Input As #1) = 0 Then
Dim As String lin
Print "Contenido del archivo:"
Do While Not Eof(1)
Line Input #1, lin
Print... | Give a code snippet in #FreeBASIC
Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm | Bitmap/Bresenham's line algorithm | Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| #Julia | Julia | function drawline!(img::Matrix{T}, x0::Int, y0::Int, x1::Int, y1::Int, col::T) where T
δx = abs(x1 - x0)
δy = abs(y1 - y0)
δe = abs(δy / δx)
er = 0.0
y = y0
for x in x0:x1
img[x, y] = col
er += δe
if er > 0.5
y += 1
er -= 1.0
end
end... | Give a code snippet in #Julia
Task
Using the data storage type defined on the Bitmap page for raster graphics images,
draw a line given two points with Bresenham's line algorithm.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least t... | #Nim | Nim | const Suffix = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"]
proc nth(n: Natural): string =
$n & "'" & (if n mod 100 in 11..20: "th" else: Suffix[n mod 10])
for j in countup(0, 1000, 250):
for i in j..j+24:
stdout.write nth(i), " "
echo "" | Give a code snippet in #Nim
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show h... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Narcissist | Narcissist | Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o... | #Haskell | Haskell | main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t... | Give a code snippet in #Haskell
Quoting from the Esolangs wiki page:
A narcissist (or Narcissus program) is the decision-problem version of a quine.
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Forth | Forth | include lib/compare.4th
include 4pp/lib/foos.4pp
[ASSERT] \ enable assertions
:: Cat
class
method: dynamicCat \ virtual method
end-class {
:static staticCat { 2 } ; \ static method
:method { s" Mew!" } ; defines dynamicCat
} ... | Give a code snippet in #Forth
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Elena | Elena | import extensions;
public program()
{
auto s := emptyString;
if (s.isEmpty())
{ console.printLine("'", s, "' is empty") };
if (s.isNonempty())
{ console.printLine("'", s, "' is not empty") }
} | Give a code snippet in #Elena
Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Oth... | 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 |... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
a=5
b=3
c=a+b
c=a-b
c=a*b
c=a/b
c=a%b
| Give a code snippet in #TUSCRIPT
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 Operatio... | 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
| #Cowgol | Cowgol | include "cowgol.coh";
print("Hello world!");
print_nl(); | Give a code snippet in #Cowgol
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/Ranking_methods | Ranking methods |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Cowgol | Cowgol | include "cowgol.coh";
# List of competitors
record Competitor is
score: uint8;
name: [uint8];
end record;
var cs: Competitor[] := {
{44, "Solomon"},
{42, "Jason"},
{42, "Errol"},
{41, "Garry"},
{41, "Bernard"},
{41, "Barry"},
{39, "Stephen"}
};
# Rank competitors given ranking ... | Give a code snippet in #Cowgol
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Average_loop_length | Average loop length | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t... | #Delphi | Delphi |
program Average_loop_length;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
const
MAX_N = 20;
TIMES = 1000000;
function Factorial(const n: Double): Double;
begin
Result := 1;
if n > 1 then
Result := n * Factorial(n - 1);
end;
function Expected(const n: Integer): Double;
var
i: Integ... | Give a code snippet in #Delphi
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #PARI.2FGP | PARI/GP | stoogeSort(v)={
local(v=v); \\ Give children access to v
ss(1,#v); \\ Sort
v
}
ss(i,j)={
my(t);
if(v[j]<v[i],
t=v[i];
v[i]=v[j];
v[j]=t
);
if(j-i > 1,
t=(1+j-i)\3;
ss(i,j-t);
ss(i+t,j);
ss(i,j-t)
)
}; | Give a code snippet in #PARI.2FGP
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 |
Quic... | 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... | #Verbexx | Verbexx | // Floating-point Literals:
//
// If present,the exponent must be of the form:
//
// eNNN...N
// ENNN...N
// e-NNN...N
// E-NNN...N
// e+NNN...N
// E+NNN...N
//
// If present, length suffix must be:
//
// f F (FLOAT64_T)
// f32... | Give a code snippet in #Verbexx
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 BN... | 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
≤... | #Pike | Pike | string line = Stdio.stdin->gets();
sscanf(line, "%d %d", int a, int b);
write(a+b +"\n"); | Give a code snippet in #Pike
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #AutoHotkey | AutoHotkey | SortThreeVariables(ByRef x,ByRef y,ByRef z){
obj := []
for k, v in (var := StrSplit("x,y,z", ","))
obj[%v%] := true
for k, v in obj
temp := var[A_Index], %temp% := k
} | Give a code snippet in #AutoHotkey
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Qui... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #zkl | zkl | fcn isAttacked(q, x,y) // ( (r,c), x,y ) : is queen at r,c attacked by q@(x,y)?
{ r,c:=q; (r==x or c==y or r+c==x+y or r-c==x-y) }
fcn isSafe(r,c,qs) // queen safe at (r,c)?, qs=( (r,c),(r,c)..) solution so far
{ ( not qs.filter1(isAttacked,r,c) ) }
fcn queensN(N=8,row=1,queens=T){
qs:=[1..N].filter(isSafe.fpM... | Give a code snippet in #zkl
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tou... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string | Strip a set of characters from a string | Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in the second argument:
print str... | #Oforth | Oforth | String method: stripChars(str) #[ str include not ] self filter ;
"She was a soul stripper. She took my heart!" stripChars("aei") println | Give a code snippet in #Oforth
Task
Create a function that strips a set of characters from a string.
The function should take two arguments:
a string to be stripped
a string containing the set of characters to be stripped
The returned string should contain the first string, stripped of any characters in ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve | Sierpinski arrowhead curve | Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| #Rust | Rust | // [dependencies]
// svg = "0.8.0"
const SQRT3_2: f64 = 0.86602540378444;
use svg::node::element::path::Data;
struct Cursor {
x: f64,
y: f64,
angle: i32,
}
impl Cursor {
fn new(x: f64, y: f64) -> Cursor {
Cursor {
x: x,
y: y,
angle: 0,
}
}
... | Give a code snippet in #Rust
Task
Produce a graphical or ASCII-art representation of a Sierpinski arrowhead curve of at least order 3.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Set | Set |
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 set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creation
Test m ∈ S -- "m is an... | #C | C | #include <stdio.h>
typedef unsigned int set_t; /* probably 32 bits; change according to need */
void show_set(set_t x, const char *name)
{
int i;
printf("%s is:", name);
for (i = 0; (1U << i) <= x; i++)
if (x & (1U << i))
printf(" %d", i);
putchar('\n');
}
int main(void)
{
int i;
set_t a, b, c;
a = ... | Give a code snippet in #C
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 set is a collection of elements, without duplicates and without order.
Task
Show each of these set operations:
Set creat... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/0-1 | Knapsack problem/0-1 | A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have to last the whole day.
He cre... | #11l | 11l | F totalvalue(comb)
V totwt = 0
V totval = 0
L(item, wt, val) comb
totwt += wt
totval += val
R I totwt <= 400 {(totval, -totwt)} E (0, 0)
V items = [
(‘map’, 9, 150), (‘compass’, 13, 35), (‘water’, 153, 200), (‘sandwich’, 50, 160),
(‘glucose’, 15, 60), (‘tin’, 68, 45), (‘banana’, 27, 60),... | Give a code snippet in #11l
A tourist wants to make a good trip at the weekend with his friends.
They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip.
He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it, and it will have t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Egyptian_division | Egyptian division | Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of... | #R | R | Egyptian_division <- function(num, den){
pow2 = 0
row = 1
Table = data.frame(powers_of_2 = 2^pow2,
doubling = den)
while(Table$doubling[nrow(Table)] < num){
row = row + 1
pow2 = pow2 + 1
Table[row, 1] <- 2^pow2
Table[row, 2] <- 2^pow2 * den
}
Table <- Table[-nrow... | Give a code snippet in #R
Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of Ethiopian multiplication
Algorithm:
Given two numbers where the dividend is to be divided by the divisor:
Start the construction of a table of two columns: powers_of_2, and d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an ob... | #PicoLisp | PicoLisp | (if (not MyNewVariable)
(handle value-is-NIL) ) | Give a code snippet in #PicoLisp
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your la... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knuth_shuffle | Knuth shuffle | The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0 to last, the algorithm can be d... | #Groovy | Groovy | def shuffle = { list ->
if (list == null || list.empty) return list
def r = new Random()
def n = list.size()
(n..1).each { i ->
def j = r.nextInt(i)
list[[i-1, j]] = list[[j, i-1]]
}
list
} | Give a code snippet in #Groovy
The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Copy_a_string | Copy a string | This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
W... | #Phix | Phix | string one = "feed"
string two = one -- (two becomes "feed", one remains "feed")
two[2..3] = "oo" -- (two becomes "food", one remains "feed")
one[1] = 'n' -- (two remains "food", one becomes "need")
?{one,two}
| Give a code snippet in #Phix
This task is about copying a string.
Task
Where it is relevant, distinguish between copying the contents of a string
versus making an additional reference to an existing string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty st... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.