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/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows th... | #F.23 | F# | // palindrome_dates.fsx
open System
let is_palindrome_date =
let date_string (date: DateTime) = date.ToString "yyyyMMdd"
let is_palindrome s =
let rev_string = Seq.rev >> Seq.map string >> String.concat ""
s = rev_string s
date_string >> is_palindrome
let palindrome_dates =
let rec l... | Give a code snippet in #F.23
Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort | Sorting algorithms/Insertion sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #BASIC_2 | BASIC | DECLARE SUB InsertionSort (theList() AS INTEGER)
DIM n(10) AS INTEGER, L AS INTEGER, o AS STRING
FOR L = 0 TO 10
n(L) = INT(RND * 32768)
NEXT
InsertionSort n()
FOR L = 1 TO 10
PRINT n(L); ";";
NEXT
SUB InsertionSort (theList() AS INTEGER)
DIM insertionElementIndex AS INTEGER
FOR insertionElementInde... | Give a code snippet in #BASIC_2
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Maple | Maple | Export("directory/filename.txt", string); | Give a code snippet in #Maple
Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #AutoHotkey | AutoHotkey | MsgBox % Pow(5,3)
MsgBox % Pow(2.5,4)
Pow(x, n){
r:=1
loop %n%
r *= x
return r
} | Give a code snippet in #AutoHotkey
Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Abbreviations,_automatic | Abbreviations, automatic | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if
the minimum abbrevia... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. AUTO-ABBREVIATIONS.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT DOW ASSIGN TO "days-of-week.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
... | Give a code snippet in #COBOL
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub─commands, options, etc.
It would make a list of words easier to maintain (as words are added, changed, and/or del... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows th... | #Java | Java |
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class PalindromeDates {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2020, 2, 3);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
DateTimeFormatter formatterDa... | Give a code snippet in #Java
Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program... | 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... | #Go | Go | package main
import "fmt"
import "math"
func main() {
var a, b, c float64
a = math.Pow(5, math.Pow(3, 2))
b = math.Pow(math.Pow(5, 3), 2)
c = math.Pow(5, math.Pow(3, 2))
fmt.Printf("5^3^2 = %.0f\n", a)
fmt.Printf("(5^3)^2 = %.0f\n", b)
fmt.Printf("5^(3^2) = %.0f\n", c)
} | Give a code snippet in #Go
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to chec... | #Modula-2 | Modula-2 | MODULE Pangrams;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;
(* Check if a string is a pangram *)
PROCEDURE pangram(s: ARRAY OF CHAR): BOOLEAN;
VAR letters: ARRAY [0..25] OF BOOLEAN;
i: CARDINAL;
BEGIN
FOR i := 0 TO 25 DO letters[i] := FALSE; END;
FOR i := 0 TO Length(s)-1 ... | Give a code snippet in #Modula-2
Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Integer_sequence | Integer sequence | Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integer... | #BASIC256 | BASIC256 | i = 1
do
print i
i += 1
until i = 0 | Give a code snippet in #BASIC256
Task
Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
... | #M2000_Interpreter | M2000 Interpreter |
Module ShellSortExample {
Module shellsort(&a()) {
DEf h%, i%, j%, k, n%
n%=LEN(a())
h% = n%
WHILE h% {
IF h% = 2 THEN {h% = 1 }ELSE h%= h% DIV 2.2
FOR i% = h% TO n% - 1
k = a(i%)
... | Give a code snippet in #M2000_Interpreter
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 sor... | 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... | #D | D | import std.stdio, std.random, std.math, std.algorithm, std.range, std.format;
real analytical(in int n) pure nothrow @safe /*@nogc*/ {
enum aux = (int k) => reduce!q{a * b}(1.0L, iota(n - k + 1, n + 1));
return iota(1, n + 1)
.map!(k => (aux(k) * k ^^ 2) / (real(n) ^^ (k + 1)))
.sum;
}
... | Give a code snippet in #D
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of ... | #Delphi | Delphi | procedure IsXmasSunday(fromyear, toyear: integer);
var
i: integer;
TestDate: TDateTime;
outputyears: string;
begin
outputyears := '';
for i:= fromyear to toyear do
begin
TestDate := EncodeDate(i,12,25);
if dayofweek(TestDate) = 1 then
begin
outputyears := outputyears + inttostr(i) + ' ';
end;
... | Give a code snippet in #Delphi
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Go | Go | package pal
import "testing"
func TestPals(t *testing.T) {
pals := []string{
"",
".",
"11",
"ere",
"ingirumimusnocteetconsumimurigni",
}
for _, s := range pals {
if !IsPal(s) {
t.Error("IsPal returned false on palindrome,", s)
}
}
}... | Give a code snippet in #Go
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Terminal_control/Inverse_video | Terminal control/Inverse video | Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| #BASIC | BASIC | INVERSE:?"ROSETTA";:NORMAL:?" CODE" | Give a code snippet in #BASIC
Task
Display a word in inverse video (or reverse video) followed by a word in normal video.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Flow-control_structures | Flow-control structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.
Note that Conditional Struc... | #MUMPS | MUMPS | GOTO LABEL^ROUTINE | Give a code snippet in #MUMPS
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
Document common flow-control structures.
One common example of a flow-control structure is the goto construct.... | 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}
... | #Picat | Picat | equilibrium_index1(A, Ix) =>
append(Front, [_|Back], A),
sum(Front) = sum(Back),
Ix = length(Front)+1. % give 1 based index | Give a code snippet in #Picat
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/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #Slate | Slate | m@(Integer traits) ackermann: n@(Integer traits)
[
m isZero
ifTrue: [n + 1]
ifFalse:
[n isZero
ifTrue: [m - 1 ackermann: n]
ifFalse: [m - 1 ackermann: (m ackermann: n - 1)]]
]. | Give a code snippet in #Slate
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Print(ls As List(Of Integer))
Dim iter = ls.GetEnumerator
Console.Write("[")
If iter.MoveNext Then
Console.Write(iter.Current)
End If
While iter.MoveNext
Console.Write(", ")
Console.Write(iter.Current)
End While
... | Give a code snippet in #Visual_Basic_.NET
Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail 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
... | #Forth | Forth | defer precedes ( addr addr -- flag )
\ e.g. ' < is precedes
: sort ( a n --)
1- cells bounds 2>r false
begin
0= dup
while
2r@ ?do
i cell+ @ i @ over over precedes ( mark unsorted )
if i ... | Give a code snippet in #Forth
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/Miller%E2%80%93Rabin_primality_test | Miller–Rabin primality test |
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin primality test or Rabin–Miller prima... | #Scheme | Scheme | #!r6rs
(import (rnrs base (6))
(srfi :27 random-bits))
;; Fast modular exponentiation.
(define (modexpt b e M)
(cond
((zero? e) 1)
((even? e) (modexpt (mod (* b b) M) (div e 2) M))
((odd? e) (mod (* b (modexpt b (- e 1) M)) M))))
;; Return s, d such that d is odd and 2^s * d = n.
(define (spli... | Give a code snippet in #Scheme
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin prim... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Multi-base_primes | Multi-base primes | Prime numbers are prime no matter what base they are represented in.
A prime number in a base other than 10 may not look prime at first glance.
For instance: 19 base 10 is 25 in base 7.
Several different prime numbers may be expressed as the "same" string when converted to a different base.
107 base 10 converted... | #Go | Go | package main
import (
"fmt"
"math"
"rcu"
)
var maxDepth = 6
var maxBase = 36
var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true)
var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var maxStrings [][][]int
var mostBases = -1
func maxSlice(a []int)... | Give a code snippet in #Go
Prime numbers are prime no matter what base they are represented in.
A prime number in a base other than 10 may not look prime at first glance.
For instance: 19 base 10 is 25 in base 7.
Several different prime numbers may be expressed as the "same" string when converted to a different b... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked ... | #NewLISP | NewLISP | (dolist (x '(a b c d e))
(println x)) | Give a code snippet in #NewLISP
Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Defin... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Esthetic_numbers | Esthetic numbers | An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero differ by 9.
These examples are n... | #Raku | Raku | use Lingua::EN::Numbers;
sub esthetic($base = 10) {
my @s = ^$base .map: -> \s {
((s - 1).base($base) if s > 0), ((s + 1).base($base) if s < $base - 1)
}
flat [ (1 .. $base - 1)».base($base) ],
{ [ flat .map: { $_ xx * Z~ flat @s[.comb.tail.parse-base($base)] } ] } … *
}
for 2 .. 16 -> $b ... | Give a code snippet in #Raku
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1.
E.G.
12 is an esthetic number. One and two differ by 1.
5654 is an esthetic number. Each digit is exactly 1 away from its neighbour.
890 is not an esthetic number. Nine and zero diffe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/String_comparison | String comparison |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #Bracmat | Bracmat | ( {Comparing two strings for exact equality}
& ( ( @(abc:abc)
& @(123:%123)
{Previous pairs of strings are exactly equal}
)
& ( @(abc:Abc)
| @(123:%246/2)
| @(abc:ab)
| @(123:%12)
| {Previous pairs of strings are not exactly equal}
)
)
{Comparing two strings for inequality (i.e., t... | Give a code snippet in #Bracmat
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 Operation... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Environment_variables | Environment variables | Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
int CpuReg, PspSeg, EnvSeg, I, J, C;
char EnvVar;
[CpuReg:= GetReg; \access CPU registers
PspSeg:= CpuReg(9); \get segment address of our PSP
EnvSeg:= Peek(PspSeg,$2C) +... | Give a code snippet in #XPL0
Task
Show how to get one of your process's environment variables.
The available variables vary by system; some of the common ones available on Unix include:
PATH
HOME
USER
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua... | #COBOL | COBOL |
EVALUATE EXPRESSION-1 ALSO EXPRESSION-2
WHEN TRUE ALSO TRUE
DISPLAY 'Both are true.'
WHEN TRUE ALSO FALSE
DISPLAY 'Expression 1 is true.'
WHEN FALSE ALSO TRUE
DISPLAY 'Expression 2 is true.'
WHEN OTHER
DISPLAY 'Neither is true.'
END-EVALUATE
| Give a code snippet in #COBOL
Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g.... | 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 ... | #AutoHotkey | AutoHotkey | ; Submitted by MasterFocus --- http://tiny.cc/iTunis
Loop
{
InputBox, OutputVar, Price Fraction Example, Insert the value to be rounded.`n* [ 0 < value < 1 ]`n* Press ESC or Cancel to exit, , 200, 150
If ErrorLevel
Break
MsgBox % "Input: " OutputVar "`nResult: " PriceFraction( OutputVar )
}
;-------------... | Give a code snippet in #AutoHotkey
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 ... | 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... | #Monte | Monte |
var i := 1024
while (i > 0):
traceln(i)
i //= 2
| Give a code snippet in #Monte
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/Downwar... | 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)
... | #AutoHotkey | AutoHotkey | ISBN13_check_digit(n){
for i, v in StrSplit(RegExReplace(n, "[^0-9]"))
sum += !Mod(i, 2) ? v*3 : v
return n "`t" (Mod(sum, 10) ? "(bad)" : "(good)")
} | Give a code snippet in #AutoHotkey
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/Morse_code | Morse code | Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may either ignore unknown characters in the file... | #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
;;; I/O ports
KBB: equ 61h ; Keyboard controller port B (also controls speaker)
PITC2: equ 42h ; Programmable Interrupt Timer, channel 2 (frequency)
PITCTL: equ 43h ; PIT control port.
;;; Control bits
SPKR: equ 3 ; Lower two bits of KBB determine speaker on/off
CTR: equ 6 ; Counter select offset i... | Give a code snippet in #8086_Assembly
Morse code
It has been in use for more than 175 years — longer than any other electronic encoding system.
Task
Send a string as audible Morse code to an audio device (e.g., the PC speaker).
As the standard Morse code does not contain all possible characters,
you may eithe... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geomet... | #Forth | Forth | : agm ( a g -- m )
begin
fover fover f+ 2e f/
frot frot f* fsqrt
fover fover 1e-15 f~
until
fdrop ;
1e 2e -0.5e f** agm f. \ 0.847213084793979 | Give a code snippet in #Forth
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function t... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Associative_array/Merging | Associative array/Merging | Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Merge these into a new associativ... | #Ring | Ring |
load "stdlib.ring"
list1 = [:name = "Rocket Skates", :price = 12.75, :color = "yellow"]
list2 = [:price = 15.25, :color = "red", :year = 1974]
for n = 1 to len(list2)
flag = 0
for m = 1 to len(list1)
if list2[n][1] = list1[m][1]
flag = 1
del(list1,m)
add(list1,[lis... | Give a code snippet in #Ring
Task
Define two associative arrays, where one represents the following "base" data:
Key
Value
"name"
"Rocket Skates"
"price"
12.75
"color"
"yellow"
And the other represents "update" data:
Key
Value
"price"
15.25
"color"
"red"
"year"
1974
Mer... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Fractran | Fractran | FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial positive integer input
n
... | #Tcl | Tcl | package require Tcl 8.6
oo::class create Fractran {
variable fracs nco
constructor {fractions} {
set fracs {}
foreach frac $fractions {
if {[regexp {^(\d+)/(\d+),?$} $frac -> num denom]} {
lappend fracs $num $denom
} else {
return -code error "$frac is not a supported fraction"
}
}
if {... | Give a code snippet in #Tcl
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway.
A FRACTRAN program is an ordered list of positive fractions
P
=
(
f
1
,
f
2
,
…
,
f
m
)
{\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})}
, together with an initial ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a ... | #R | R | n <- 100000
u <- sqrt(-2*log(runif(n)))
v <- 2*pi*runif(n)
x <- u*cos(v)
y <- v*sin(v)
hist(x) | Give a code snippet in #R
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random num... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags | Rosetta Code/Fix code tags | Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
| #Maple | Maple | #Used <#/lang> to desensitize wiki
txt := FileTools[Text][ReadFile]("C:/Users/username/Desktop/text.txt"):
#langs should be a real list of programming languages
langs := ['foo', 'bar', 'baz', 'barf'];
for lan in langs do
txt := StringTools:-SubstituteAll(txt, cat("<", lan, ">"), cat ("<lang ", lan, ">")):
txt := Str... | Give a code snippet in #Maple
Task
Fix Rosetta Code deprecated code tags, with these rules:
Change <%s> to <lang %s>
Change </%s> to </lang>
Change <code %s> to <lang %s>
Change </code> to </lang>
Usage
./convert.py < wikisource.txt > converted.txt
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Knapsack_problem/Continuous | Knapsack problem/Continuous |
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after... | #Rust | Rust | fn main() {
let items: [(&str, f32, u8); 9] = [
("beef", 3.8, 36),
("pork", 5.4, 43),
("ham", 3.6, 90),
("greaves", 2.4, 45),
("flitch", 4.0, 30),
("brawn", 2.5, 56),
("welt", 3.7, 67),
("salami", 3.0, 95),
("sausage", 5.9, 98),
];
let ... | Give a code snippet in #Rust
A thief burgles a butcher's shop, where he can select from some items.
The thief knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; the ... | 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... | #D | D | import std.stdio, std.range;
void main() {
// Print odd numbers up to 9.
for (int i = 1; i < 10; i += 2)
writeln(i);
// Alternative way.
foreach (i; iota(1, 10, 2))
writeln(i);
} | Give a code snippet in #D
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/Increme... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #F.23 | F# |
//Find Cheryl's Birthday. Nigel Galloway: October 23rd., 2018
type Month = |May |June |July |August
let fN n= n |> List.filter(fun (_,n)->(List.length n) < 2) |> List.unzip
let dates = [(May,15);(May,16);(May,19);(June,17);(June,18);(July,14);(July,16);(August,14);(August,15);(August,17)]
let _,n = dates |> List.grou... | Give a code snippet in #F.23
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells A... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substring | Substring |
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 |... | #PicoLisp | PicoLisp | (let Str (chop "This is a string")
(prinl (head 4 (nth Str 6))) # From 6 of 4 length
(prinl (nth Str 6)) # From 6 up to the end
(prinl (head -1 Str)) # Minus last character
(prinl (head 8 (member "s" Str))) # From character "s" of length 8
(prinl ... | Give a code snippet in #PicoLisp
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/Pick_random_element | Pick random element | Demonstrate how to pick a random element from a list.
| #11l | 11l | print(random:choice([‘foo’, ‘bar’, ‘baz’])) | Give a code snippet in #11l
Demonstrate how to pick a random element from a list.
| 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
... | #Swift | Swift | func addCombo(prevCombo: [Int], var pivotList: [Int]) -> [([Int], [Int])] {
return (0..<pivotList.count)
.map {
_ -> ([Int], [Int]) in
(prevCombo + [pivotList.removeAtIndex(0)], pivotList)
}
}
func combosOfLength(n: Int, m: Int) -> [[Int]] {
return [Int](1...m)
.reduce([([Int](), [Int](0... | Give a code snippet in #Swift
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... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conjugate_transpose | Conjugate transpose | Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
(
M
H
)
j
i
=
M
i
j
... | #Common_Lisp | Common Lisp |
(defun matrix-multiply (m1 m2)
(mapcar
(lambda (row)
(apply #'mapcar
(lambda (&rest column)
(apply #'+ (mapcar #'* row column))) m2)) m1))
(defun identity-p (m &optional (tolerance 1e-6))
"Is m an identity matrix?"
(loop for row in m
for r = 1 then (1+ r) do
(loop for col in row
... | Give a code snippet in #Common_Lisp
Suppose that a matrix
M
{\displaystyle M}
contains complex numbers. Then the conjugate transpose of
M
{\displaystyle M}
is a matrix
M
H
{\displaystyle M^{H}}
containing the complex conjugates of the matrix transposition of
M
{\displaystyle M}
.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number | Factors of a Mersenne number | A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,... | #360_Assembly | 360 Assembly | * Factors of a Mersenne number 11/09/2015
MERSENNE CSECT
USING MERSENNE,R15
MVC Q,=F'929' q=929 (M929=2**929-1)
LA R6,1 k=1
LOOPK C R6,=F'1048576' do k=1 to 2**20
BNL ELOOPK
LR R5,R6 k
M ... | Give a code snippet in #360_Assembly
A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor b... | 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
⋮
⋮
⋮
⋱
... | #C.23 | C# |
using System;
using System.Linq;
namespace IdentityMatrix
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Requires exactly one argument");
return;
}
int n;
... | Give a code snippet in #C.23
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/Unicode_strings | Unicode strings | As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is your programming language for ... | #WDTE | WDTE | let プリント t => io.writeln io.stdout t;
プリント 'これは実験です。'; | Give a code snippet in #WDTE
As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, Unicode is your best friend.
It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings.
How well prepared is ... | 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
| #Wren | Wren | import "./fmt" for Fmt // imports the Fmt module and makes the 'Fmt' class available
import "./math" for Int // imports the Math module and makes the 'Int' class available
Fmt.print("The maximum safe integer in Wren is $,d.", Int.maxSafe) | Give a code snippet in #Wren
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/Penney%27s_game | Penney's game | Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or HTH for short.
The other pla... | #Go | Go |
package main
import "fmt"
import "math/rand"
func main(){
var a1,a2,a3,y,match,j,k int
var inp string
y=1
for y==1{
fmt.Println("Enter your sequence:")
fmt.Scanln(&inp)
var Ai [3] int
var user [3] int
for j=0;j<3;j++{
if(inp[j]==104){
user[j]=1
}else{
user[j]=0
}
}
for k=0;k<3;k++{
Ai[k]=rand.Intn(2)
}
for user[0]==A... | Give a code snippet in #Go
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or H... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_and_product_of_an_array | Sum and product of an array | Task
Compute the sum and product of an array of integers.
| #CoffeeScript | CoffeeScript |
sum = (array) ->
array.reduce (x, y) -> x + y
product = (array) ->
array.reduce (x, y) -> x * y
| Give a code snippet in #CoffeeScript
Task
Compute the sum and product of an array of integers.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail | Strip whitespace from a string/Top and tail | Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace removed
For the purposes of thi... | #D | D | import std.stdio, std.string;
void main() {
auto s = " \t \r \n String with spaces \t \r \n ";
assert(s.stripLeft() == "String with spaces \t \r \n ");
assert(s.stripRight() == " \t \r \n String with spaces");
assert(s.strip() == "String with spaces");
} | Give a code snippet in #D
Task
Demonstrate how to strip leading and trailing whitespace from a string.
The solution should demonstrate how to achieve the following three results:
String with leading whitespace removed
String with trailing whitespace removed
String with both leading and trailing whitespace remove... | 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
≤... | #Phixmonti | Phixmonti | /# Rosetta Code problem: http://rosettacode.org/wiki/A+B
by Galileo, 05/2022 #/
include ..\Utilitys.pmt
def valid
dup -1000 >= swap 1000 <= and
enddef
true while
clear cls
"Enter two numbers (betwen -1000 ... +1000) separated by space: " input split pop pop drop tonum swap tonum
over valid over va... | Give a code snippet in #Phixmonti
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, sepa... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newbie | Hello world/Newbie | Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the language-newbie is competent in install... | #Common_Lisp | Common Lisp |
(format t "Hello world!~%")
| Give a code snippet in #Common_Lisp
Task
Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the Hello world/Text task.
Assume the language-newbie is a programmer in another language.
Assume the la... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tree_from_nesting_levels | Tree from nesting levels | Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
Every int appears, in order, at its depth of nesting.
If the next level int is greater than the previous then it appears in a sub-list o... | #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Data.Bifunctor (bimap)
import Data.Tree (Forest, Tree (..), drawTree, foldTree)
------------- TREE FROM NEST LEVELS (AND BACK) -----------
treeFromSparseLevels :: [Int] -> Tree (Maybe Int)
treeFromSparseLevels =
Node Nothing
. forestFromNestLevels
. rooted
. nor... | Give a code snippet in #Haskell
Given a flat list of integers greater than zero, representing object nesting
levels, e.g. [1, 2, 4],
generate a tree formed from nested lists of those nesting level integers where:
Every int appears, in order, at its depth of nesting.
If the next level int is greater than the previou... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_to_100 | Sum to 100 | Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular sum (in this iconic case, ... | #Julia | Julia | using Printf, IterTools, DataStructures
expr(p::String...)::String = @sprintf("%s1%s2%s3%s4%s5%s6%s7%s8%s9", p...)
function genexpr()::Vector{String}
op = ["+", "-", ""]
return collect(expr(p...) for (p) in Iterators.product(op, op, op, op, op, op, op, op, op) if p[1] != "+")
end
using DataStructures
func... | Give a code snippet in #Julia
Task
Find solutions to the sum to one hundred puzzle.
Add (insert) the mathematical
operators + or - (plus
or minus) before any of the digits in the
decimal numeric string 123456789 such that the
resulting mathematical expression adds up to a
particular... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an ov... | #Kotlin | Kotlin | // version 1.0.6
infix fun Int.ipow(exp: Int): Int =
when {
this == 1 -> 1
this == -1 -> if (exp and 1 == 0) 1 else -1
exp < 0 -> throw IllegalArgumentException("invalid exponent")
exp == 0 -> 1
else -> {
var ans = 1
var base = this
... | Give a code snippet in #Kotlin
Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or pr... | 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 .
| #PHP | PHP | $min_x=-2;
$max_x=1;
$min_y=-1;
$max_y=1;
$dim_x=400;
$dim_y=300;
$im = @imagecreate($dim_x, $dim_y)
or die("Cannot Initialize new GD image stream");
header("Content-Type: image/png");
$black_color = imagecolorallocate($im, 0, 0, 0);
$white_color = imagecolorallocate($im, 255, 255, 255);
for($y=0;$y<=$dim_y;$y+... | Give a code snippet in #PHP
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/Variadic_function | Variadic function | Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Functions.
Related task
Call a function... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | show-all(:
while /= ) dup:
!.
drop
show-all( :foo "Hello" 42 [ true ] ) | Give a code snippet in #D.C3.A9j.C3.A0_Vu
Task
Create a function which takes in a variable number of arguments and prints each one on its own line.
Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime.
Functions of this type are also known as Variadic Fun... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Magic_constant | Magic constant | A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant.
EG
A 3 x 3 magic square always sums to ... | #Prolog | Prolog |
m(X,Y):- Y is X*(X*X+1)/2.
l(L,R,T,X):- L > R -> X is L; M is div(L+R,2), m(M,F),
(T < F -> R_ is M-1, l(L,R_,T,X); L_ is M+1, l(L_,R,T,X)).
l(B,X):- l(1,B,B,X).
task:-
write("First 20 magic constants are:"), forall(between(3,22,N), (m(N,X), format(" ~d",X))), nl,
write("The 1000th magic constant is:"... | Give a code snippet in #Prolog
A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant.
EG
A 3 ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Ackermann_function | Ackermann function | The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
n
+
1
if
m
=
0
A
(
m
... | #PL.2FI | PL/I | Ackerman: procedure (m, n) returns (fixed (30)) recursive;
declare (m, n) fixed (30);
if m = 0 then return (n+1);
else if m > 0 & n = 0 then return (Ackerman(m-1, 1));
else if m > 0 & n > 0 then return (Ackerman(m-1, Ackerman(m, n-1)));
return (0);
end Ackerman; | Give a code snippet in #PL.2FI
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
The Ackermann function is usually defined as follows:
A
(
m
,
n
)
=
{
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat... | #Clojure | Clojure | (defn modes [coll]
(let [distrib (frequencies coll)
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
sorted (sort-by (comp - freq) distrib)
maxfq (freq (first sorted))]
(map value (take-while #(= maxfq (freq %)) sorted)))) | Give a code snippet in #Clojure
Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #Kotlin | Kotlin | // version 1.1.2
fun throwDie(nSides: Int, nDice: Int, s: Int, counts: IntArray) {
if (nDice == 0) {
counts[s]++
return
}
for (i in 1..nSides) throwDie(nSides, nDice - 1, s + i, counts)
}
fun beatingProbability(nSides1: Int, nDice1: Int, nSides2: Int, nDice2: Int): Double {
val len1 ... | Give a code snippet in #Kotlin
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The playe... | 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 ... | #Fortran | Fortran | ! game 21 - an example in modern fortran language for rosseta code.
subroutine ai
common itotal, igoal
if (itotal .lt. igoal) then
move = 1
do i = 1, 3
if (mod(itotal + i - 1 , 4) .eq. 0) then
move = i
end if
end do
do i = 1, 3
if (itotal + i .eq. igoal) then
move... | Give a code snippet in #Fortran
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 th... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Strip_comments_from_a_string | Strip comments from a string | Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
Whitespace debacle: There is s... | #Groovy | Groovy | def stripComments = { it.replaceAll(/\s*[#;].*$/, '') } | Give a code snippet in #Groovy
Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line.
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion | Doubly-linked list/Element insertion | Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element inse... | #PicoLisp | PicoLisp | # Insert an element X at position Pos
(de 2insert (X Pos DLst)
(let (Lst (nth (car DLst) (dec (* 2 Pos))) New (cons X (cadr Lst) Lst))
(if (cadr Lst)
(con (cdr @) New)
(set DLst New) )
(if (cdr Lst)
(set @ New)
(con DLst New) ) ) )
(setq *DL (2list 'A 'B)) # Bu... | Give a code snippet in #PicoLisp
Doubly-Linked List (element)
This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #PureBasic | PureBasic | Prototype.i fun(x.i)
Procedure.i quark(z.i)
Debug "Quark "+Str(z) : ProcedureReturn z-1
EndProcedure
Procedure rep(q.fun,n.i)
Repeat : n=q(n) : Until n=0
EndProcedure
rep(@quark(),3) | Give a code snippet in #PureBasic
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Increment_a_numerical_string | Increment a numerical string | Task
Increment a numerical string.
| #REXX | REXX | /*REXX program demonstrates a method how to increment a numerical string*/
count = "3" /*REXX variables (and constants) are character strings.*/
count = 3 /*(identical to the above statement.) */
count = count+1 /*strings in a numerical context are treated as numbers*/
say 'sum=' count /*d... | Give a code snippet in #REXX
Task
Increment a numerical string.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #MUMPS | MUMPS |
GCD(A,B)
QUIT:((A/1)'=(A\1))!((B/1)'=(B\1)) 0
SET:A<0 A=-A
SET:B<0 B=-B
IF B'=0
FOR SET T=A#B,A=B,B=T QUIT:B=0 ;ARGUEMENTLESS FOR NEEDS TWO SPACES
QUIT A | Give a code snippet in #MUMPS
Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest... | christopher/rosetta-code | |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
Stri... | #8080_Assembly | 8080 Assembly | CR: equ 13
LF: equ 10
puts: equ 9 ; CP/M function to write a string to the console
bdos: equ 5 ; CP/M entry point
org 100h
mvi e,0 ; Start with first verse
;;; Print verse
verse: lxi h,onthe ; On the
call pstr
lxi h,ordtab
call ptabs ; Nth
lxi h,doc
call pstr ; day of Christmas, my true love gave to me
lxi h,... | Give a code snippet in #8080_Assembly
Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string o... | christopher/rosetta-code | |
http://rosettacode.org/wiki/First_perfect_square_in_base_n_with_n_unique_digits | First perfect square in base n with n unique digits | Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the search space, but the code must do ... | #Python | Python | '''Perfect squares using every digit in a given base.'''
from itertools import count, dropwhile, repeat
from math import ceil, sqrt
from time import time
# allDigitSquare :: Int -> Int -> Int
def allDigitSquare(base, above):
'''The lowest perfect square which
requires all digits in the given base.
... | Give a code snippet in #Python
Find the first perfect square in a given base N that has at least N digits and
exactly N significant unique digits when expressed in base N.
E.G. In base 10, the first perfect square with at least 10 unique digits is 1026753849 (32043²).
You may use analytical methods to reduce the sea... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Playing_cards | Playing cards | Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the current contents of a deck
Each card mu... | #Common_Lisp | Common Lisp | (defconstant +suits+
'(club diamond heart spade)
"Card suits are the symbols club, diamond, heart, and spade.")
(defconstant +pips+
'(ace 2 3 4 5 6 7 8 9 10 jack queen king)
"Card pips are the numbers 2 through 10, and the symbols ace, jack,
queen and king.")
(defun make-deck (&aux (deck '()))
"Returns a ... | Give a code snippet in #Common_Lisp
Task
Create a data structure and the associated methods to define and manipulate a deck of playing cards.
The deck should contain 52 unique cards.
The methods must include the ability to:
make a new deck
shuffle (randomize) the deck
deal from the deck
print the cur... | 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... | #Common_Lisp | Common Lisp |
;Calling a function that requires no arguments
(defun a () "This is the 'A' function")
(a)
;Calling a function with a fixed number of arguments
(defun b (x y) (list x y))
(b 1 2)
;Calling a function with optional arguments
(defun c (&optional x y) (list x y))
(c 1)
;Calling a function with a variable number of argume... | Give a code snippet in #Common_Lisp
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 wit... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem | Sailors, coconuts and a monkey problem | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th... | #Haskell | Haskell | import Control.Monad ((>=>))
import Data.Maybe (mapMaybe)
import System.Environment (getArgs)
-- Takes the number of sailors and the final number of coconuts. Returns
-- Just the associated initial number of coconuts and Nothing otherwise.
tryFor :: Int -> Int -> Maybe Int
tryFor s = foldr (>=>) pure $ replicate s st... | Give a code snippet in #Haskell
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, s... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedi... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 9 С/П ПП 28 пи * cos x<0 16 ИП2
ПП 28 1 - БП 51 ИП7 ПП 28 ИП7
ПП 28 КИП2 ИП2 ВП 4 4 С/П 1 -
x=0 33 8 П2 С/П П7 ИП2 4 - x#0
43 x<0 45 8 + П8 ИП7 - x#0 55
ИП8 ВП 6 6 С/П ИП2 В/О | Give a code snippet in #.D0.9C.D0.9A-61.2F52
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See als... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Binary_search | Binary search | A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p... | #Erlang | Erlang | %% Task: Binary Search algorithm
%% Author: Abhay Jain
-module(searching_algorithm).
-export([start/0]).
start() ->
List = [1,2,3],
binary_search(List, 5, 1, length(List)).
binary_search(List, Value, Low, High) ->
if Low > High ->
io:format("Number ~p not found~n", [Value]),
not_foun... | Give a code snippet in #Erlang
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm.
As an analogy, consider the children's game "guess a number." The scorer has a secret ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/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... | #QBasic | QBasic | FUNCTION Copialo$ (txt$, siNo, final$)
DIM nuevaCadena$
FOR cont = 1 TO siNo
nuevaCadena$ = nuevaCadena$ + txt$
NEXT cont
Copialo$ = LTRIM$(RTRIM$(nuevaCadena$)) + final$
END FUNCTION
SUB Saludo
PRINT "Hola mundo!"
END SUB
SUB testCadenas (txt$)
FOR cont = 1 TO LEN(txt$)
PRINT MID$(txt... | Give a code snippet in #QBasic
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/Zeckendorf_arithmetic | Zeckendorf arithmetic | This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions.
Addition
Like bin... | #Raku | Raku | addition: +z
subtraction: -z
multiplication: *z
division: /z (more of a divmod really)
post increment: ++z
post decrement: --z
| Give a code snippet in #Raku
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation.
The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation... | christopher/rosetta-code | |
http://rosettacode.org/wiki/SEDOLs | SEDOLs | Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0YBKT7
B000300
Extra credit
... | #J | J | sn =. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ac0 =: (, 10 | 1 3 1 7 3 9 +/@:* -)&.(sn i. |:) | Give a code snippet in #J
Task
For each number list of 6-digit SEDOLs, calculate and append the checksum digit.
That is, given this input:
710889
B0YBKJ
406566
B0YBLH
228276
B0YBKL
557910
B0YBKR
585284
B0YBKT
B00030
Produce this output:
7108899
B0YBKJ7
4065663
B0YBLH2
2282765
B0YBKL9
5579107
B0YBKR5
5852842
B0Y... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
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 | import java.util.Arrays;
import java.util.Comparator;
public class SortComp {
public static class Pair {
public String name;
public String value;
public Pair(String n, String v) {
name = n;
value = v;
}
}
public static void main(String[] args) {
... | 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/Find_the_intersection_of_two_lines | Find the intersection of two lines | [1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| #Rust | Rust | #[derive(Copy, Clone, Debug)]
struct Point {
x: f64,
y: f64,
}
impl Point {
pub fn new(x: f64, y: f64) -> Self {
Point { x, y }
}
}
#[derive(Copy, Clone, Debug)]
struct Line(Point, Point);
impl Line {
pub fn intersect(self, other: Self) -> Option<Point> {
let a1 = self.1.y - se... | Give a code snippet in #Rust
[1]
Task
Find the point of intersection of two lines in 2D.
The 1st line passes though (4,0) and (6,10) .
The 2nd line passes though (0,3) and (10,7) .
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Scilab | Scilab | A = [1 3 -5]
B = [4 -2 -1]
C = sum(A.*B) | Give a code snippet in #Scilab
Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Best_shuffle | Best shuffle | Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative... | #Tcl | Tcl | package require Tcl 8.5
package require struct::list
# Simple metric function; assumes non-empty lists
proc count {l1 l2} {
foreach a $l1 b $l2 {incr total [string equal $a $b]}
return $total
}
# Find the best shuffling of the string
proc bestshuffle {str} {
set origin [split $str ""]
set best $origin... | Give a code snippet in #Tcl
Task
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be d... | #C.2B.2B | C++ | #include <iostream>
class T
{
public:
virtual void identify() { std::cout << "I am a genuine T" << std::endl; }
virtual T* clone() { return new T(*this); }
virtual ~T() {}
};
class S: public T
{
public:
virtual void identify() { std::cout << "I am an S" << std::endl; }
virtual S* clone() { return new S(*t... | Give a code snippet in #C.2B.2B
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x we... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #Swift | Swift | import Darwin
M_E // e
M_PI // pi
sqrt(x) // square root--cube root also available (cbrt)
log(x) // natural logarithm--log base 10 also available (log10)
exp(x) // exponential
abs(x) // absolute value
floor(x) // floor
ceil(x) // ceiling
pow(x,y) // power | Give a code snippet in #Swift
Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "m... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
... | #SuperCollider | SuperCollider | (
var text, words, sorted, dict = IdentityDictionary.new, findMax;
File.use("unixdict.txt".resolveRelative, "r", { |f| text = f.readAllString });
words = text.split(Char.nl);
sorted = words.collect { |each|
var key = each.copy.sort.asSymbol;
dict[key] ?? { dict[key] = [] };
dict[key] = dict[key].add(each)
};
findMax... | Give a code snippet in #SuperCollider
When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most wo... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Unicode_variable_names | Unicode variable names | Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
Case-sensitivity of identif... | #Ada | Ada | with Ada.Text_IO;
procedure main is
Δ : Integer;
begin
Δ := 41;
Δ := Δ + 1;
Ada.Text_IO.Put_Line (Δ'Img);
end main; | Give a code snippet in #Ada
Task
Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables.
Show how to:
Set a variable with a name including the 'Δ', (delta character), to 1
Increment it
Print its value.
Related task
... | christopher/rosetta-code | |
http://rosettacode.org/wiki/ASCII_art_diagram_converter | ASCII art diagram converter | Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:
http://www.ietf.org/rfc/rfc1035.txt
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RC... | #D | D | string makeStructFromDiagram(in string rawDiagram) pure @safe {
import std.conv: text;
import std.format: format;
import std.string: strip, splitLines, indexOf;
import std.array: empty, popFront;
static void commitCurrent(ref uint anonCount,
ref uint totalBits,
... | Give a code snippet in #D
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:
http://www.ietf.org/rfc/rfc1035.txt
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #AutoHotkey | AutoHotkey | repeat("fMsgBox",3)
return
repeat(f, n){
loop % n
%f%()
}
fMsgBox(){
MsgBox hello
} | Give a code snippet in #AutoHotkey
Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Factor | Factor | USING: formatting locals ;
IN: scratchpad
[let
"Benjamin" :> dog
"Samba" :> Dog
"Bernie" :> DOG
{ dog Dog DOG } "There are three dogs named %s, %s, and %s." vprintf
] | Give a code snippet in #Factor
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, S... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Jump_anywhere | Jump anywhere | Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different... | #Delphi | Delphi |
var
x: Integer = 5;
label
positive, negative, both;
begin
if (x > 0) then
goto positive
else
goto negative;
positive:
writeln('pos');
goto both;
negative:
writeln('neg');
both:
readln;
end.
| Give a code snippet in #Delphi
Imperative programs
conditional structures
loops
local jumps
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom ... | 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... | #Perl | Perl | package Trit;
# -1 = false ; 0 = maybe ; 1 = true
use Exporter 'import';
our @EXPORT_OK = qw(TRUE FALSE MAYBE is_true is_false is_maybe);
our %EXPORT_TAGS = (
all => \@EXPORT_OK,
const => [qw(TRUE FALSE MAYBE)],
bool => [qw(is_true is_false is_maybe)],
);
use List::Util qw(min max);
use overload
'=' => su... | Give a code snippet in #Perl
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/Count_the_coins | Count the coins | There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 pennies
A nickel and 10 pen... | #11l | 11l | F changes(amount, coins)
V ways = [Int64(0)] * (amount + 1)
ways[0] = 1
L(coin) coins
L(j) coin .. amount
ways[j] += ways[j - coin]
R ways[amount]
print(changes(100, [1, 5, 10, 25]))
print(changes(100000, [1, 5, 10, 25, 50, 100])) | Give a code snippet in #11l
There are four types of common coins in US currency:
quarters (25 cents)
dimes (10 cents)
nickels (5 cents), and
pennies (1 cent)
There are six ways to make change for 15 cents:
A dime and a nickel
A dime and 5 pennies
3 nickels
2 nickels and 5 p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Flipping_bits_game | Flipping bits game | The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one move).
In an inversion. any 1 ... | #C.2B.2B | C++ |
#include <time.h>
#include <iostream>
#include <string>
typedef unsigned char byte;
using namespace std;
class flip
{
public:
flip() { field = 0; target = 0; }
void play( int w, int h ) { wid = w; hei = h; createField(); gameLoop(); }
private:
void gameLoop()
{
int moves = 0;
while( !solved() ... | Give a code snippet in #C.2B.2B
The game
Given an N×N square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.
The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once (as one m... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter | Compiler/virtual machine interpreter | A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should read input from a file and/or stdin, an... | #Go | Go | package main
import (
"bufio"
"encoding/binary"
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
)
type code = byte
const (
fetch code = iota
store
push
add
sub
mul
div
mod
lt
gt
le
ge
eq
ne
and
or
neg
not
jmp
... | Give a code snippet in #Go
A virtual machine implements a computer in software.
Task[edit]
Write a virtual machine interpreter. This interpreter should be able to run virtual
assembly language programs created via the task. This is a
byte-coded, 32-bit word stack based virtual machine.
The program should read input ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Look-and-say_sequence | Look-and-say sequence | The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, 11, 21, 1211, 11122... | #R | R | look.and.say <- function(x, return.an.int=FALSE)
{
#convert number to character vector
xstr <- unlist(strsplit(as.character(x), ""))
#get run length encoding
rlex <- rle(xstr)
#form new string
odds <- as.character(rlex$lengths)
evens <- rlex$values
newstr <- as.vector(rbind(odds, evens))
#... | Give a code snippet in #R
The Look and say sequence is a recursively defined sequence of numbers studied most notably by John Conway.
The look-and-say sequence is also known as the Morris Number Sequence, after cryptographer Robert Morris, and the puzzle What is the next number in the sequence 1, ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Modula-2 | Modula-2 | MODULE Towers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
PROCEDURE Move(n,from,to,via : INTEGER);
VAR buf : ARRAY[0..63] OF CHAR;
BEGIN
IF n>0 THEN
Move(n-1, from, via, to);
FormatString("Move disk %i from pole %i to pole %i\n", buf, n, from, to);
Wr... | Give a code snippet in #Modula-2
Task
Solve the Towers of Hanoi problem with recursion.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Primorial_numbers | Primorial numbers | Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
primorial(4) = 210 (2×3×5×... | #Pascal | Pascal | {$H+}
uses
sysutils,mp_types,mp_base,mp_prime,mp_numth;
var
x: mp_int;
t0,t1: TDateTime;
s: AnsiString;
var
i,cnt : NativeInt;
ctx :TPrimeContext;
begin
mp_init(x);
cnt := 1;
i := 2;
FindFirstPrime32(i,ctx);
i := 10;
t0 := time;
repeat
repeat
FindNextPrime32(ctx);
inc(cnt);
... | Give a code snippet in #Pascal
Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
primorial(0) = 1 (by definition)
primorial(1) = 2 (2)
primorial(2) = 6 (2×3)
primorial(3) = 30 (2×3×5)
prim... | 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 ... | #Prolog | Prolog |
% Prolog implementation: SWI-Prolog 7.2.3
replace([_|T], 0, E, [E|T]) :- !.
replace([H|T], N, E, Xs) :-
succ(N1, N), replace(T, N1, E, Xs1), Xs = [H|Xs1].
% True if Xs is the Original grid with the element at (X, Y) replaces by E.
replace_in([H|T], (0, Y), E, Xs) :- replace(H, Y, E, NH), Xs = [NH|T], !.
r... | Give a code snippet in #Prolog
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 1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third... | #Gambas | Gambas | Public Sub Main()
Dim bDoor As New Boolean[101]
Dim siCount1, siCount2, siStart As Short
For siCount1 = 1 To 100
Inc siStart
For siCount2 = siStart To 100 Step siCount1
bDoor[siCount2] = Not bDoor[siCount2]
Next
Next
For siCount1 = 1 To 100
If bDoor[siCount1] Then Print siCount1;;
Next
End | Give a code snippet in #Gambas
There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, .... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_occurrences_of_a_substring | Count occurrences of a substring | Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched for.
It should return an integer cou... | #CoffeeScript | CoffeeScript |
countSubstring = (str, substr) ->
n = 0
i = 0
while (pos = str.indexOf(substr, i)) != -1
n += 1
i = pos + substr.length
n
console.log countSubstring "the three truths", "th"
console.log countSubstring "ababababab", "abab"
| Give a code snippet in #CoffeeScript
Task
Create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
The function should take two arguments:
the first argument being the string to search, and
the second a substring to be searched f... | 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,... | #ActionScript | ActionScript | //creates an array of length 10
var array1:Array = new Array(10);
//creates an array with the values 1, 2
var array2:Array = new Array(1,2);
//arrays can also be set using array literals
var array3:Array = ["foo", "bar"];
//to resize an array, modify the length property
array2.length = 3;
//arrays can contain objects o... | Give a code snippet in #ActionScript
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, an... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pierpont_primes | Pierpont primes | A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the first definition, but will be c... | #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
pierpont = []
limit1 = 18
limit2 = 8505000
limit3 = 50
limit4 = 21
limit5 = 30500000
for n = 0 to limit1
for m = 0 to limit1
num = pow(2,n)*pow(3,m) + 1
if isprime(num) and num < limit2
add(pierpont,num)
ok
if num > limit2
... | Give a code snippet in #Ring
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v .
A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v .
The term "Pierpont primes" is generally understood to mean the f... | christopher/rosetta-code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.