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 |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation langu... | #Emacs_Lisp | Emacs Lisp | (defun running-std (items)
(let ((running-sum 0)
(running-len 0)
(running-squared-sum 0)
(result 0))
(dolist (item items)
(setq running-sum (+ running-sum item))
(setq running-len (1+ running-len))
(setq running-squared-sum (+ running-squared-sum (* item item)))
(se... |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Elixir | Elixir | defmodule Test do
def crc32(str) do
IO.puts :erlang.crc32(str) |> Integer.to_string(16)
end
end
Test.crc32("The quick brown fox jumps over the lazy dog") |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Erlang | Erlang |
-module(crc32).
-export([test/0]).
test() ->
io:fwrite("~.16#~n",[erlang:crc32(<<"The quick brown fox jumps over the lazy dog">>)]).
|
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... | #360_Assembly | 360 Assembly | * count the coins 04/09/2015
COINS CSECT
USING COINS,R12
LR R12,R15
L R8,AMOUNT npenny=amount
L R4,AMOUNT
SRDA R4,32
D R4,=F'5'
LR R9,R5 nnickle=amount/5
L R4,AMOUNT
... |
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... | #Ada | Ada | with Ada.Text_IO;
procedure Count_The_Coins is
type Counter_Type is range 0 .. 2**63-1; -- works with gnat
type Coin_List is array(Positive range <>) of Positive;
function Count(Goal: Natural; Coins: Coin_List) return Counter_Type is
Cnt: array(0 .. Goal) of Counter_Type := (0 => 1, others => 0);
... |
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... | #Ada | Ada | with Ada.Strings.Unbounded;
generic
type Item_Type is private;
with function To_String(Item: Item_Type) return String is <>;
with procedure Put(S: String) is <>;
with procedure Put_Line(Line: String) is <>;
package HTML_Table is
subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
function ... |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Julia | Julia | ts = Dates.today()
println("Today's date is:")
println("\t$ts")
println("\t", Dates.format(ts, "E, U dd, yyyy")) |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Kotlin | Kotlin | // version 1.0.6
import java.util.GregorianCalendar
fun main(args: Array<String>) {
val now = GregorianCalendar()
println("%tF".format(now))
println("%tA, %1\$tB %1\$te, %1\$tY".format(now))
} |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #C | C | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int n;
double **elems;
} SquareMatrix;
SquareMatrix init_square_matrix(int n, double elems[n][n]) {
SquareMatrix A = {
.n = n,
.elems = malloc(n * sizeof(double *))
};
for(int i = 0; i < n; ++i) {
A... |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program createDirFic.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall exit Program
.equ WRITE, 4 @ Linux syscall write FILE
.equ MKDIR, 0x27 @ Linux Syscal create directory
.equ CHGDIR, 0xC @ Linux Syscal chang... |
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... | #BBC_BASIC | BBC BASIC | DATA "Character,Speech"
DATA "The multitude,The messiah! Show us the messiah!"
DATA "Brian's mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>"
DATA "The multitude,Who are you?"
DATA "Brian's mother,I'm his mother; that's who!"
DAT... |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #Factor | Factor | USING: csv io.encodings.utf8 kernel math.parser sequences ;
IN: rosetta-code.csv-manipulation
: append-sum ( seq -- seq' )
dup [ string>number ] map-sum number>string suffix ;
: csv-sums ( seq -- seq' )
[ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ;
"example.csv" utf8 [ file>csv csv-sums ] [ csv>f... |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #Forth | Forth | \ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues
\ USAGE:
\ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv
CHAR , CONSTANT SEPARATOR
3 CONSTANT DECIMALS
1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE
: colsum ... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #PHP | PHP | <?php
function lookup($r,$c) {
$table = array(
array(0, 3, 1, 7, 5, 9, 8, 6, 4, 2),
array(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),
array(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),
array(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),
array(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),
array(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Lua | Lua | local primes = {3, 5}
local cutOff = 200
local bigUn = 100000
local chunks = 50
local little = math.floor(bigUn / chunks)
local tn = " cuban prime"
print(string.format("The first %d%ss", cutOff, tn))
local showEach = true
local c = 0
local u = 0
local v = 1
for i=1,10000000000000 do
local found = false
u = u + ... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #Wren | Wren | import "/big" for BigRat
var hamburgers = BigRat.new("4000000000000000")
var milkshakes = BigRat.two
var price1 = BigRat.fromFloat(5.5)
var price2 = BigRat.fromFloat(2.86)
var taxPc = BigRat.fromFloat(0.0765)
var totalPc = BigRat.fromFloat(1.0765)
var totalPreTax = hamburger... |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a qu... | #zkl | zkl | var priceList=Dictionary("hamburger",550, "milkshake",286);
var taxRate=765; // percent*M
const M=0d10_000;
fcn toBucks(n){ "$%,d.%02d".fmt(n.divr(100).xplode()) }
fcn taxIt(n) { d,c:=n.divr(M).apply('*(taxRate)); d + (c+5000)/M; }
fcn calcTab(items){ // (hamburger,15), (milkshake,100) ...
items=vm.arglist;
f... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Raku | Raku | my &negative = &infix:<->.assuming(0);
say negative 1; |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #REXX | REXX | /*REXX program demonstrates a REXX currying method to perform addition. */
say 'add 2 to 3: ' add(2, 3)
say 'add 2 to 3 (curried):' add2(3)
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Ruby | Ruby | require 'time'
d = "March 7 2009 7:30pm EST"
t = Time.parse(d)
puts t.rfc2822
puts t.zone
new = t + 12*3600
puts new.rfc2822
puts new.zone
# another timezone
require 'rubygems'
require 'active_support'
zone = ActiveSupport::TimeZone['Beijing']
remote = zone.at(new)
# or, remote = new.in_time_zone('Beijing')
puts re... |
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 ... | #Maple | Maple | xmas:= proc()
local i, dt;
for i from 2008 to 2121 by 1 do
dt := Date(i, 12, 25);
if (Calendar:-DayOfWeek(dt) = 1) then
print(i);
end if;
end do;
end proc;
xmas(); |
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 ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Reap[If[DateString[{#,12,25},"DayName"]=="Sunday",Sow[#]]&/@Range[2008,2121]][[2,1]] |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #REXX | REXX | /*REXX program validates that the last digit (the check digit) of a CUSIP is valid. */
@.=
parse arg @.1 .
if @.1=='' | @.1=="," then do; @.1= 037833100 /* Apple Incorporated */
@.2= 17275R102 /* Cisco Systems */
... |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #C | C | #include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][u... |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation langu... | #Erlang | Erlang |
-module( standard_deviation ).
-export( [add_sample/2, create/0, destroy/1, get/1, task/0] ).
-compile({no_auto_import,[get/1]}).
add_sample( Pid, N ) -> Pid ! {add, N}.
create() -> erlang:spawn_link( fun() -> loop( [] ) end ).
destroy( Pid ) -> Pid ! stop.
get( Pid ) ->
Pid ! {get, erlang:self()},
rece... |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #F.23 | F# |
module Crc32 =
open System
// Generator polynomial (modulo 2) for the reversed CRC32 algorithm.
let private s_generator = uint32 0xEDB88320
// Generate lookup table
let private lutIntermediate input =
if (input &&& uint32 1) <> uint32 0
then s_generator ^^^ (input >>> 1)
... |
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... | #ALGOL_68 | ALGOL 68 |
#
Rosetta Code "Count the coins"
This is a direct translation of the "naive" Haskell version, using an array
rather than a list. LWB, UPB, and array slicing makes the mapping very simple:
LWB > UPB <=> []
LWB = UPB <=> [x]
a[LWB a] <=> head xs
a[LWB a + 1:] <=> tail xs
#
BEGIN
PROC wa... |
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... | #Agena | Agena | notNumbered := 0; # possible values for html table row numbering
numberedLeft := 1; # " " " " " " "
numberedRight := 2; # " " " " " " "
alignCentre := 0; # possible values for html table column alignment
alignLeft := 1; # " " " " ... |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #langur | langur | var .now = dt//
var .format1 = "2006-01-02"
var .format2 = "Monday, January 2, 2006"
writeln $"\.now:dt.format1;"
writeln $"\.now:dt.format2;" |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Lasso | Lasso |
date('11/10/2007')->format('%Q') // 2007-11-10
date('11/10/2007')->format('EEEE, MMMM d, YYYY') //Saturday, November 10, 2007
|
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #C.23 | C# | using System;
using System.Collections.Generic;
using static System.Linq.Enumerable;
public static class CramersRule
{
public static void Main() {
var equations = new [] {
new [] { 2, -1, 5, 1, -3 },
new [] { 3, 2, 2, -6, -32 },
new [] { 1, 3, 3, -1, -47 },
... |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Arturo | Arturo | output: "output.txt"
docs: "docs"
write output ""
write.directory docs ø
write join.path ["/" output] ""
write.directory join.path ["/" docs] ø |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #AutoHotkey | AutoHotkey | FileAppend,,output.txt
FileCreateDir, docs
FileAppend,,c:\output.txt
FileCreateDir, c:\docs |
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... | #Befunge | Befunge | <v_>#!,#:< "<table>" \0 +55
v >0>::65*1+`\"~"`!*#v_4-5v >
v>#^~^<v"<tr><td>" < \v-1/<>">elb"
<^ >:#,_$10 |!:<>\#v_ vv"ta"
v-",":\-"&":\-"<":\<>5#05#<v+ >"/"v
>#v_$$$0">dt<>dt/<"vv"tr>"+<5 v"<"<
>^>\#v_$$0";pma&" v>"/<>d"v5 v , <
$ > \#v_$0";tl&"v v"</t"<0 > : |
^_>#!,#:<>#<0#<\#<<< >:#,_$#^_v@ $< |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #Fortran | Fortran | program rowsum
implicit none
character(:), allocatable :: line, name, a(:)
character(20) :: fmt
double precision, allocatable :: v(:)
integer :: n, nrow, ncol, i
call get_command_argument(1, length=n)
allocate(character(n) :: name)
call get_command_argument(1, name)
open(unit=10, f... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #PicoLisp | PicoLisp | (setq *D
(quote
(0 3 1 7 5 9 8 6 4 2) ... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #PL.2FM | PL/M | 100H:
/* DAMM CHECKSUM FOR DECIMAL NUMBER IN GIVEN STRING */
CHECK$DAMM: PROCEDURE (PTR) BYTE;
DECLARE PTR ADDRESS, CH BASED PTR BYTE;
DECLARE DAMM DATA
( 0,3,1,7,5,9,8,6,4,2,
7,0,9,2,1,5,4,8,6,3,
4,2,0,6,8,7,1,3,5,9,
1,7,5,0,9,8,3,4,2,6,
6,1,2,3,0,4,5,9,7,8,
... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Maple | Maple | CubanPrimes := proc(n) local i, cp;
cp := Array([]);
for i by 2 while numelems(cp) < n do
if isprime(3/4*i^2 + 1/4) then
ArrayTools:-Append(cp, 3/4*i^2 + 1/4);
end if;
end do;
return cp;
... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | cubans[m_Integer] := Block[{n = 1, result = {}, candidate},
While[Length[result] < m,
n++;
candidate = n^3 - (n - 1)^3;
If[PrimeQ[candidate], AppendTo[result, candidate]]];
result]
cubans[200]
NumberForm[Last[cubans[100000]], NumberSeparator -> ",", DigitBlock -> 3] |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Ruby | Ruby |
b = proc {|x, y, z| (x||0) + (y||0) + (z||0) }
p b.curry[1][2][3] #=> 6
p b.curry[1, 2][3, 4] #=> 6
p b.curry(5)[1][2][3][4][5] #=> 6
p b.curry(5)[1, 2][3, 4][5] #=> 6
p b.curry(1)[1] #=> 1
b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) }
p b.curry[1][2][3] ... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Run_BASIC | Run BASIC | theDate$ = "March 7 2009 7:30pm EST"
monthName$ = "January February March April May June July August September October November December"
for i = 1 to 12
if word$(theDate$,1) = word$(monthName$,i) then monthNum = i ' turn month name to number
next i
d = val(date$(monthNum;"/";word$(theDate$,2);"/";word$(theDate$... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Rust | Rust |
use chrono::prelude::*;
use chrono::Duration;
fn main() {
// Chrono allows parsing time zone abbreviations like "EST", but
// their meaning is ignored due to a lack of standardization.
//
// This solution compromises by augmenting the parsed datetime
// with the timezone using the IANA abbreviat... |
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 ... | #MATLAB_.2F_Octave | MATLAB / Octave | t = datenum([[2008:2121]',repmat([12,25,0,0,0], 2121-2007, 1)]);
t = t(strmatch('Sunday', datestr(t,'dddd')), :);
datestr(t,'yyyy')
|
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Ring | Ring |
# Project : CUSIP
inputstr = list(6)
inputstr[1] = "037833100"
inputstr[2] = "17275R102"
inputstr[3] = "38259P508"
inputstr[4] = "594918104"
inputstr[5] = "68389X106"
inputstr[6] = "68389X105"
for n = 1 to len(inputstr)
cusip(inputstr[n])
next
func cusip(inputstr)
if len(inputstr) != 9
s... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Ruby | Ruby |
#!/usr/bin/env ruby
def check_cusip(cusip)
abort('CUSIP must be 9 characters') if cusip.size != 9
sum = 0
cusip.split('').each_with_index do |char, i|
next if i == cusip.size - 1
case
when char.scan(/\D/).empty?
v = char.to_i
when char.scan(/\D/).any?
pos = char.upcase.ord - 'A'.... |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #C.23 | C# |
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArra... |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation langu... | #Factor | Factor | USING: accessors io kernel math math.functions math.parser
sequences ;
IN: standard-deviator
TUPLE: standard-deviator sum sum^2 n ;
: <standard-deviator> ( -- standard-deviator )
0.0 0.0 0 standard-deviator boa ;
: current-std ( standard-deviator -- std )
[ [ sum^2>> ] [ n>> ] bi / ]
[ [ sum>> ] [ n>>... |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Factor | Factor | IN: scratchpad USING: checksums checksums.crc32 ;
IN: scratchpad "The quick brown fox jumps over the lazy dog" crc32
checksum-bytes hex-string .
"414fa339"
|
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #FBSL | FBSL | #APPTYPE CONSOLE
PRINT HEX(CHECKSUM("The quick brown fox jumps over the lazy dog"))
PAUSE |
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... | #AppleScript | AppleScript | -- All input values must be integers and multiples of the same monetary unit.
on countCoins(amount, denominations)
-- Potentially long list of counters, initialised with 1 (result for amount 0) and 'amount' zeros.
script o
property counters : {1}
end script
repeat amount times
set end of... |
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... | #11l | 11l | print(‘the three truths’.count(‘th’))
print(‘ababababab’.count(‘abab’)) |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #0815 | 0815 | }:l:> Start loop, enqueue Z (initially 0).
}:o: Treat the queue as a stack and
<:8:= accumulate the octal digits
/=>&~ of the current number.
^:o:
<:0:- Get a sentinel negative 1.
&>@ Enqueue it between the digits and the current number.
{ Dequeue the first octal digit.
}:p:
... |
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... | #ALGOL_68 | ALGOL 68 | INT not numbered = 0; # possible values for HTMLTABLE row numbering #
INT numbered left = 1; # " " " " " " #
INT numbered right = 2; # " " " " " " #
INT align centre = 0; # possible values for HTMLTABLE column alignment #
INT align ... |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Liberty_BASIC | Liberty BASIC | 'Display the current date in the formats of "2007-11-10"
d$=date$("yyyy/mm/dd")
print word$(d$,1,"/")+"-"+word$(d$,2,"/")+"-"+word$(d$,3,"/")
'and "Sunday, November 10, 2007".
day$(0)="Tuesday"
day$(1)="Wednesday"
day$(2)="Thursday"
day$(3)="Friday"
day$(4)="Saturday"
day$(5)="Sunday"
day$(6)="Monday"
theDay = date$(... |
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <vector>
class SubMatrix {
const std::vector<std::vector<double>> *source;
std::vector<double> replaceColumn;
const SubMatrix *prev;
size_t sz;
int colIndex = -1;
public:
SubMatrix(const std::vector<std::vector<double>> &src, const std::vecto... |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #AWK | AWK | BEGIN {
printf "" > "output.txt"
close("output.txt")
printf "" > "/output.txt"
close("/output.txt")
system("mkdir docs")
system("mkdir /docs")
} |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Axe | Axe | GetCalc("appvOUTPUT",0) |
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... | #Bracmat | Bracmat | ( ( CSVtoHTML
= p q Character Speech swor rows row
. 0:?p
& :?swor:?rows
& ( @( !arg
: ?
( [!p ?Character "," ?Speech \n [?q ?
& !q:?p
& (tr.,(th.,!Character) (th.,!Speech))
!swor
: ?swor
... |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Open "manip.csv" For Input As #1 ' existing CSV file
Open "manip2.csv" For Output As #2 ' new CSV file for writing changed data
Dim header As String
Line Input #1, header
header += ",SUM"
Print #2, header
Dim As Integer c1, c2, c3, c4, c5, sum
While Not Eof(1)
Input #1, c1, c2, c3, c4, c5
... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #PowerShell | PowerShell |
$table = (
(0, 3, 1, 7, 5, 9, 8, 6, 4, 2),
(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),
(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),
(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),
(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),
(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),
(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),
(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),
(9, 4, 3, 8, 6,... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Nim | Nim | import strformat
import strutils
import math
const cutOff = 200
const bigUn = 100000
const chunks = 50
const little = bigUn div chunks
echo fmt"The first {cutOff} cuban primes"
var primes: seq[int] = @[3, 5]
var c, u = 0
var showEach: bool = true
var v = 1
for i in 1..high(BiggestInt):
var found: bool
inc u, 6
... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Pascal | Pascal | program CubanPrimes;
{$IFDEF FPC}
{$MODE DELPHI}
{$OPTIMIZATION ON,Regvar,PEEPHOLE,CSE,ASMCSE}
{$CODEALIGN proc=32}
{$ENDIF}
uses
primTrial;
const
COLUMNCOUNT = 10*10;
procedure FormOut(Cuban:Uint64;ColSize:Uint32);
var
s : String;
pI,pJ :pChar;
i,j : NativeInt;
Begin
str(Cuban,s);
i := length(s);... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Rust | Rust | fn add_n(n : i32) -> impl Fn(i32) -> i32 {
move |x| n + x
}
fn main() {
let adder = add_n(40);
println!("The answer to life is {}.", adder(2));
} |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Scala | Scala |
def add(a: Int)(b: Int) = a + b
val add5 = add(5) _
add5(2)
|
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Sidef | Sidef | var adder = 1.method(:add);
say adder(3); #=> 4 |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Scala | Scala | import java.text.SimpleDateFormat
import java.util.{Calendar, Locale, TimeZone}
object DateManipulation {
def main(args: Array[String]): Unit = {
val input="March 7 2009 7:30pm EST"
val df=new SimpleDateFormat("MMMM d yyyy h:mma z", Locale.ENGLISH)
val c=Calendar.getInstance()
c.setTime(df.parse(inp... |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
include "duration.s7i";
const func time: parseDate (in string: dateStri) is func
result
var time: aTime is time.value;
local
const array string: monthNames is [] ("January", "February", "March", "April",
"May", "June", "July", "August", "September"... |
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 ... | #Maxima | Maxima | weekday(year, month, day) := block([m: month, y: year, k],
if m < 3 then (m: m + 12, y: y - 1),
k: 1 + remainder(day + quotient((m + 1)*26, 10) + y + quotient(y, 4)
+ 6*quotient(y, 100) + quotient(y, 400) + 5, 7),
['monday, 'tuesday, 'wednesday, 'thurdsday, 'friday, 'saturday, 'sunday][k]
)$
sublist(... |
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 ... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П9 7 П7 1 П8 НОП ИП8 2 2 -
1 0 / [x] П6 ИП9 + 1 8 9
9 - 3 6 5 , 2 5 * [x]
ИП8 ИП6 1 2 * - 1 4 - 3
0 , 5 9 * [x] + 2 9 +
ИП7 + П4 ИП4 7 / [x] 7 * -
x=0 64 ИП9 С/П ИП9 1 + П9 БП 06 |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Rust | Rust | fn cusip_check(cusip: &str) -> bool {
if cusip.len() != 9 {
return false;
}
let mut v = 0;
let capital_cusip = cusip.to_uppercase();
let char_indices = capital_cusip.as_str().char_indices().take(7);
let total = char_indices.fold(0, |total, (i, c)| {
v = match c {
... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Scala | Scala | object Cusip extends App {
val candidates = Seq("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")
for (candidate <- candidates)
printf(f"$candidate%s -> ${if (isCusip(candidate)) "correct" else "incorrect"}%s%n")
private def isCusip(s: String): Boolean = {
if (s.length !=... |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ... | #C.2B.2B | C++ | #include <iostream>
int main()
{
// read values
int dim1, dim2;
std::cin >> dim1 >> dim2;
// create array
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
for (int i = 0; i < dim1; ++i)
array[i] = array_data + dim2*i;
// write element
array[0][0] = 3.5;
// ... |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation langu... | #FOCAL | FOCAL | 01.01 C-- TEST SET
01.10 S T(1)=2;S T(2)=4;S T(3)=4;S T(4)=4
01.20 S T(5)=5;S T(6)=5;S T(7)=7;S T(8)=9
01.30 D 2.1
01.35 T %6.40
01.40 F I=1,8;S A=T(I);D 2.2;T "VAL",A;D 2.3;T " SD",A,!
01.50 Q
02.01 C-- RUNNING STDDEV
02.02 C-- 2.1: INITIALIZE
02.03 C-- 2.2: INSERT VALUE A
02.04 C-- 2.3: A = CURRENT STDDEV
02.10 S X... |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Forth | Forth |
: crc/ ( n -- n ) 8 0 do dup 1 rshift swap 1 and if $edb88320 xor then loop ;
: crcfill 256 0 do i crc/ , loop ;
create crctbl crcfill
: crc+ ( crc n -- crc' ) over xor $ff and cells crctbl + @ swap 8 rshift xor ;
: crcbuf ( crc str len -- crc ) bounds ?do i c@ crc+ loop ;
$ffffffff s" The quick brown f... |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and... | #Fortran | Fortran | module crc32_m
use iso_fortran_env
implicit none
integer(int32) :: crc_table(0:255)
contains
subroutine update_crc(a, crc)
integer :: n, i
character(*) :: a
integer(int32) :: crc
crc = not(crc)
n = len(a)
do i = 1, n
crc = ieor(shiftr(crc, 8)... |
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... | #Arturo | Arturo | changes: function [amount coins][
ways: map 0..amount+1 [x]-> 0
ways\0: 1
loop coins 'coin [
loop coin..amount 'j ->
set ways j (get ways j) + get ways j-coin
]
ways\[amount]
]
print changes 100 [1 5 10 25]
print changes 100000 [1 5 10 25 50 100] |
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... | #360_Assembly | 360 Assembly | * Count occurrences of a substring 05/07/2016
COUNTSTR CSECT
USING COUNTSTR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) ... |
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... | #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Count non-overlapping substrings (BC) in string (HL)
;;; Returns amount of matches in DE
subcnt: lxi d,0 ; Amount of matches
s_scan: mov a,m ; Get current character
ana a ; End of string?
rz ; Then stop
push b ; Keep start of substring search
push h ; Keep current location in string
s_cm... |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #360_Assembly | 360 Assembly | * Octal 04/07/2016
OCTAL CSECT
USING OCTAL,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
... |
http://rosettacode.org/wiki/Count_in_octal | Count in octal | Task
Produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number.
Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
Related task
Integer sequ... | #6502_Assembly | 6502 Assembly |
define SRC_LO $00
define SRC_HI $01
define DEST_LO $02
define DEST_HI $03
define temp $04 ;temp storage used by foo
;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime.
SET_TABLE:
TXA
STA $1000,X
INX
BNE SET_TABLE
;stores the identity table at memory address $1000-$10... |
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... | #11l | 11l | F get_prime_factors(=li)
I li == 1
R ‘1’
E
V res = ‘’
V f = 2
L
I li % f == 0
res ‘’= f
li /= f
I li == 1
L.break
res ‘’= ‘ x ’
E
f++
R res
L(x) 1..17
print(‘#4: #.’.format(x, get_prime_... |
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... | #Arturo | Arturo | table: function [content]
-> join @["<table>" join @content "</table>"]
header: function [cells] -> join @["<tr>" join @cells "</tr>"]
th: function [lbl] -> join @["<th>" lbl "</th>"]
row: function [no]
-> join @[
"<tr><td style='font-weight:bold'>" no "</td>"
"<td>" random 1000 9999 "</td>"
... |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #LiveCode | LiveCode | on mouseUp pButtonNumber
put the date into tDate
convert tDate to dateItems
put item 1 of tDate & "-" & item 2 of tDate & "-" & item 3 of tDate & return into tMyFormattedDate
put tMyFormattedDate & the long date
end mouseUp |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Logo | Logo |
print first shell [date +%F]
print first shell [date +"%A, %B %d, %Y"]
|
http://rosettacode.org/wiki/Cramer%27s_rule | Cramer's rule | linear algebra
Cramer's rule
system of linear equations
Given
{
a
1
x
+
b
1
y
+
c
1
z
=
d
1
a
2
x
+
b
2
y
+
c
2
z
=
d
2
a
3
x
+
b
3
y
+
c
3
z
=
d
3
{\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1... | #Common_Lisp | Common Lisp | (defun minor (m col)
(loop with dim = (1- (array-dimension m 0))
with result = (make-array (list dim dim))
for i from 1 to dim
for r = (1- i)
do (loop with c = 0
for j to dim
when (/= j col)
do (setf (aref result r c) (aref m i j))
... |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #BASIC | BASIC | OPEN "output.txt" FOR OUTPUT AS 1
CLOSE
OPEN "\output.txt" FOR OUTPUT AS 1
CLOSE |
http://rosettacode.org/wiki/Create_a_file | Create a file | In this task, the job is to create a new empty file called "output.txt" of size 0 bytes
and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Batch_File | Batch File | copy nul output.txt
copy nul \output.txt |
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... | #C | C | #include <stdio.h>
const char *input =
"Character,Speech\n"
"The multitude,The messiah! Show us the messiah!\n"
"Brians mother,<angry>Now you listen here! He's not the messiah; "
"he's a very naughty boy! Now go away!</angry>\n"
"The multitude,Who are you?\n"
"Brians mother,I'm his mother; that's who!\n"
"Th... |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #FunL | FunL | import io.{lines, PrintWriter}
data Table( header, rows )
def read( file ) =
l = lines( file )
def next = vector( l.next().split(',') )
if l.isEmpty() then
return Table( vector(), [] )
header = next()
rows = seq()
while l.hasNext()
rows += next()
Table( header, rows.toList() )
def ... |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the cha... | #Gambas | Gambas | Public Sub Form_Open()
Dim sData As String = File.Load("data.csv")
Dim sLine, sTemp As String
Dim sOutput As New String[]
Dim siCount As Short
Dim bLine1 As Boolean
For Each sLine In Split(sData, gb.NewLine)
If Not bLine1 Then
sLine &= ",SUM"
sOutput.Add(sLine)
bLine1 = True
Continue
End If
For... |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #PureBasic | PureBasic | DataSection
DT_Start:
Data.b 0,3,1,7,5,9,8,6,4,2
Data.b 7,0,9,2,1,5,4,8,6,3
Data.b 4,2,0,6,8,7,1,3,5,9
Data.b 1,7,5,0,9,8,3,4,2,6
Data.b 6,1,2,3,0,4,5,9,7,8
Data.b 3,6,7,4,2,0,9,5,8,1
Data.b 5,8,6,9,7,2,0,1,3,4
Data.b 8,9,4,5,3,6,2,0,1,7
Data.b 9,4,3,8,6,1,7,2,0,5
Data.b 2,5,8,1,4,3,6,7,9,0
EndD... |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - ... | #Perl | Perl | use feature 'say';
use ntheory 'is_prime';
sub cuban_primes {
my ($n) = @_;
my @primes;
for (my $k = 1 ; ; ++$k) {
my $p = 3 * $k * ($k + 1) + 1;
if (is_prime($p)) {
push @primes, $p;
last if @primes >= $n;
}
}
return @primes;
}
sub commify {
... |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Standard_ML | Standard ML | fun addnums (x:int) y = x+y (* declare a curried function *)
val add1 = addnums 1 (* bind the first argument to get another function *)
add1 42 (* apply to actually compute a result, 43 *) |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Swift | Swift | func addN(n:Int)->Int->Int { return {$0 + n} }
var add2 = addN(2)
println(add2) // (Function)
println(add2(7)) // 9 |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. 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
Create a simple demonstrative example of Currying in a specific la... | #Tcl | Tcl | interp alias {} addone {} ::tcl::mathop::+ 1
puts [addone 6]; # => 7 |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #SenseTalk | SenseTalk | set date to "March 7 2009 7:30pm EST"
insert "[month name] [day] [year] [hour12]:[min][pm] [timeZoneID]" into the timeInputFormat
put date + 12 hours
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Sidef | Sidef | var dt = frequire('DateTime::Format::Strptime')
var input = 'March 7 2009 7:30pm EST'
input.sub!('EST', 'America/New_York')
say dt.strptime('%b %d %Y %I:%M%p %O', input) \
.add(hours => 12) \
.set_time_zone('America/Edmonton') \
.format_cldr('MMMM d yyyy h:mma zzz... |
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 ... | #Modula-3 | Modula-3 | MODULE Yule EXPORTS Main;
IMPORT IO, Fmt, Date, Time;
VAR date: Date.T;
time: Time.T;
BEGIN
FOR year := 2008 TO 2121 DO
date.day := 25;
date.month := Date.Month.Dec;
date.year := year;
TRY
time := Date.ToTime(date);
EXCEPT
| Date.Error =>
IO.Put(Fmt.Int(year) & " is th... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #SNOBOL4 | SNOBOL4 | #!/usr/local/bin/snobol4 -r
* cusip.sno
* -- Committee on Uniform Security Identification Procedures
* -r : read data placed after the end label.
* Verify check digit and size of cusip code.
define("cusipt()i") :(cusipt_end)
cusipt
chars = &digits &ucase "*@#"
cusipt = table()
... |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North A... | #Swift | Swift | struct CUSIP {
var value: String
private static let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
init?(value: String) {
if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) {
self.value = value
} else if value.count == 8, let checkDigit = CUSIP.... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.