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/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #Stata | Stata | clear
gen str8 addrid=""
gen str50 street=""
gen str25 city=""
gen str2 state=""
gen str20 zip=""
save address |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #Tcl.2BSQLite | Tcl+SQLite | package require sqlite3
sqlite3 db address.db
db eval {
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
} |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #Transact-SQL_.28MSSQL.29 | Transact-SQL (MSSQL) | CREATE TABLE #Address (
addrID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
addrStreet VARCHAR(50) NOT NULL ,
addrCity VARCHAR(25) NOT NULL ,
addrState CHAR(2) NOT NULL ,
addrZIP CHAR(10) NOT NULL
)
DROP TABLE #Address |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #VBScript | VBScript |
Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE... |
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... | #AmigaBASIC | AmigaBASIC | print date$,time$ |
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... | #AppleScript | AppleScript | display dialog ((current date) as text) |
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... | #BBC_BASIC | BBC BASIC | *FLOAT64
DIM list$(30)
maxiter% = 0
maxseed% = 0
FOR seed% = 0 TO 999999
list$(0) = STR$(seed%)
iter% = 0
REPEAT
list$(iter%+1) = FNseq(list$(iter%))
IF VALlist$(iter%+1) <= VALlist$(iter%) THEN
FOR try% = iter% TO 0 STEP -1
... |
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.
| #C.2B.2B | C++ | #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
... |
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... | #Go | Go | package main
import "fmt"
type point struct {
x, y float32
}
var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}
var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}
func main() {
var cp1, cp2, ... |
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... | #C | C | #include <stdio.h>
#include <string.h>
const char *A[] = { "John", "Serena", "Bob", "Mary", "Serena" };
const char *B[] = { "Jim", "Mary", "John", "Jim", "Bob" };
#define LEN(x) sizeof(x)/sizeof(x[0])
/* null duplicate items */
void uniq(const char *x[], int len)
{
int i, j;
for (i = 0; i < len; i++)
for (j =... |
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... | #Lua | Lua | for d = 2, 5 do
local n, found = 0, {}
local dds = string.rep(d, d)
while #found < 10 do
local dnd = string.format("%15.f", d * n ^ d)
if string.find(dnd, dds) then found[#found+1] = n end
n = n + 1
end
print("super-" .. d .. ": " .. table.concat(found,", "))
end |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[SuperD]
SuperD[d_, m_] := Module[{n, res, num},
res = {};
n = 1;
While[Length[res] < m,
num = IntegerDigits[d n^d];
If[MatchQ[num, {___, Repeated[d, {d}], ___}],
AppendTo[res, n]
];
n++;
];
res
]
Scan[Print[SuperD[#, 10]] &, Range[2, 6]] |
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... | #Nim | Nim | import sequtils, strutils, times
import bignum
iterator superDNumbers(d, maxCount: Positive): Natural =
var count = 0
var n = 2
let e = culong(d) # Bignum ^ requires a culong as exponent.
let pattern = repeat(chr(d + ord('0')), d)
while count != maxCount:
if pattern in $(d * n ^ e):
yield n
... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #FreeBASIC | FreeBASIC | If Len(Command) Then
Open "notes.txt" For Append As #1
Print #1, Date, Time
Print #1, Chr(9); Command
Close
Else
If Open("notes.txt" For Input As #1) = 0 Then
Dim As String lin
Print "Contenido del archivo:"
Do While Not Eof(1)
Line Input #1, lin
Print... |
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... | #Gambas | Gambas | 'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas'
Public Sub Main()
Dim sContents As String 'To store the file contents
Dim sArgs As String[] = Args.All 'To store all the Command l... |
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... | #J | J | selips=: 4 :0
'n a b'=. y
1 >: ((n^~a%~]) +&|/ n^~b%~]) i:x
)
require'viewmat'
viewmat 300 selips 2.5 200 200 |
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... | #Java | Java | import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new ... |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequenc... | #Swift | Swift | import BigNumber
func sylvester(n: Int) -> BInt {
var a = BInt(2)
for _ in 0..<n {
a = a * a - a + 1
}
return a
}
var sum = BDouble(0)
for n in 0..<10 {
let syl = sylvester(n: n)
sum += BDouble(1) / BDouble(syl)
print(syl)
}
print("Sum of the reciprocals of first ten in sequence: \(sum)") |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequenc... | #Verilog | Verilog |
module main;
integer i;
real suma, num;
initial begin
$display("10 primeros términos de la sucesión de sylvester:");
$display("");
suma = 0;
num = 0;
for(i=1; i<=10; i=i+1) begin
if (i==1) num = 2;
else num = num * num - num + 1;
$display(i, ": ", num);
... |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. 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 number theory, Sylvester's sequence is an integer sequenc... | #Wren | Wren | import "/big" for BigInt, BigRat
var sylvester = [BigInt.two]
var prod = BigInt.two
var count = 1
while (true) {
var next = prod + 1
sylvester.add(next)
count = count + 1
if (count == 10) break
prod = prod * next
}
System.print("The first 10 terms in the Sylvester sequence are:")
System.print(sylv... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | findTaxi[n_] := Sort[Keys[Select[Counts[Flatten[Table[x^3 + y^3, {x, 1, n}, {y, x, n}]]], GreaterThan[1]]]];
Take[findTaxiNumbers[100], 25]
found=findTaxiNumbers[1200][[2000 ;; 2005]]
Map[Reduce[x^3 + y^3 == # && x >= y && x > 0 && y > 0, {x, y}, Integers] &, found] |
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... | #Nim | Nim | import heapqueue, strformat
type
CubeSum = tuple[x, y, value: int]
# Comparison function needed for the heap queues.
proc `<`(c1, c2: CubeSum): bool = c1.value < c2.value
template cube(n: int): int = n * n * n
iterator cubesum(): CubeSum =
var queue: HeapQueue[CubeSum]
var n = 1
while true:
whil... |
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'... | #Perl | Perl | use ntheory qw/forperm/;
for my $len (1..8) {
my($pre, $post, $t) = ("","");
forperm {
$t = join "",@_;
$post .= $t unless index($post ,$t) >= 0;
$pre = $t . $pre unless index($pre, $t) >= 0;
} $len;
printf "%2d: %8d %8d\n", $len, length($pre), length($post);
} |
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'... | #Phix | Phix | with javascript_semantics
constant nMax = iff(platform()=JS?8:12)
-- Aside: on desktop/Phix, strings can be modified in situ, whereas
-- JavaScript strings are immutable, and the equivalent code
-- in p2js.js ends up doing excessive splitting and splicing
-- hence nMax has to be significantly smal... |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Verilog | Verilog | module main;
integer n, m, num, limit, tau;
initial begin
$display("The first 100 tau numbers are:\n");
n = 0;
num = 0;
limit = 100;
while (num < limit) begin
n = n + 1;
tau = 0;
for (m = 1; m <= n; m=m+1) if (n % m == 0) tau = tau + 1;
if (n % tau == 0) begin
... |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #VTL-2 | VTL-2 | 10 N=1100
20 I=1
30 :I)=1
40 I=I+1
50 #=N>I*30
60 I=2
70 J=I
80 :J)=:J)+1
90 J=J+I
100 #=N>J*80
110 I=I+1
120 #=N>I*70
130 C=0
140 I=1
150 #=I/:I)*0+0<%*210
160 ?=I
170 $=9
180 C=C+1
190 #=C/10*0+0<%*210
200 ?=""
210 I=I+1
220 #=C<100*150 |
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... | #Ceylon | Ceylon | shared void run() {
void printKelvinConversions(Float kelvin) {
value celsius = kelvin - 273.15;
value rankine = kelvin * 9.0 / 5.0;
value fahrenheit = rankine - 459.67;
print("Kelvin: ``formatFloat(kelvin, 2, 2)``
Celsius: ``formatFloat(celsius, 2, 2)``
... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #PureBasic | PureBasic | If OpenConsole()
For i=1 To 100
If i<3 : Print(RSet(Str(i),4)) : Continue :EndIf
c=2
For j=2 To i/2+1 : c+Bool(i%j=0) : Next
Print(RSet(Str(c),4))
If i%10=0 : PrintN("") : EndIf
Next
Input()
EndIf
End |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Python | Python | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #REXX | REXX | /*REXX boilerplate determines how to clear screen (under various REXXes)*/
trace off; parse arg ! /*turn off tracing; get C.L. args*/
if !all(arg()) then exit /*Doc request? Show, then exit.*/
if !cms then address '' /*Is this CMS? Use this address.*/
!cls ... |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary... | #Perl | Perl | package Trit;
# -1 = false ; 0 = maybe ; 1 = true
use Exporter 'import';
our @EXPORT_OK = qw(TRUE FALSE MAYBE is_true is_false is_maybe);
our %EXPORT_TAGS = (
all => \@EXPORT_OK,
const => [qw(TRUE FALSE MAYBE)],
bool => [qw(is_true is_false is_maybe)],
);
use List::Util qw(min max);
use overload
'=' => su... |
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... | #R | R | #Read in data from file
dfr <- read.delim("readings.txt")
#Calculate daily means
flags <- as.matrix(dfr[,seq(3,49,2)])>0
vals <- as.matrix(dfr[,seq(2,49,2)])
daily.means <- rowSums(ifelse(flags, vals, 0))/rowSums(flags)
#Calculate time between good measurements
times <- strptime(dfr[1,1], "%Y-%m-%d", tz="GMT") + 3600*s... |
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... | #MiniScript | MiniScript | days = ["first","second","third", "fourth","fifth","sixth",
"seventh","eigth","nineth","tenth","eleventh","twelfth"]
gifts = ["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-swimmi... |
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... | #Nim | Nim | import strutils, algorithm
const
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",
... |
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... | #J | J | input=: 1 :0
nlines=: 0
u;._2@fread 'input.txt'
smoutput nlines
)
output=: 3 :0
nlines=: nlines+1
smoutput y
) |
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... | #Java | Java | import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
class SynchronousConcurrency
{
public static void main(String[] args)... |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #Visual_FoxPro | Visual FoxPro |
CLOSE DATABASES ALL
CREATE DATABASE usdata.dbc
SET NULL OFF
CREATE TABLE address.dbf ;
(id I AUTOINC NEXTVALUE 1 STEP 1 PRIMARY KEY COLLATE "Machine", ;
street V(50), city V(25), state C(2), zipcode C(10))
CLOSE DATABASES ALL
*!* To use
CLOSE DATABASES ALL
OPEN DATABASE usdata.dbc
USE address.dbf SHARED
|
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #Wren | Wren | import "/dynamic" for Enum, Tuple
import "/fmt" for Fmt
import "/sort" for Cmp, Sort
var FieldType = Enum.create("FieldType", ["text", "num", "int", "bool"])
var Field = Tuple.create("Field", ["name", "fieldType", "maxLen"])
class Table {
construct new(name, fields, keyIndex) {
_name = name
_f... |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program sysTime.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/****************************************... |
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... | #Bracmat | Bracmat | ( ( self-referential
= seq N next
. ( next
= R S d f
. 0:?S
& whl
' (@(!arg:%@?d ?arg)&(.!d)+!S:?S)
& :?R
& whl
' ( !S:#?f*(.?d)+?S
& !f !d !R:?R
)
& str$!R
)
& 1... |
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.
| #F.23 | F# |
// Summarize Primes: Nigel Galloway. April 16th., 2021
primes32()|>Seq.takeWhile((>)1000)|>Seq.scan(fun(n,g) p->(n+1,g+p))(0,0)|>Seq.filter(snd>>isPrime)|>Seq.iter(fun(n,g)->printfn "%3d->%d" n g)
|
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.
| #Factor | Factor | USING: assocs formatting kernel math.primes math.ranges
math.statistics prettyprint ;
1000 [ [1,b] ] [ primes-upto cum-sum ] bi zip
[ nip prime? ] assoc-filter
[ "The sum of the first %3d primes is %5d (which is prime).\n" printf ] assoc-each |
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.
| #Fermat | Fermat | n:=0
s:=0
for i=1, 162 do s:=s+Prime(i);if Isprime(s)=1 then n:=n+1;!!(n,Prime(i),s) fi od
|
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.
| #Forth | Forth | : prime? ( n -- flag )
dup 2 < if drop false exit then
dup 2 mod 0= if 2 = exit then
dup 3 mod 0= if 3 = exit then
5
begin
2dup dup * >=
while
2dup mod 0= if 2drop false exit then
2 +
2dup mod 0= if 2drop false exit then
4 +
repeat
2drop true ;
: main
0 0 { count sum }
." count... |
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... | #Haskell | Haskell | module SuthHodgClip (clipTo) where
import Data.List
type Pt a = (a, a)
type Ln a = (Pt a, Pt a)
type Poly a = [Pt a]
-- Return a polygon from a list of points.
polyFrom ps = last ps : ps
-- Return a list of lines from a list of points.
linesFrom pps@(_:ps) = zip pps ps
-- Return true if the point (x,y) is... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace RosettaCode.SymmetricDifference
{
public static class IEnumerableExtension
{
public static IEnumerable<T> SymmetricDifference<T>(this IEnumerable<T> @this, IEnumerable<T> that)
{
return @this.Except(that).... |
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... | #Pascal | Pascal | program Super_D;
uses
sysutils,gmp;
var
s :ansistring;
s_comp : ansistring;
test : mpz_t;
i,j,dgt,cnt : NativeUint;
Begin
mpz_init(test);
for dgt := 2 to 9 do
Begin
//create '22' to '999999999'
i := dgt;
For j := 2 to dgt do
i := i*10+dgt;
s_comp := IntToStr(i);
writeln... |
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... | #Go | Go | package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
// To be extra careful with er... |
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... | #JavaScript | JavaScript |
var n = 2.5, a = 200, b = 200, ctx;
function point( x, y ) {
ctx.fillRect( x, y, 1, 1);
}
function start() {
var can = document.createElement('canvas');
can.width = can.height = 600;
ctx = can.getContext( "2d" );
ctx.rect( 0, 0, can.width, can.height );
ctx.fillStyle = "#000000"; ctx.fill... |
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... | #PARI.2FGP | PARI/GP | taxicab(n)=my(t); for(k=sqrtnint((n-1)\2,3)+1, sqrtnint(n,3), if(ispower(n-k^3, 3), if(t, return(1), t=1))); 0;
cubes(n)=my(t); for(k=sqrtnint((n-1)\2,3)+1, sqrtnint(n,3), if(ispower(n-k^3, 3, &t), print(n" = \t"k"^3\t+ "t"^3")))
select(taxicab, [1..402597])
apply(cubes, %); |
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'... | #PureBasic | PureBasic | EnableExplicit
#MAX=10
Declare.i fact_sum(n.i) : Declare.i r(n.i) : Declare superperm(n.i)
Global pos.i, Dim cnt.i(#MAX), Dim super.s{1}(fact_sum(#MAX))
If OpenConsole() ;- MAIN: Superpermutation_minimisation
Define.i n
For n=0 To #MAX
superperm(n) : Print("superperm("+RSet(Str(n),2)+") len = "+LSet(Str(pos... |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
System.print("The first 100 tau numbers are:")
var count = 0
var i = 1
while (count < 100) {
var tf = Int.divisors(i).count
if (i % tf == 0) {
Fmt.write("$,5d ", i)
count = count + 1
if (count % 10 == 0) System.print()
}
i = i + 1
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #XPL0 | XPL0 | func Divs(N); \Return number of divisors of N
int N, D, C;
[C:= 0;
for D:= 1 to N do
if rem(N/D) = 0 then C:= C+1;
return C;
];
int C, N;
[Format(5, 0);
C:= 0; N:= 1;
loop [if rem(N/Divs(N)) = 0 then
[RlOut(0, float(N));
C:= C+1;
if rem(C/10) = 0 then CrLf(0);
... |
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... | #Clojure | Clojure | (defn to-celsius [k]
(- k 273.15))
(defn to-fahrenheit [k]
(- (* k 1.8) 459.67))
(defn to-rankine [k]
(* k 1.8))
(defn temperature-conversion [k]
(if (number? k)
(format "Celsius: %.2f Fahrenheit: %.2f Rankine: %.2f"
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(format "Error: Non-nume... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Quackery | Quackery | [ factors size ] is tau ( n --> n )
[] []
100 times [ i^ 1+ tau join ]
witheach [ number$ nested join ]
70 wrap$
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #R | R | lengths(sapply(1:100, function(n) c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Raku | Raku | use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;
say "\nTau function - first 100:\n", # ID
(1..*).map({ +.&divisors })[^100]\ # the task
.batch(20)».fmt("%3d").join("\n"); # display formatting
say "\nTau numbers - first 100:\n", # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\ ... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Ring | Ring | system('clear') |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Ruby | Ruby | system 'clear' |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Rust | Rust | print!("\x1B[2J"); |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Scala | Scala | object Cls extends App {print("\033[2J")} |
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... | #Phix | Phix | enum T, M, F
type ternary(integer t) return find(t,{T,M,F}) end type
function t_not(ternary a)
return F+1-a
end function
function t_and(ternary a, ternary b)
return iff(a=T and b=T?T:iff(a=F or b=F?F:M))
end function
function t_or(ternary a, ternary b)
return iff(a=T or b=T?T:iff(a=F and b=F?F:M)) ... |
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... | #Racket | Racket | #lang racket
;; Use SRFI 48 to make %n.nf formats convenient.
(require (prefix-in srfi/48: srfi/48)) ; SRFI 48: Intermediate Format Strings
;; Parameter allows us to used exact decimal strings
(read-decimal-as-inexact #f)
;; files to read is a sequence, so it could be either a list or vector of files
(define (text-... |
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... | #Objeck | Objeck |
class TwelveDaysOfChristmas {
function : Main(args : String[]) ~ Nil {
days := ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
"tenth", "eleventh", "twelfth"];
gifts := ["A partridge in a pear tree",
"Two turtle doves",
"Three... |
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... | #Julia | Julia |
function inputlines(txtfile, iochannel)
for line in readlines(txtfile)
Base.put!(iochannel, line)
end
Base.put!(iochannel, nothing)
println("The other task printed $(take!(iochannel)) lines.")
end
function outputlines(iochannel)
totallines = 0
while (line = Base.take!(iochannel)) != ... |
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... | #Kotlin | Kotlin | import java.util.concurrent.SynchronousQueue
import kotlin.concurrent.thread
import java.io.File
const val EOT = "\u0004" // end of transmission
fun main(args: Array<String>) {
val queue = SynchronousQueue<String>()
val work = thread {
var count = 0
while (true) {
val line ... |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip... | #zkl | zkl | const NM="address.db";
dbExec(NM,"create table address (street, city, state, zip);"); |
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... | #Arturo | Arturo | print 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... | #Asymptote | Asymptote | time();
time("%a %b %d %H:%M:%S %Z %Y");
//are equivalent ways of returning the current time in the default format used by the UNIX date command. |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec_t rec_t;
struct rec_t {
int depth;
rec_t * p[10];
};
rec_t root = {0, {0}};
#define USE_POOL_ALLOC
#ifdef USE_POOL_ALLOC /* not all that big a deal */
rec_t *tail = 0, *head = 0;
#define POOL_SIZE (1 << 20)
inline rec_t *new_rec()
{
... |
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.
| #FreeBASIC | FreeBASIC | #include "isprime.bas"
print 1,2,2
dim as integer sum = 2, i, n=1
for i = 3 to 999 step 2
if isprime(i) then
sum += i
n+=1
if isprime(sum) then
print n, i, sum
end if
end if
next i |
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum, n, c := 0, 0, 0
fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:")
fmt.Println(" n cumulative sum")
for _, p := range primes {
n++
sum += p
if rcu.IsP... |
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... | #J | J | NB. assumes counterclockwise orientation.
NB. determine whether point y is inside edge x.
isinside=:0< [:-/ .* {.@[ -~"1 {:@[,:]
NB. (p0,:p1) intersection (p2,:p3)
intersection=:|:@[ (+/ .* (,-.)) [:{. ,.&(-~/) %.~ -&{:
SutherlandHodgman=:4 :0 NB. clip S-H subject
clip=.2 ]\ (,{.) x
subject=.y
for_edge. clip ... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;
int main( ) {
string setA[] = { "John", "Bob" , "Mary", "Serena" };
string setB[] = { "Jim" , "Mary", "John", "Bob" };
set<string>
firstSet( setA , setA + 4 ),
secondSet( setB ... |
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... | #Perl | Perl | use strict;
use warnings;
use bigint;
use feature 'say';
sub super {
my $d = shift;
my $run = $d x $d;
my @super;
my $i = 0;
my $n = 0;
while ( $i < 10 ) {
if (index($n ** $d * $d, $run) > -1) {
push @super, $n;
++$i;
}
++$n;
}
@super;
}
... |
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... | #Phix | Phix | with javascript_semantics
include mpfr.e
procedure main()
atom t0 = time()
mpz k = mpz_init()
for i=2 to iff(platform()=JS?7:9) do
printf(1,"First 10 super-%d numbers:\n", i)
integer count := 0, j = 3
string tgt = repeat('0'+i,i)
while count<10 do
mpz_ui_pow_ui(... |
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... | #Groovy | Groovy | def notes = new File('./notes.txt')
if (args) {
notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n"
} else {
println notes.text
}
|
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... | #Haskell | Haskell | import System.Environment (getArgs)
import System.Time (getClockTime)
main :: IO ()
main = do
args <- getArgs
if null args
then catch (readFile "notes.txt" >>= putStr)
(\_ -> return ())
else
do ct <- getClockTime
appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "... |
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... | #Julia | Julia | function superellipse(n, a, b, step::Int=100)
@assert n > 0 && a > 0 && b > 0
na = 2 / n
pc = 2π / step
t = 0
xp = Vector{Float64}(undef, step + 1)
yp = Vector{Float64}(undef, step + 1)
for i in 0:step
# because sin^n(x) is mathematically the same as (sin(x))^n...
xp[i+1] = ... |
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... | #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import java.awt.geom.Path2D
import javax.swing.*
import java.lang.Math.pow
/* assumes a == b */
class SuperEllipse(val n: Double, val a: Int) : JPanel() {
init {
require(n > 0.0 && a > 0)
preferredSize = Dimension(650, 650)
background = Color.black
... |
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... | #Pascal | Pascal | program taxiCabNo;
uses
sysutils;
type
tPot3 = Uint32;
tPot3Sol = record
p3Sum : tPot3;
i1,j1,
i2,j2 : Word;
end;
tpPot3 = ^tPot3;
tpPot3Sol = ^tPot3Sol;
var
//1290^3 = 2'146'689'000 < 2^31-1
//1190 is the magic number of the task ;-)
pot3 : ar... |
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'... | #Python | Python | "Generate a short Superpermutation of n characters A... as a string using various algorithms."
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
"""
Uses greedy algorithm ... |
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... | #CLU | CLU | kelvin = proc (k: real) returns (real)
return(k)
end kelvin
celsius = proc (k: real) returns (real)
return(k - 273.15)
end celsius
rankine = proc (k: real) returns (real)
return(k * 9./5.)
end rankine
fahrenheit = proc (k: real) returns (real)
return(rankine(k) - 459.67)
end fahrenheit
conv =... |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #REXX | REXX | /*REXX program counts the number of divisors (tau, or sigma_0) up to and including N.*/
parse arg LO HI cols . /*obtain optional argument from the CL.*/
if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= LO + 100 - ... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "console.s7i";
const proc: main is func
local
var text: console is STD_NULL;
begin
console := open(CONSOLE);
clear(console);
# Terminal windows often restore the previous
# content, when a program is terminated. Therefore
# the program waits until Return... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Sidef | Sidef | func clear { print(static x = `clear`) };
clear(); |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Smalltalk | Smalltalk | Transcript clear. |
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... | #PHP | PHP | #!/usr/bin/php
<?php
# defined as numbers, so I can use max() and min() on it
if (! define('triFalse',0)) trigger_error('Unknown error defining!', E_USER_ERROR);
if (! define('triMaybe',1)) trigger_error('Unknown error defining!', E_USER_ERROR);
if (! define('triTrue', 2)) trigger_error('Unknown error defining!', ... |
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... | #Raku | Raku | my @gaps;
my $previous = 'valid';
for $*IN.lines -> $line {
my ($date, @readings) = split /\s+/, $line;
my @valid;
my $hour = 0;
for @readings -> $reading, $flag {
if $flag > 0 {
@valid.push($reading);
if $previous eq 'invalid' {
@gaps[*-1]{'end'} =... |
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... | #PARI.2FGP | PARI/GP | days=["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"];
gifts=["And 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 ... |
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... | #Logtalk | Logtalk |
:- object(team).
:- threaded.
:- public(start/0).
start :-
threaded((
reader,
writer(0)
)).
reader :-
open('input.txt', read, Stream),
repeat,
read_term(Stream, Term, []),
threaded_notify(term(Term)),
Term ==... |
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... | #Lua | Lua | function ReadFile()
local fp = io.open( "input.txt" )
assert( fp ~= nil )
for line in fp:lines() do
coroutine.yield( line )
end
fp:close()
end
co = coroutine.create( ReadFile )
while true do
local status, val = coroutine.resume( co )
if coroutine.status( co ) == "dead" then break 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... | #AutoHotkey | AutoHotkey | FormatTime, t
MsgBox,% t |
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... | #C.2B.2B | C++ |
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
std::map<char, int> _map;
std::vector<std::string> _result;
size_t longest = 0;
void make_sequence( std::string n ) {
_map.clear();
for( std::string::iterator i = n.begin(); i != n.end(); i++ )
_map.insert(... |
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.
| #Go | Go | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum, n, c := 0, 0, 0
fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:")
fmt.Println(" n cumulative sum")
for _, p := range primes {
n++
sum += p
if rcu.IsP... |
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.
| #Haskell | Haskell | import Data.List (scanl)
import Data.Numbers.Primes (isPrime, primes)
--------------- PRIME SUMS OF FIRST N PRIMES -------------
indexedPrimeSums :: [(Integer, Integer, Integer)]
indexedPrimeSums =
filter (\(_, _, n) -> isPrime n) $
scanl
(\(i, _, m) p -> (succ i, p, p + m))
(0, 0, 0)
primes... |
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... | #Java | Java | import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class SutherlandHodgman extends JFrame {
SutherlandHodgmanPanel panel;
public static void main(String[] args) {
JFrame f = new SutherlandHodgman();
f.setDefaultCloseOpera... |
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... | #Clojure | Clojure | (use '[clojure.set])
(defn symmetric-difference [s1 s2]
(union (difference s1 s2) (difference s2 s1)))
(symmetric-difference #{:john :bob :mary :serena} #{:jim :mary :john :bob}) |
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... | #Common_Lisp | Common Lisp | (set-exclusive-or
(remove-duplicates '(John Serena Bob Mary Serena))
(remove-duplicates '(Jim Mary John Jim Bob))) |
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... | #Python | Python | from itertools import islice, count
def superd(d):
if d != int(d) or not 2 <= d <= 9:
raise ValueError("argument must be integer from 2 to 9 inclusive")
tofind = str(d) * d
for n in count(2):
if tofind in str(d * n ** d):
yield n
if __name__ == '__main__':
for d in range(... |
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.