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/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a st... | #Raku | Raku | my $str = "Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!";
# comment... | Give a code snippet in #Raku
Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Cre... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Common_Lisp | Common Lisp | (format t "Hello world!~%") | Give a code snippet in #Common_Lisp
Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard e... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pi | Pi |
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning 3.14159265 ...... | #Racket | Racket |
#lang racket
(require racket/generator)
(define pidig
(generator ()
(let loop ([q 1] [r 0] [t 1] [k 1] [n 3] [l 3])
(if (< (- (+ r (* 4 q)) t) (* n t))
(begin (yield n)
(loop (* q 10) (* 10 (- r (* n t))) t k
(- (quotient (* 10 (+ (* 3 q) r)) t) (* 10 n))
... | Give a code snippet in #Racket
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal seq... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_program | Empty program | Task
Create the simplest possible program that is still considered "correct."
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | С/П | Give a code snippet in #.D0.9C.D0.9A-61.2F52
Task
Create the simplest possible program that is still considered "correct."
| christopher/rosetta-code | |
http://rosettacode.org/wiki/User_input/Text | User input/Text | User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| #Euphoria | Euphoria | include get.e
sequence s
atom n
s = prompt_string("Enter a string:")
puts(1, s & '\n')
n = prompt_number("Enter a number:",{})
printf(1, "%d", n) | Give a code snippet in #Euphoria
User input/Text is part of Short Circuit's Console Program Basics selection.
Task
Input a string and the integer 75000 from the text console.
See also: User input/Graphical
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Factorions | Factorions |
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1,499,999.
Task
Write a progr... | #Python | Python | fact = [1] # cache factorials from 0 to 11
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
... | Give a code snippet in #Python
Definition
A factorion is a natural number that equals the sum of the factorials of its digits.
Example
145 is a factorion in base 10 because:
1! + 4! + 5! = 1 + 24 + 120 = 145
It can be shown (see talk page) that no factorion in base 10 can exceed 1... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
... | #Delphi | Delphi | program Optional_parameters;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TRow = TArray<string>;
TOrderingFun = TFunc<TRow, TRow, Boolean>;
TTable = array of TRow;
TRowHelper = record helper for TRow
public
procedure Swap(var other: TRow);
function ToString: string;
function Length:... | Give a code snippet in #Delphi
Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; le... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Bitwise_operations | Bitwise operations |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #BBC_BASIC | BBC BASIC | number1% = &89ABCDEF
number2% = 8
PRINT ~ number1% AND number2% : REM bitwise AND
PRINT ~ number1% OR number2% : REM bitwise OR
PRINT ~ number1% EOR number2% : REM bitwise exclusive-OR
PRINT ~ NOT number1% : REM bitwise NOT
PRINT ~ number1% << number2% : REM left s... | Give a code snippet in #BBC_BASIC
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operati... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Higher-order_functions | Higher-order functions | Task
Pass a function as an argument to another function.
Related task
First-class functions
| #Order | Order |
#include <order/interpreter.h>
#define ORDER_PP_DEF_8func1 ORDER_PP_FN ( \
8fn(8F, \
8ap(8F, 8("a string")) ))
#define ORDER_PP_DEF_8func2 ORDER_PP_FN ( \
8fn(8S, \
8adjoin(8("func2 called with "), 8S ) ))
ORDER_PP(
8func1(8func2)
)
// -> "func2 called with ""a string"
#define ORDER_PP_DEF_8func3 OR... | Give a code snippet in #Order
Task
Pass a function as an argument to another function.
Related task
First-class functions
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Globally_replace_text_in_several_files | Globally replace text in several files | Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
| #Fortran | Fortran | SUBROUTINE FILEHACK(FNAME,THIS,THAT) !Attacks a file!
CHARACTER*(*) FNAME !The name of the file, presumed to contain text.
CHARACTER*(*) THIS !The text sought in each record.
CHARACTER*(*) THAT !Its replacement, should it be found.
INTEGER F,T !Mnemonics for file unit numbers.
... | Give a code snippet in #Fortran
Task
Replace every occurring instance of a piece of text in a group of text files with another one.
For this task we want to replace the text "Goodbye London!" with "Hello New York!" for a list of files.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Nested_templated_data | Nested templated data | A template for data is an arbitrarily nested tree of integer indices.
Data payloads are given as a separate mapping, array or other simpler, flat,
association of indices to individual items of data, and are strings.
The idea is to create a data structure with the templates' nesting, and the
payload corresponding to e... | #REXX | REXX | /* REXX */
tok.=''
Do i=0 To 6
tok.i="'Payload#"i"'"
End
t1='[[[1,2],[3,4,1],5]]'
t2='[[[1,6],[3,4,7,0],5]]'
Call transform t1
Call transform t2
Exit
transform:
Parse Arg t 1 tt
/* http://rosettacode.org/wiki/Nested_templated_data */
/*
[[['Payload#1', 'Payload#2'],
['Payload#3', 'Payload#4', 'Payload#1'],
'P... | Give a code snippet in #REXX
A template for data is an arbitrarily nested tree of integer indices.
Data payloads are given as a separate mapping, array or other simpler, flat,
association of indices to individual items of data, and are strings.
The idea is to create a data structure with the templates' nesting, and ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Convex_hull | Convex hull | Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-... | #Visual_Basic_.NET | Visual Basic .NET | Imports ConvexHull
Module Module1
Class Point : Implements IComparable(Of Point)
Public Property X As Integer
Public Property Y As Integer
Public Sub New(x As Integer, y As Integer)
Me.X = x
Me.Y = y
End Sub
Public Function CompareTo(other As P... | Give a code snippet in #Visual_Basic_.NET
Find the points which form a convex hull from a set of arbitrary two dimensional points.
For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Create_an_HTML_table | Create an HTML table | Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
The... | #J | J | ele=:4 :0
nm=. x-.LF
lf=. x-.nm
;('<',nm,'>') ,L:0 y ,L:0 '</',nm,'>',lf
)
hTbl=:4 :0
rows=. 'td' <@ele"1 ":&.>y
'table' ele ('tr',LF) <@ele ('th' ele x); rows
) | Give a code snippet in #J
Create an HTML table.
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with se... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The ba... | #VBScript | VBScript | class stack
dim tos
dim stack()
dim stacksize
private sub class_initialize
stacksize = 100
redim stack( stacksize )
tos = 0
end sub
public sub push( x )
stack(tos) = x
tos = tos + 1
end sub
public property get stackempty
stackempty = ( tos = 0 )
end property
public property get stackfull
... | Give a code snippet in #VBScript
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Humble_numbers | Humble numbers | Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above is:
humble = 2i × 3j × 5k... | #Raku | Raku | sub smooth-numbers (*@list) {
cache my \Smooth := gather {
my %i = (flat @list) Z=> (Smooth.iterator for ^@list);
my %n = (flat @list) Z=> 1 xx *;
loop {
take my $n := %n{*}.min;
for @list -> \k {
%n{k} = %i{k}.pull-one * k if %n{k} == $n;
... | Give a code snippet in #Raku
Humble numbers are positive integers which have no prime factors > 7.
Humble numbers are also called 7-smooth numbers, and sometimes called highly composite,
although this conflicts with another meaning of highly composite numbers.
Another way to express the above ... | 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)
... | #F.23 | F# | // ISBN13 Check Digit
open System
let parseInput (input: string) =
Seq.map(fun c -> c |> string) input |> Seq.toList |> List.map(fun x -> Int32.Parse x)
[<EntryPoint>]
let main argv =
let isbnnum = parseInput (String.filter (fun x -> x <> '-') argv.[0])
// Multiply every other digit by 3
let everyOt... | Give a code snippet in #F.23
Task
Validate the check digit of an ISBN-13 code:
Multiply every other digit by 3.
Add these numbers and the other digits.
Take the remainder of this number after division by 10.
If it is 0, the ISBN-13 check digit is correct.
Use the following codes for testing:
9... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Letter_frequency | Letter frequency | Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequen... | #OxygenBasic | OxygenBasic |
indexbase 0
sys a,e,i,c[255]
string s=getfile "t.txt"
e=len s
for i=1 to e
a=asc(s,i)
++c(a)
next
cr=chr(13)+chr(10)
pr="Char Frequencies" cr cr
for i=32 to 255
pr+=chr(i) chr(9) c(i) cr
next
print pr
'putfile "CharCount.txt",pr
| Give a code snippet in #OxygenBasic
Task
Open a text file and count the occurrences of each letter.
Some of these programs count all characters (including punctuation),
but some only count letters A to Z.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Lah_numbers | Lah numbers | Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets.
Lah numbers a... | #R | R | Lah_numbers <- function(n, k, type = "unsigned") {
if (n == k)
return(1)
if (n == 0 | k == 0)
return(0)
if (k == 1)
return(factorial(n))
if (k > n)
return(NA)
if (type == "unsigned")
return((factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 1)) ... | Give a code snippet in #R
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly orde... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #OCaml | OCaml | (*
* Caution: This is my first Ocaml program and anyone with Ocaml experience probably thinks it's horrible
* So please don't use this as an example for "good ocaml code" see it more as
* "this is what my first lines of ocaml might look like"
*
* The only reason im publishing this is th... | Give a code snippet in #OCaml
There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (di... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Empty_string | Empty string | Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
Other tasks related to string oper... | #Zoomscript | Zoomscript | var string
string = ""
if eq string ""
print "The string is empty."
else
print "The string is not empty."
endif | Give a code snippet in #Zoomscript
Languages may have features for dealing specifically with empty strings
(those containing no characters).
Task
Demonstrate how to assign an empty string to a variable.
Demonstrate how to check that a string is empty.
Demonstrate how to check that a string is not empty.
... | 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 .
| #Icon_and_Unicon | Icon and Unicon | link graphics
procedure main()
width := 750
height := 600
limit := 100
WOpen("size="||width||","||height)
every x:=1 to width & y:=1 to height do
{
z:=complex(0,0)
c:=complex(2.5*x/width-2.0,(2.0*y/height-1.0))
j:=0
while j<limit & cAbs(z)<2.0 do
{
... | Give a code snippet in #Icon_and_Unicon
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/IBAN | IBAN |
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The International Bank Account Number (IBAN) is an internationally agree... | #Java | Java | import java.math.BigInteger;
import java.util.*;
public class IBAN {
private static final String DEFSTRS = ""
+ "AL28 AD24 AT20 AZ28 BE16 BH22 BA20 BR29 BG22 "
+ "HR21 CY28 CZ24 DK18 DO28 EE20 FO18 FI18 FR27 GE22 DE22 GI23 "
+ "GL18 GT28 HU28 IS26 IE22 IL23 IT27 KZ20 KW30 LV21 ... | Give a code snippet in #Java
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The International Bank Account Number (IBAN)... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Prolog | Prolog |
:- initialization(main).
main :-
current_prolog_flag(argv, [File|_]),
read_file_to_string(File, String, []).
| Give a code snippet in #Prolog
Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incr... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or pow... | #Sidef | Sidef | var arr = %w(a b c)
for i in (0 .. arr.len) {
say arr.combinations(i)
} | Give a code snippet in #Sidef
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #C.23 | C# | public static int[,] ZigZag(int n)
{
int[,] result = new int[n, n];
int i = 0, j = 0;
int d = -1; // -1 for top-right move, +1 for bottom-left move
int start = 0, end = n * n - 1;
do
{
result[i, j] = start++;
result[n - i - 1, n - j - 1] = end--;
i += d; j -= d;
... | Give a code snippet in #C.23
Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to enco... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Conway%27s_Game_of_Life | Conway's Game of Life | The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, in an m-by-m (or m×m) sq... | #Delphi | Delphi |
program game_of_life;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Velthuis.Console; // CrlScr
type
TBoolMatrix = TArray<TArray<Boolean>>;
TField = record
s: TBoolMatrix;
w, h: Integer;
procedure SetValue(x, y: Integer; b: boolean);
function Next(x, y: Integer): boolean;
function S... | Give a code snippet in #Delphi
The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is the best-known example of a cellular automaton.
Conway's game of life is described here:
A cell C is represented by a 1 when alive, or 0 when dead, ... | 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... | #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
DEFINE PTR="CARD"
PTR ARRAY num(12),obj(12)
BYTE i,j
num(0)="first" num(1)="second" num(2)="third"
num(3)="fourth" num(4)="fifth" num(5)="sixth"
num(6)="seventh" num(7)="eight" num(8)="ninth"
num(... | Give a code snippet in #Action.21
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 opera... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the ... | #Go | Go | package main
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
)
const (
filename = "mlijobs.txt"
inoutField = 1
timeField = 3
numFields = 7
)
func main() {
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
var ml, out in... | Give a code snippet in #Go
A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checko... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Random_numbers | Random numbers | Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Related task
Standard deviation
| #Kotlin | Kotlin | // version 1.0.6
import java.util.Random
fun main(args: Array<String>) {
val r = Random()
val da = DoubleArray(1000)
for (i in 0 until 1000) da[i] = 1.0 + 0.5 * r.nextGaussian()
// now check actual mean and SD
val mean = da.average()
val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.a... | Give a code snippet in #Kotlin
Task
Generate a collection filled with 1000 normally distributed random (or pseudo-random) numbers
with a mean of 1.0 and a standard deviation of 0.5
Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms.
Relate... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Balanced_ternary | Balanced ternary | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0"
... | #Nim | Nim | import strformat
import tables
type
# Trit definition.
Trit = range[-1'i8..1'i8]
# Balanced ternary number as a sequence of trits stored in little endian way.
BTernary = seq[Trit]
const
# Textual representation of trits.
Trits: array[Trit, char] = ['-', '0', '+']
# Symbolic names used for trit... | Give a code snippet in #Nim
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1.
Examples
Decimal 11 = 32 + 31 − 30, thus it can be written as "++−"
Decimal 6 = 32 − 31 + 0 × 30, thu... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Memory_allocation | Memory allocation | Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| #BBC_BASIC | BBC BASIC | size% = 12345
DIM mem% size%-1
PRINT ; size% " bytes of heap allocated at " ; mem% | Give a code snippet in #BBC_BASIC
Task
Show how to explicitly allocate and deallocate blocks of memory in your language.
Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Van_der_Corput_sequence | Van der Corput sequence | When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\displaystyle 2^{1}}
; and so o... | #ERRE | ERRE | PROGRAM VAN_DER_CORPUT
!
! for rosettacode.org
!
PROCEDURE VDC(N%,B%->RES)
LOCAL V,S%
S%=1
WHILE N%>0 DO
S%*=B%
V+=(N% MOD B%)/S%
N%=N% DIV B%
END WHILE
RES=V
END PROCEDURE
BEGIN
FOR BASE%=2 TO 5 DO
PRINT("Base";STR$(BASE%);":")
FOR NUMBE... | Give a code snippet in #ERRE
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of
2
0
{\displaystyle 2^{0}}
; the digit in the next column to the left has a multiplier of
2
1
{\d... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Word_wrap | Word wrap | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, sho... | #Phix | Phix | string s = substitute("""In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful that the sun itself,
which has seen so much, was astonished whenever it shone in her face. Close by the king's
castle lay a great dark forest, and under an old ... | Give a code snippet in #Phix
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
Basic task
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provi... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Ada | Ada | with Ada.Command_Line, Ada.Text_IO, Ada.Strings.Fixed;
procedure Rep_String is
function Find_Largest_Rep_String(S:String) return String is
L: Natural := S'Length;
begin
for I in reverse 1 .. L/2 loop
declare
use Ada.Strings.Fixed;
T: String := S(S'First .. S'First + I-1); -- the first ... | Give a code snippet in #Ada
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least ... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sum_of_squares | Sum of squares | Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| #Octave | Octave | a = [1:10];
sumsq = sum(a .^ 2); | Give a code snippet in #Octave
Task
Write a program to find the sum of squares of a numeric vector.
The program should work on a zero-length vector (with an answer of 0).
Related task
Mean
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Raku | Raku | use NativeCall;
sub XOpenDisplay(Str $s --> int64) is native('X11') {*}
sub XCloseDisplay(int64 $i --> int32) is native('X11') {*}
if try my $d = XOpenDisplay ":0.0" {
say "ID = $d";
XCloseDisplay($d);
}
else {
say "No X11 library!";
say "Use this window instead --> ⬜";
} | Give a code snippet in #Raku
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Knuth_shuffle | Knuth shuffle | The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from 0 to last, the algorithm can be d... | #ALGOL_68 | ALGOL 68 | PROC between = (INT a, b)INT :
(
ENTIER (random * ABS (b-a+1) + (a<b|a|b))
);
PROC knuth shuffle = (REF[]INT a)VOID:
(
FOR i FROM LWB a TO UPB a DO
INT j = between(LWB a, UPB a);
INT t = a[i];
a[i] := a[j];
a[j] := t
OD
); | Give a code snippet in #ALGOL_68
The Knuth shuffle (a.k.a. the Fisher-Yates shuffle) is an algorithm for randomly shuffling the elements of an array.
Task
Implement the Knuth shuffle for an integer array (or, if possible, an array of any type).
Specification
Given an array items with indices ranging from... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Rust | Rust | const EPSILON: f64 = 1e-15;
fn main() {
let mut fact: u64 = 1;
let mut e: f64 = 2.0;
let mut n: u64 = 2;
loop {
let e0 = e;
fact *= n;
n += 1;
e += 1.0 / fact as f64;
if (e - e0).abs() < EPSILON {
break;
}
}
println!("e = {:.15}", e);... | Give a code snippet in #Rust
Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Count_in_factors | Count in factors | Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it would be shown as
2
×
3
{\di... | #Pascal | Pascal | program CountInFactors(output);
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
type
TdynArray = array of integer;
function factorize(number: integer): TdynArray;
var
k: integer;
begin
if number = 1 then
begin
setlength(Result, 1);
Result[0] := 1
end
else
begin
k := 2;
while number > 1 do
... | Give a code snippet in #Pascal
Task
Write a program which counts up from 1, displaying each number as the multiplication of its prime factors.
For the purpose of this task, 1 (unity) may be shown as itself.
Example
2 is prime, so it would be shown as itself.
6 is not prime; it woul... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Permutations | Permutations | Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations generation tasks.
Order Uni... | #VBA | VBA | Public Sub Permute(n As Integer, Optional printem As Boolean = True)
'Generate, count and print (if printem is not false) all permutations of first n integers
Dim P() As Integer
Dim t As Integer, i As Integer, j As Integer, k As Integer
Dim count As Long
Dim Last As Boolean
If n <= 1 Then
Debug.Print "Please gi... | Give a code snippet in #VBA
Task
Write a program that generates all permutations of n different objects. (Practically numerals!)
Related tasks
Find the missing permutation
Permutations/Derangements
The number of samples of size k from n objects.
With combinations and permutations genera... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Sexy_primes | Sexy primes |
This page uses content from Wikipedia. The original article was at Sexy_prime. 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 mathematics, sexy primes are prime numbers that differ from each ot... | #C.2B.2B | C++ | #include <array>
#include <iostream>
#include <vector>
#include <boost/circular_buffer.hpp>
#include "prime_sieve.hpp"
int main() {
using std::cout;
using std::vector;
using boost::circular_buffer;
using group_buffer = circular_buffer<vector<int>>;
const int max = 1000035;
const int max_grou... | Give a code snippet in #C.2B.2B
This page uses content from Wikipedia. The original article was at Sexy_prime. 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 mathematics, sexy primes are prime... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Pythagoras_tree | Pythagoras tree |
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or ... | #BASIC256 | BASIC256 |
Subroutine pythagoras_tree(x1, y1, x2, y2, depth)
If depth > 10 Then Return
dx = x2 - x1 : dy = y1 - y2
x3 = x2 - dy : y3 = y2 - dx
x4 = x1 - dy : y4 = y1 - dx
x5 = x4 + (dx - dy) / 2
y5 = y4 - (dx + dy) / 2
#draw the box
Line x1, y1, x2, y2 : Line x2, y2, x3, y3
Line x3, y3, x4, y4 : Line x4, y4, x1, y1
... | Give a code snippet in #BASIC256
The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem.
Task
Construct a Pythagoras tree of order 7 u... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hello_world/Newline_omission | Hello world/Newline omission | Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Standard error
Hello world/Text
| #EchoLisp | EchoLisp |
(begin
(write "GoodBye, World")
(write "Next on same line"))
| Give a code snippet in #EchoLisp
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output.
Task
Display the string Goodbye, World! without a trailing newline.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/St... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration | Convert seconds to compound duration | Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed below (e.g., "2 hr, 59 sec").
Demonstrat... | #Applesoft_BASIC | Applesoft BASIC | 100 DATA604800,WK,86400,D,3600,HR,60,MIN,1,SEC
110 FOR I = 0 TO 4
120 READ M(I), U$(I)
130 NEXT
140 DATA7259,86400,6000000
150 ON ERR GOTO 270
160 READ S
170 GOSUB 200
180 PRINT S " = " S$
190 GOTO 160
200 N = S
210 S$ = ""
220 FOR I = 0 TO 4
230 IF INT(N / M(I)) THEN S$ = S$ + MID$(", ", 1, (LEN(... | Give a code snippet in #Applesoft_BASIC
Task
Write a function or program which:
takes a positive integer representing a duration in seconds as input (e.g., 100), and
returns a string which shows the same duration decomposed into:
weeks,
days,
hours,
minutes, and
seconds.
This is detailed be... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Compare_a_list_of_strings | Compare a list of strings | Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false value, which could be used as t... | #Prolog | Prolog | los(["AA","BB","CC"]).
los(["AA","AA","AA"]).
los(["AA","CC","BB"]).
los(["AA","ACB","BB","CC"]).
los(["single_element"]).
lexically_equal(S,S,S).
in_order(G,L,G) :- compare(<,L,G).
test_list(List) :-
List = [L|T],
write('for list '), write(List), nl,
(foldl(lexically_equal, T, L, _)
-> writel... | Give a code snippet in #Prolog
Task
Given a list of arbitrarily many strings, show how to:
test if they are all lexically equal
test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)
Each of those two tests should result in a single true or false... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Hash_from_two_arrays | Hash from two arrays | Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| #Picat | Picat | go =>
A = [a,b,c,d,e],
B = [1,2,3,4,5],
Map = new_map([K=V : {K,V} in zip(A,B)]),
println(Map). | Give a code snippet in #Picat
Task
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
Related task
Associative arrays/Creation
| christopher/rosetta-code | |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
... | #Elena | Elena | import extensions;
public program()
{
int sleep := console.readLine().toInt();
console.printLine("Sleeping...");
system'threading'threadControl.sleep(sleep);
console.printLine("Awake!")
} | Give a code snippet in #Elena
Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Trav... | #PL.2FI | PL/I |
/* Let H be a pointer to a node in a one-way-linked list. */
/* Insert an element, whose value is given by variable V, following that node. */
allocate node set (Q);
node.p = H; /* The new node now points at the list where we want to insert it. */
node.value = V;
H->p = Q; /* Break the list at H, and point it at ... | Give a code snippet in #PL.2FI
Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definiti... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Concurrent_computing | Concurrent computing | Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
| #Go | Go | package main
import (
"fmt"
"golang.org/x/exp/rand"
"time"
)
func main() {
words := []string{"Enjoy", "Rosetta", "Code"}
seed := uint64(time.Now().UnixNano())
q := make(chan string)
for i, w := range words {
go func(w string, seed uint64) {
r := rand.New(rand.NewSourc... | Give a code snippet in #Go
Task
Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order.
Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your lang... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Zig-zag_matrix | Zig-zag matrix | Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, gi... | #Scala | Scala | def zigzag(n: Int): Array[Array[Int]] = {
val l = for (i <- 0 until n*n) yield (i%n, i/n)
val lSorted = l.sortWith {
case ((x,y), (u,v)) =>
if (x+y == u+v)
if ((x+y) % 2 == 0) x<u else y<v
else x+y < u+v
}
val res = Array.ofDim[Int](n, n)
lSorted.zipWithIndex fo... | Give a code snippet in #Scala
Task
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to enc... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity... | #OCaml | OCaml | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 | Give a code snippet in #OCaml
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of p... | christopher/rosetta-code | |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #C.2B.2B | C++ |
#include <iostream>
#include <string>
#include <fstream>
class cipher {
public:
bool work( std::string e, std::string f, std::string k ) {
if( e.length() < 1 ) return false;
fileBuffer = readFile( f );
if( "" == fileBuffer ) return false;
keyBuffer = readFile( k );
if( ""... | Give a code snippet in #C.2B.2B
Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then ... | christopher/rosetta-code |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 11