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/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #Sidef | Sidef | var gaps = [];
var previous = :valid;
ARGF.each { |line|
var (date, *readings) = line.words...;
var valid = [];
var hour = 0;
readings.map{.to_n}.each_slice(2, { |slice|
var(reading, flag) = slice...;
if (flag > 0) {
valid << reading;
if (previous == :invalid) {... |
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... | #Phixmonti | Phixmonti | include ..\Utilitys.pmt
( "A partridge in a pear tree."
"Two turtle doves, and"
"Three French hens,"
"Four calling birds,"
"Five gold rings,"
"Six geese a-laying,"
"Seven swans a-swimming,"
"Eight maids a-milking,"
"Nine ladies dancing,"
"Ten lords a-leaping,"
"Eleven pipers piping,"
"Twelve dru... |
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... | #PHP | PHP |
<?php
header("Content-Type: text/plain; charset=UTF-8");
$days = array(
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth',
);
$gifts = array(
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four ca... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #ooRexx | ooRexx |
queue = .workqueue~new
input = .stream~new("jabberwocky.txt")
output = .output
reader = .filereader~new(input, queue)
writer = .filewriter~new(output, queue)
::class workQueue
::method init
expose queue stopped actionpending
queue = .queue~new
stopped = .false
actionPending = .false
-- add an item to th... |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #Batch_File | Batch File | date /t
time /t |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #BBC_BASIC | BBC BASIC | PRINT TIME$ |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #Common_Lisp | Common Lisp | (defun count-and-say (str)
(let* ((s (sort (map 'list #'identity str) #'char>))
(out (list (first s) 0)))
(loop for x in s do
(if (char= x (first out))
(incf (second out))
(setf out (nconc (list x 1) out))))
(format nil "~{~a~^~}" (nreverse out))))
(defun ref-seq-len (n &optional dopri... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Raku | Raku | use Lingua::EN::Numbers;
my @primes = grep *.is-prime, ^Inf;
my @primesums = [\+] @primes;
say "{.elems} cumulative prime sums:\n",
.map( -> $p {
sprintf "The sum of the first %3d (up to {@primes[$p]}) is prime: %s",
1 + $p, comma @primesums[$p]
}
).join("\n")
given grep { @primes... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #REXX | REXX | /*REXX pgm finds summation primes P, primes which the sum of primes up to P are prime. */
parse arg hi . /*obtain optional argument from the CL.*/
if hi=='' | hi=="," then hi= 1000 /*Not specified? Then use the default.*/
call genP ... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | p1 = Polygon[{{50, 150}, {200, 50}, {350, 150}, {350, 300}, {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}];
p2 = Polygon[{{100, 100}, {300, 100}, {300, 300}, {100, 300}}];
RegionIntersection[p1, p2]
Graphics[{Red, p1, Blue, p2, Green, RegionIntersection[p1, p2]}] |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #Eiffel | Eiffel | note
description: "Summary description for {SYMETRIC_DIFFERENCE_EXAMPLE}."
URI: "http://rosettacode.org/wiki/Symmetric_difference"
class
SYMETRIC_DIFFERENCE_EXAMPLE
create
make
feature {NONE} -- Initialization
make
local
a,a1,b,b1: ARRAYED_SET [STRING]
do
create a.make (4)
create b.make (4)
... |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a... | #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
fcn superDW(d){
digits:=d.toString()*d;
[2..].tweak('wrap(n)
{ BI(n).pow(d).mul(d).toString().holds(digits) and n or Void.Skip });
}
foreach d in ([2..8]){ println(d," : ",superDW(d).walk(10).concat(" ")) } |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Lua | Lua | filename = "NOTES.TXT"
if #arg == 0 then
fp = io.open( filename, "r" )
if fp ~= nil then
print( fp:read( "*all*" ) )
fp:close()
end
else
fp = io.open( filename, "a+" )
fp:write( os.date( "%x %X\n" ) )
fp:write( "\t" )
for i = 1, #arg do
fp:write( arg[i], " " )
end
... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Perl | Perl | my $a = 200;
my $b = 200;
my $n = 2.5;
# y in terms of x
sub y_from_x {
my($x) = @_;
int $b * abs(1 - ($x / $a) ** $n ) ** (1/$n)
}
# find point pairs for one quadrant
push @q, $_, y_from_x($_) for 0..200;
# Generate an SVG image
open $fh, '>', 'superellipse.svg';
print $fh
qq|<svg height="@{[2*$b]}" w... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Racket | Racket | #lang racket
(define (cube x) (* x x x))
;floor of cubic root
(define (cubic-root x)
(let ([aprox (inexact->exact (round (expt x (/ 1 3))))])
(if (> (cube aprox) x)
(- aprox 1)
aprox)))
(let loop ([p 1] [n 1])
(let ()
(define pairs
(for*/list ([j (in-range 1 (add1 (cubic-root (qu... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Raku | Raku | constant @cu = (^Inf).map: { .³ }
sub MAIN ($start = 1, $end = 25) {
my %taxi;
my int $taxis = 0;
my $terminate = 0;
my int $max = 0;
for 1 .. * -> $c1 {
last if ?$terminate && ($terminate < $c1);
for 1 .. $c1 -> $c2 {
my $this = @cu[$c1] + @cu[$c2];
%taxi... |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'... | #zkl | zkl | const MAX = 12;
var super=Data(), pos, cnt; // global state, ick
fcn fact_sum(n){ // -->1! + 2! + ... + n!
[1..n].reduce(fcn(s,n){ s + [2..n].reduce('*,1) },0)
}
fcn r(n){
if (not n) return(0);
c := super[pos - n];
if (not (cnt[n]-=1)){
cnt[n] = n;
if (not r(n-1)) return(0);
}
super... |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #EasyLang | EasyLang | k = number input
print k & " °K"
print k - 273.15 & " °C"
print k * 1.8 - 459.67 & " °F"
print k * 1.8 & " °R" |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Quackery | Quackery |
[ 2 ] is maybe ( --> t )
[ table 2 0 1 ] is jiggle ( t --> n )
[ jiggle 1+ ]this[ swap peek do ]done[ ] is 1-trit ( t --> t )
[ swap jiggle 1+ ]this[
swap peek
swap jiggle peek do ]done[ ] is 2-trits ... |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Racket | Racket | #lang typed/racket
; to avoid the hassle of adding a maybe value that is as special as
; the two standard booleans, we'll use symbols to make our own
(define-type trit (U 'true 'false 'maybe))
(: not (trit -> trit))
(define (not a)
(case a
[(true) 'false]
[(maybe) 'maybe]
[(false) 'true]))
(: and (t... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #Swift | Swift | import Foundation
let fmtDbl = { String(format: "%10.3f", $0) }
Task.detached {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let (data, _) = try await URLSession.shared.bytes(from: URL(fileURLWithPath: CommandLine.arguments[1]))
var rowStats = [(Date, Double, Int)]()
var invalid... |
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... | #Picat | Picat | go =>
Days = "first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth".split(" "),
Gifts =
"A partridge in a pear tree.
Two turtle doves, and
Three french hens,
Four calling birds,
Five golden rings,
Six geese a-laying,
Seven swans a-swimming,
Eight maids a-milking,
Nine ladies dancing,
T... |
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... | #PicoLisp | PicoLisp | (de days
first second third fourth fifth sixth
seventh eight ninth tenth eleventh twelfth )
(de texts
"A partridge in a pear tree."
"Two turtle doves and"
"Three french hens"
"Four calling birds"
"Five golden rings"
"Six geese a-laying"
"Seven swans a-swimming"
"Eight maids a-milking"
... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Oz | Oz | declare
%% Helper function to read a file lazily.
%% Returns a lazy list of lines.
fun {ReadLines FN}
F = {New class $ from Open.file Open.text end init(name:FN)}
fun lazy {ReadNext}
case {F getS($)} of
false then nil
[] Line then
Line|{ReadNext}
end
en... |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #BQN | BQN | •Show •UnixTime @ |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #C | C | #include<time.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
time_t my_time = time(NULL);
printf("%s", ctime(&my_time));
return 0;
} |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #D | D | import std.stdio, std.algorithm, std.conv;
string[] selfReferentialSeq(string n, string[] seen=[]) nothrow {
__gshared static string[][string] cache;
if (n in cache)
return cache[n];
if (seen.canFind(n))
return [];
int[10] digit_count;
foreach (immutable d; n)
digit_count... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Ring | Ring |
load "stdlib.ring"
see "working..." + nl
see "Summarize primes:" + nl
see "n sum" + nl
row = 0
sum = 0
limit = 1000
Primes = []
for n = 2 to limit
if isprime(n)
add(Primes,n)
ok
next
for n = 1 to len(Primes)
sum = sum + Primes[n]
if isprime(sum)
row = row + 1
see "" + n + " " ... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Ruby | Ruby | def isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
i = 5
while i * i <= n
if n % i == 0 then
return false
end
i += 2
if n % i == 0 then
... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Rust | Rust | // [dependencies]
// primal = "0.3"
fn main() {
let limit = 1000;
let mut sum = 0;
println!("count prime sum");
for (n, p) in primal::Sieve::new(limit)
.primes_from(2)
.take_while(|x| *x < limit)
.enumerate()
{
sum += p;
if primal::is_prime(sum as u64)... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #MATLAB_.2F_Octave | MATLAB / Octave | %The inputs are a table of x-y pairs for the verticies of the subject
%polygon and boundary polygon. (x values in column 1 and y values in column
%2) The output is a table of x-y pairs for the clipped version of the
%subject polygon.
function clippedPolygon = sutherlandHodgman(subjectPolygon,clipPolygon)
%% Helper... |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #Elixir | Elixir | iex(1)> a = ~w[John Bob Mary Serena] |> MapSet.new
#MapSet<["Bob", "John", "Mary", "Serena"]>
iex(2)> b = ~w[Jim Mary John Bob] |> MapSet.new
#MapSet<["Bob", "Jim", "John", "Mary"]>
iex(3)> sym_dif = fn(a,b) -> MapSet.difference(MapSet.union(a,b), MapSet.intersection(a,b)) end
#Function<12.54118792/2 in :erl_eval.expr/... |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #Erlang | Erlang | %% Implemented by Arjun Sunel
-module(symdiff).
-export([main/0]).
main() ->
SetA = sets:from_list(["John","Bob","Mary","Serena"]),
SetB = sets:from_list(["Jim","Mary","John","Bob"]),
AUnionB = sets:union(SetA,SetB),
AIntersectionB = sets:intersection(SetA,SetB),
SymmDiffAB = sets:subtract(AUnionB,AIntersectionB... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"];
Print[ReadString[str, EndOfFile]]; Close[str],
str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]];
WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]];
Close[str]] |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #MATLAB_.2F_Octave | MATLAB / Octave | function notes(varargin)
% NOTES can be used for taking notes
% usage:
% notes displays the content of the file NOTES.TXT
% notes arg1 arg2 ...
% add the current date, time and arg# to NOTES.TXT
%
filename = 'NOTES.TXT';
if nargin==0
fid = fopen(filename,'rt')... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Phix | Phix | --
-- demo\rosetta\Superellipse.exw
-- =============================
--
with javascript_semantics
atom n = 2.5 -- '+' and '-' increase/decrease in steps of 0.1
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*ih*/)
integer {w, h} = IupGetIntInt(canvas, "DRAWSIZ... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #REXX | REXX | /*REXX program displays the specified first (lowest) taxicab numbers (for three ranges).*/
parse arg L.1 H.1 L.2 H.2 L.3 H.3 . /*obtain optional arguments from the CL*/
if L.1=='' | L.1=="," then L.1= 1 /*L1 is the low part of 1st range. */
if H.1=='' | H.1=="," then H.1= 25 ... |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Elena | Elena | import extensions;
convertKelvinToFahrenheit(x)
= x * 1.8r - 459.6r;
convertKelvinToRankine(x)
= x * 1.8r;
convertKelvinToCelsius(x)
= x - 273.15r;
public program()
{
console.print("Enter a Kelvin Temperature: ");
var inputVal := console.readLine();
real kelvinTemp := 0.0r;
try
... |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Raku | Raku | # Implementation:
enum Trit <Foo Moo Too>;
sub prefix:<¬> (Trit $a) { Trit(1-($a-1)) }
sub infix:<∧> (Trit $a, Trit $b) is equiv(&infix:<*>) { $a min $b }
sub infix:<∨> (Trit $a, Trit $b) is equiv(&infix:<+>) { $a max $b }
sub infix:<⇒> (Trit $a, Trit $b) is equiv(&infix:<..>) { ¬$a max $b }
sub infix:<≡> (Trit $... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #Tcl | Tcl | set max_invalid_run 0
set max_invalid_run_end ""
set tot_file 0
set num_file 0
set linefmt "Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f"
set filename readings.txt
set fh [open $filename]
while {[gets $fh line] != -1} {
set tot_line [set count [set num_line 0]]
set fields [regexp... |
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... | #Pike | Pike | int main() {
array(string) days = ({"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"});
array(string) gifts = ({"A partridge in a pear tree.", "Two turtle doves and", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Perl | Perl | use threads;
use Thread::Queue qw();
my $q1 = Thread::Queue->new;
my $q2 = Thread::Queue->new;
my $reader = threads->create(sub {
my $q1 = shift;
my $q2 = shift;
open my $fh, '<', 'input.txt';
$q1->enqueue($_) while <$fh>;
close $fh;
$q1->enqueue(undef);
print $q2->dequeue;
},... |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #C.23 | C# | Console.WriteLine(DateTime.Now); |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #C.2B.2B | C++ | #include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
int main( ) {
boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
std::cout << to_simple_string( t ) << std::endl ;
return 0 ;
} |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #EchoLisp | EchoLisp |
(lib 'hash)
(lib 'list) ;; permutations
(define H (make-hash))
;; G R A P H
;; generate 'normalized' starter vectors D[i] = number of digits 'i' (0 <=i < 10)
;; reduce graph size : 9009, 9900 .. will be generated once : vector #(2 0 0 0 0 0 0 0 0 2)
(define (generate D dstart ndigits (sd 0))
(when (> ndigits... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Sidef | Sidef | 1000.primes.map_reduce {|a,b| a + b }.map_kv {|k,v|
[k+1, prime(k+1), v]
}.grep { .tail.is_prime }.prepend(
['count', 'prime', 'sum']
).each_2d {|n,p,s|
printf("%5s %6s %8s\n", n, p, s)
} |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
var primes = Int.primeSieve(999)
var sum = 0
var n = 0
var c = 0
System.print("Summing the first n primes (<1,000) where the sum is itself prime:")
System.print(" n cumulative sum")
for (p in primes) {
n = n + 1
sum = sum + p
if (Int.isPrime(sum)) {
c... |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is a prime number
int N, I;
[if N <= 1 then return false;
for I:= 2 to sqrt(N) do
if rem(N/I) = 0 then return false;
return true;
];
int Count, N, Sum, Prime;
[Text(0, "Prime Prime
count sum
");
Count:= 0; N:= 0; Sum:= 0;
for Prime:= 2 to 1000-1 do
if IsPrime(P... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #Nim | Nim | import sequtils, strformat
type
Vec2 = tuple[x, y: float]
Edge = tuple[p, q: Vec2]
Polygon = seq[Vec2]
func `-`(a, b: Vec2): Vec2 = (a.x - b.x, a.y - b.y)
func cross(a, b: Vec2): float = a.x * b.y - a.y * b.x
func isInside(p: Vec2; edge: Edge): bool =
(edge.q.x - edge.p.x) * (p.y - edge.p.y) > (edge.q... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #OCaml | OCaml | let is_inside (x,y) ((ax,ay), (bx,by)) =
(bx -. ax) *. (y -. ay) > (by -. ay) *. (x -. ax)
let intersection (sx,sy) (ex,ey) ((ax,ay), (bx,by)) =
let dc_x, dc_y = (ax -. bx, ay -. by) in
let dp_x, dp_y = (sx -. ex, sy -. ey) in
let n1 = ax *. by -. ay *. bx in
let n2 = sx *. ey -. sy *. ex in
let n3 = 1.0 ... |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #F.23 | F# | > let a = set ["John"; "Bob"; "Mary"; "Serena"]
let b = set ["Jim"; "Mary"; "John"; "Bob"];;
val a : Set<string> = set ["Bob"; "John"; "Mary"; "Serena"]
val b : Set<string> = set ["Bob"; "Jim"; "John"; "Mary"]
> (a-b) + (b-a);;
val it : Set<string> = set ["Jim"; "Serena"] |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Mercury | Mercury | :- module notes.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, time.
main(!IO) :-
io.command_line_arguments(Args, !IO),
( if Args = [] then print_notes(!IO) else add_note(Args, !IO) ).
:- pred print_notes(io::di, io::uo) is det.
pri... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Nim | Nim | import os, times, strutils
if paramCount() == 0:
try: stdout.write readFile("notes.txt")
except IOError: discard
else:
var f = open("notes.txt", fmAppend)
f.writeLine getTime()
f.writeLine "\t", commandLineParams().join(" ")
f.close() |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #OCaml | OCaml | #! /usr/bin/env ocaml
#load "unix.cma"
let notes_file = "notes.txt"
let take_notes() =
let gmt = Unix.gmtime (Unix.time()) in
let date =
Printf.sprintf "%d-%02d-%02d %02d:%02d:%02d"
(1900 + gmt.Unix.tm_year) (1 + gmt.Unix.tm_mon) gmt.Unix.tm_mday
gmt.Unix.tm_hour gmt.Unix.tm_min gmt.Unix.tm_sec
... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Processing | Processing |
//Aamrun, 29th June 2022
float a = 200, b = 200, n = 2.5;
float i, incr = 0.001;
int xMul,yMul;
size(500,500);
stroke(#ff0000);
for(i=0;i<2*PI;i+=incr){
if(PI/2<i && i<3*PI/2)
xMul = -1;
else
xMul = 1;
if(PI<i && i<2*PI)
yMul = -1;
else
yMul = 1;
ellipse(width/2 + xMul * a*pow(abs(... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Ring | Ring |
# Project : Taxicab numbers
num = 0
for n = 1 to 500000
nr = 0
tax = []
for m = 1 to 75
for p = m + 1 to 75
if n = pow(m, 3) + pow(p, 3)
add(tax, m)
add(tax, p)
nr = nr + 1
ok
next
next
if nr > 1
num = nu... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Ruby | Ruby | def taxicab_number(nmax=1200)
[*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort
end
t = [0] + taxicab_number
[*1..25, *2000...2007].each do |i|
puts "%4d: %10d" % [i, t[i][0]] + t[i][1].map{|a| " = %4d**3 + %4d**3" % a}.join
end |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Elixir | Elixir | defmodule Temperature do
def conversion(t) do
IO.puts "K : #{f(t)}"
IO.puts "\nC : #{f(t - 273.15)}"
IO.puts "\nF : #{f(t * 1.8 - 459.67)}"
IO.puts "\nR : #{f(t * 1.8)}"
end
defp f(a) do
Float.round(a, 2)
end
def task, do: conversion(21.0)
end
Temperature.task |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Erlang | Erlang | % Implemented by Arjun Sunel
-module(temp_conv).
-export([main/0]).
main() ->
conversion(21).
conversion(T) ->
io:format("\nK : ~p\n\n",[f(T)]),
io:format("C : ~p \n\n",[f(T - 273.15)]),
io:format("F : ~p\n\n",[f(T * 1.8 - 459.67)]),
io:format("R : ~p\n\n",[f(T * 1.8)]).
f(A) ->
(round(A*1... |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Red | Red | Red ["Ternary logic"]
; define trits as a set of 3 Red words: 'oui, 'non and 'bof
; ('bof is a French teenager word expressing indifference)
trits: [oui bof non]
; set the value of each word to itself
; so the expression " oui " will evaluate to word 'oui
foreach t trits [set t to-lit-word t]
; utility ... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #Ursala | Ursala | #import std
#import nat
#import flo
parsed_data = ^|A(~&,* ^|/%ep@iNC ~&h==`1)*htK27K28pPCS (sep 9%cOi&)*FyS readings_dot_txt
daily_stats =
* ^|A(~&,@rFlS ^/length ^/plus:-0. ||0.! ~&i&& mean); mat` + <.
~&n,
'accept: '--+ @ml printf/'%7.0f'+ float,
'total: '--+ @mrl printf/'%10.1f',
'average: '--+ @... |
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... | #PowerShell | PowerShell | $days = @{
1 = "first";
2 = "second";
3 = "third";
4 = "fourth";
5 = "fifth";
6 = "sixth";
7 = "seventh";
8 = "eight";
9 = "ninth";
10 = "tenth";
11 = "eleventh";
12 = "twelfth";
}
$gifts = @{
1 = 'A partridge in a pear tree';
2 = 'Two turtle doves';
3 = 'Th... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Phix | Phix | -- demo\rosetta\Synchronous_concurrency.exw
without js -- threads, file i/o, command_line()
string filename = substitute(command_line()[2],".exe",".exw")
atom frThread, -- file reader thread
lcThread -- line counter thread
sequence queue = {}
integer qlock = init_cs(),
linecount = 1
procedure readfile()
... |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #Clojure | Clojure | (import '[java.util Date])
; the current system date time string
(print (new Date))
; the system time as milliseconds since 1970
(print (. (new Date) getTime))
; or
(print (System/currentTimeMillis)) |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #CLU | CLU | start_up = proc ()
stream$putl(stream$primary_output(), date$unparse(now()))
end start_up |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #Eiffel | Eiffel |
class
SELF_REFERENTIAL_SEQUENCE
create
make
feature
make
local
i: INTEGER
length, max: INTEGER_64
do
create seed_value.make
create sequence.make (25)
create permuted_values.make
from
i := 1
until
i > 1000000
loop
length := check_length (i.out)
if length > max then
... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #Perl | Perl | use strict;
use warnings;
sub intersection {
my($L11, $L12, $L21, $L22) = @_;
my ($d1x, $d1y) = ($$L11[0] - $$L12[0], $$L11[1] - $$L12[1]);
my ($d2x, $d2y) = ($$L21[0] - $$L22[0], $$L21[1] - $$L22[1]);
my $n1 = $$L11[0] * $$L12[1] - $$L11[1] * $$L12[0];
my $n2 = $$L21[0] * $$L22[1] - $$L21[1] * $$... |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #Factor | Factor | : symmetric-diff ( a b -- c )
[ diff ] [ swap diff ] 2bi append ;
{ "John" "Bob" "Mary" "Serena" } { "Jim" "Mary" "John" "Bob" } symmetric-diff . |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #Forth | Forth | : elm ( n -- ; one cell per set )
[ cell 8 * 1- ] literal umin CREATE 1 swap lshift ,
DOES> ( -- 2^n ) @ ;
: universe ( u "name" -- )
dup 0 DO I elm latest swap LOOP
CREATE dup , 0 DO , LOOP
DOES> ( n a -- ) dup @ tuck cells +
swap 0
DO ( n a' )
over I rshift 1 AND
IF dup @ name>string space type ... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Oz | Oz | functor
import
Application
Open
OS
System
define
fun {TimeStamp}
N = {OS.localTime}
in
(1900+N.year)#"-"#(1+N.mon)#"-"#N.mDay#", "#N.hour#":"#N.min#":"#N.sec
end
fun {Join X|Xr Sep}
{FoldL Xr fun {$ Z X} Z#Sep#X end X}
end
case {Application.getArgs plain}
of nil th... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Pascal | Pascal |
{$mode delphi}
PROGRAM notes;
// Notes: a time-stamped command line notebook
// usage: >notes "note"< or >notes< to display contents
USES Classes, SysUtils;
VAR
Note : TStringList;
Fname : STRING = 'Notes.txt';
Dtime : STRING;
Ntext : STRING;
c : Cardinal;
BEGIN
DTime := FormatDateTime('YYYY-MM-DD-hh... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #Python | Python |
# Superellipse drawing in Python 2.7.9
# pic can see at http://www.imgup.cz/image/712
import matplotlib.pyplot as plt
from math import sin, cos, pi
def sgn(x):
return ((x>0)-(x<0))*1
a,b,n=200,200,2.5 # param n making shape
na=2/n
step=100 # accuracy
piece=(pi*2)/step
xp=[];yp=[]
t=0
for t1 in range(step+1):... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Rust | Rust |
use std::collections::HashMap;
use itertools::Itertools;
fn cubes(n: u64) -> Vec<u64> {
let mut cube_vector = Vec::new();
for i in 1..=n {
cube_vector.push(i.pow(3));
}
cube_vector
}
fn main() {
let c = cubes(1201);
let it = c.iter().combinations(2);
let mut m = HashMap::new();
for x in it {
let sum =... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Scala | Scala | import scala.collection.MapView
import scala.math.pow
implicit class Pairs[A, B]( p:List[(A, B)]) {
def collectPairs: MapView[A, List[B]] = p.groupBy(_._1).view.mapValues(_.map(_._2)).filterNot(_._2.size<2)
}
// Make a sorted List of Taxi Cab Numbers. Limit it to the cube of 1200 because we know it's high enough.... |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Euphoria | Euphoria |
include std/console.e
atom K
while 1 do
K = prompt_number("Enter temperature in Kelvin >=0: ",{0,4294967296})
printf(1,"K = %5.2f\nC = %5.2f\nF = %5.2f\nR = %5.2f\n\n",{K,K-273.15,K*1.8-459.67,K*1.8})
end while
|
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #REXX | REXX | /*REXX program displays a ternary truth table [true, false, maybe] for the variables */
/*──── and one or more expressions. */
/*──── Infix notation is supported with one character propositional constants. */
/*──── Variables (propositional constants) allo... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #VBScript | VBScript | Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\data.txt",1)
bad_readings_total = 0
good_readings_total = 0
data_gap = 0
start_date = ""
end_date = ""
tmp_datax_gap = 0
tmp_start_date = ""
Do Until objFile.AtEndOfSt... |
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... | #Prolog | Prolog | day(1, 'first').
day(2, 'second').
day(3, 'third').
day(4, 'fourth').
day(5, 'fifth').
day(6, 'sixth').
day(7, 'seventh').
day(8, 'eighth').
day(9, 'ninth').
day(10, 'tenth').
day(11, 'eleventh').
day(12, 'twelfth').
gift(1, 'A partridge in a pear tree.').
gift(2, 'Two turtle doves and').
gift(3, 'Three French hens,'... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #PicoLisp | PicoLisp | # Reading task (synchronous)
(task (open "input.txt")
(let Fd @
(if (in Fd (line T)) # More lines?
(udp "localhost" 4444 @) # Yes: Send next line
(task (port T 4445) # Else install handler
(prinl (udp @) " lines") # to receive and print count
... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #Pony | Pony | use "files"
actor Main
let _env: Env // The environment contains stdout, so we save it here
new create(env: Env) =>
_env = env
let printer: Printer tag = Printer(env)
try
let path = FilePath(env.root as AmbientAuth, "input.txt")? // this may fail, hence the ?
let file = File.open(path)
... |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #COBOL | COBOL | WORKING-STORAGE SECTION.
01 WS-CURRENT-DATE-FIELDS.
05 WS-CURRENT-DATE.
10 WS-CURRENT-YEAR PIC 9(4).
10 WS-CURRENT-MONTH PIC 9(2).
10 WS-CURRENT-DAY PIC 9(2).
05 WS-CURRENT-TIME.
10 WS-CURRENT-HOUR PIC ... |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #F.23 | F# |
// Summarize and say sequence . Nigel Galloway: April 23rd., 2021
let rec fN g=let n=let n,g=List.head g|>List.countBy id|>List.unzip in n@(g|>List.collect(fun g->if g<10 then [g] else [g/10;g%10]))
if List.contains n g then g.Tail|>List.rev else fN(n::g)
let rec fG n g=seq{yield! n; if g>1 then yield! f... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #Phix | Phix | --
-- demo\rosetta\Sutherland_Hodgman_polygon_clipping.exw
-- ====================================================
--
with javascript_semantics
enum X,Y
function inside(sequence cp1, cp2, p)
return (cp2[X]-cp1[X])*(p[Y]-cp1[Y])>(cp2[Y]-cp1[Y])*(p[X]-cp1[X])
end function
function intersect(sequence cp1, cp2, s, e)... |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #Fortran | Fortran | program Symmetric_difference
implicit none
character(6) :: a(4) = (/ "John ", "Bob ", "Mary ", "Serena" /)
character(6) :: b(4) = (/ "Jim ", "Mary ", "John ", "Bob " /)
integer :: i, j
outer1: do i = 1, size(a)
do j = 1, i-1
if(a(i) == a(j)) cycle outer1 ! Do not check duplic... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Perl | Perl | my $file = 'notes.txt';
if ( @ARGV ) {
open NOTES, '>>', $file or die "Can't append to file $file: $!";
print NOTES scalar localtime, "\n\t@ARGV\n";
} else {
open NOTES, '<', $file or die "Can't read file $file: $!";
print <NOTES>;
}
close NOTES; |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Phix | Phix | without js -- (file i/o)
constant cmd = command_line(),
filename = "notes.txt"
if length(cmd)<3 then
object text = get_text(filename)
printf(1,"%s\n",iff(string(text)?text:"<empty>"))
else
integer fn = open(filename,"a")
printf(fn,"%d-%02d-%02d %d:%02d:%02d\n",date())
printf(fn,"\t%s\n",joi... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #QB64 | QB64 | _Title "Super Ellipse"
Dim As Integer sw, sh
Dim As Single i
sw = 480: sh = 480
Screen _NewImage(sw, sh, 8)
Cls , 15
'Show different possible Super Ellipse shapes
Color 10
For i = 0.2 To 5.0 Step .1
Call SuperEllipse(sw \ 2, sh \ 2, 200, 200, i, 80)
Next
'Show task specified Super Ellipse
Color 0
Call Super... |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a... | #QBasic | QBasic | SCREEN 12
CLS
a = 200
b = 200
n = 2.5
na = 2 / n
t = .01
LINE -(520, 245), 0, BF
FOR i = 0 TO 314
xp = a * SGN(COS(t)) * ABS((COS(t))) ^ na + 320
yp = b * SGN(SIN(t)) * ABS((SIN(t))) ^ na + 240
t = t + .02
LINE -(xp, yp), 1, BF
NEXT i |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Scheme | Scheme |
(import (scheme base)
(scheme write)
(srfi 1) ; lists
(srfi 69) ; hash tables
(srfi 132)) ; sorting
(define *max-n* 1500) ; let's go up to here, maximum for x and y
(define *numbers* (make-hash-table eqv?)) ; hash table for total -> list of list of pairs
(define (r... |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Excel | Excel | A1 : Kelvin
B1 : Celsius
C1 : Fahrenheit
D1 : Rankine
Name A2 : K
B2 : =K-273.15
C2 : =K*1.8-459.67
D2 : =K*1.8
Input in A1 |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute z... | #Ezhil | Ezhil |
# convert from Kelvin
நிரல்பாகம் கெல்வின்_இருந்து_மாற்று( k )
பதிப்பி "Kelvin: ",k,"Celsius: ",round(k-273.15)," Fahrenheit: ",(round(k*1.8 - 459.67))," Rankine: ",(round(k*1.8))
முடி
கெல்வின்_இருந்து_மாற்று( 0 ) #absolute zero
கெல்வின்_இருந்து_மாற்று( 273 ) #freezing pt of water
கெல்வின்_இருந்து_மாற்று( 30 + 273 ... |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Ruby | Ruby | # trit.rb - ternary logic
# http://rosettacode.org/wiki/Ternary_logic
require 'singleton'
# MAYBE, the only instance of MaybeClass, enables a system of ternary
# logic using TrueClass#trit, MaybeClass#trit and FalseClass#trit.
#
# !a.trit # ternary not
# a.trit & b # ternary and
# a.trit | b # ternary o... |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr... | #Vedit_macro_language | Vedit macro language | #50 = Buf_Num // Current edit buffer (source data)
File_Open("output.txt")
#51 = Buf_Num // Edit buffer for output file
Buf_Switch(#50)
#10 = 0 // total sum of file data
#11 = 0 // number of valid data items in file
#12 = 0 // Current run of consecutive flags<0 in lines of file
#13 = -1 // Max consecutive flag... |
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... | #PureBasic | PureBasic | #TXT$ = "On the * day of Christmas, my true love sent to me:"
days$ = ~"first\nsecond\nthird\nfourth\nfifth\nsixth\nseventh\neighth\nninth\ntenth\neleventh\ntwelfth\n"
gifts$= ~"Twelve drummers drumming,\nEleven pipers piping,\nTen lords a-leaping,\nNine ladies dancing,\n"+
~"Eight maids a-milking,\nSeven swans... |
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... | #Python | Python | gifts = '''\
A partridge in a pear tree.
Two turtle doves
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pipers piping
Twelve drummers drumming'''.split('\n')
days = '''first second third fourth fift... |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th... | #PureBasic | PureBasic | Enumeration
#Write
#Done
EndEnumeration
Structure commblock
txtline.s
Order.i
EndStructure
Global MessageSent=CreateSemaphore()
Global LineWritten=CreateSemaphore()
Global LinesWritten, com.commblock
Procedure Writer(arg)
Repeat
WaitSemaphore(MessageSent)
If com\Order=#Write
PrintN(com\t... |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #ColdFusion | ColdFusion | <cfscript>
// Date Time
currentTime = Now();
writeOutput( currentTime );
// Epoch
// Credit for Epoch time should go to Ben Nadel
// bennadel.com is his blog
utcDate = dateConvert( "local2utc", currentTime );
writeOutput( utcDate.getTime() );
</cfscript> |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retr... | #Common_Lisp | Common Lisp | (multiple-value-bind (second minute hour day month year) (get-decoded-time)
(format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second)) |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #Factor | Factor | USING: assocs grouping io kernel math math.combinatorics
math.functions math.ranges math.statistics math.text.utils
prettyprint sequences sets ;
IN: rosetta-code.self-referential-sequence
: next-term ( seq -- seq ) histogram >alist concat ;
! Output the self-referential sequence, given a seed value.
: srs ( seq -- ... |
http://rosettacode.org/wiki/Sutherland-Hodgman_polygon_clipping | Sutherland-Hodgman polygon clipping | The Sutherland-Hodgman clipping algorithm finds the polygon that is the intersection between an arbitrary polygon (the “subject polygon”) and a convex polygon (the “clip polygon”).
It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a... | #PHP | PHP |
<?php
function clip ($subjectPolygon, $clipPolygon) {
function inside ($p, $cp1, $cp2) {
return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);
}
function intersection ($cp1, $cp2, $e, $s) {
$dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];
$dp = [ $s[0] - ... |
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.
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.