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/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... | #AutoIt | AutoIt | ; ### USAGE - TESTING PURPOSES ONLY
Local Const $_KELVIN = 21
ConsoleWrite("Kelvin: " & $_KELVIN & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "C") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "F") & @CRLF)
ConsoleWrite("Kelvin: " & Kelvin(21, "R") & @CRLF)
; ### KELVIN TEMPERATURE CONVERSIONS
Func Kelvin($de... |
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
| #Factor | Factor | USING: assocs formatting io kernel math math.primes.factors
math.ranges sequences sequences.extras ;
ERROR: nonpositive n ;
: (tau) ( n -- count )
group-factors values [ 1 + ] map-product ; inline
: tau ( n -- count ) dup 0 > [ (tau) ] [ nonpositive ] if ;
"Number of divisors for integers 1-100:" print nl
"... |
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
| #Fermat | Fermat | Func Tau(t) =
if t<3 then Return(t) else
numdiv:=2;
for q = 2 to t\2 do
if Divides(q, t) then numdiv:=numdiv+1 fi;
od;
Return(numdiv);
fi;
.;
for i = 1 to 100 do
!(Tau(i),' ');
od; |
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
| #Forth | Forth | : divisor_count ( n -- n )
1 >r
begin
dup 2 mod 0=
while
r> 1+ >r
2/
repeat
3
begin
2dup dup * >=
while
1 >r
begin
2dup mod 0=
while
r> 1+ >r
tuck / swap
repeat
2r> * >r
2 +
repeat
drop 1 > if r> 2* else r> then ;
: print_divisor_counts ( n -... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #jq | jq | "\u001B[2J" |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Jsish | Jsish | /* Terminal Control, clear the screen, in Jsish */
function cls() { printf('\u001b[2J'); }
;cls();
/*
=!EXPECTSTART!=
cls() ==> ^[[2Jundefined
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Julia | Julia |
println("\33[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... | #jq | jq | def ternary_nand(a; b):
if a == false or b == false then true
elif a == "maybe" or b == "maybe" then "maybe"
else false
end ;
def ternary_not(a): ternary_nand(a; a);
def ternary_or(a; b): ternary_nand( ternary_not(a); ternary_not(b) );
def ternary_nor(a; b): ternary_not( ternary_or(a;b) );
def terna... |
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... | #Julia | Julia | @enum Trit False Maybe True
const trits = (False, Maybe, True)
Base.:!(a::Trit) = a == False ? True : a == Maybe ? Maybe : False
∧(a::Trit, b::Trit) = a == b == True ? True : (a, b) ∋ False ? False : Maybe
∨(a::Trit, b::Trit) = a == b == False ? False : (a, b) ∋ True ? True : Maybe
⊃(a::Trit, b::Trit) = a == False ||... |
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... | #OCaml | OCaml | let input_line ic =
try Some(input_line ic)
with End_of_file -> None
let fold_input f ini ic =
let rec fold ac =
match input_line ic with
| Some line -> fold (f ac line)
| None -> ac
in
fold ini
let ic = open_in "readings.txt"
let scan line =
Scanf.sscanf line "%s\
\t%f\t%d\t%f\t%d\t%f... |
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... | #J | J | require 'strings' NB. not necessary for versions > j6
days=: ;:'first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth'
gifts=: <;.2 ] 0 : 0
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-swimm... |
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... | #Java | Java | public class TwelveDaysOfChristmas {
final static 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",
"Seven swans a-swimming", "Eight maids a-milking",
"Nine ladies ... |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #Perl | Perl | my %colors = (
red => "\e[1;31m",
green => "\e[1;32m",
yellow => "\e[1;33m",
blue => "\e[1;34m",
magenta => "\e[1;35m",
cyan => "\e[1;36m"
);
$clr = "\e[0m";
print "$colors{$_}$_ text $clr\n" for sort keys %colors;
# the Raku code also works
use feature 'say';
use Term::ANSIColo... |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #Phix | Phix | --
-- demo\rosetta\Coloured_text.exw
-- ==============================
--
with javascript_semantics
text_color(GRAY)
bk_color(BLACK)
printf(1,"Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15\n")
printf(1," -----------------------------------------------\n")
for foreground=0 to... |
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... | #Clojure | Clojure | (use '[clojure.java.io :as io])
(def writer (agent 0))
(defn write-line [state line]
(println line)
(inc state)) |
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... | #Common_Lisp | Common Lisp | (defvar *self*)
(defclass queue ()
((condition :initform (make-condition-variable)
:reader condition-of)
(mailbox :initform '()
:accessor mailbox-of)
(lock :initform (make-lock)
:reader lock-of)))
(defun message (recipient name &rest message)
(with-lock-held ((lock-of r... |
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... | #ooRexx | ooRexx | /* REXX ***************************************************************
* 17.05.2013 Walter Pachl translated from REXX version 2
* nice try? improvements are welcome as I am rather unexperienced
* 18.05.2013 the array may contain a variety of objects!
*******************************************************************... |
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... | #Oracle | Oracle | CREATE SEQUENCE seq_address_pk START BY 100 INCREMENT BY 1
/
CREATE TABLE address (
addrID NUMBER DEFAULT seq_address_pk.NEXTVAL,
street VARCHAR2( 50 ) NOT NULL,
city VARCHAR2( 25 ) NOT NULL,
state VARCHAR2( 2 ) NOT NULL,
zip VARCHAR2( 20 ) NOT NULL,
CONSTRAINT address_pk1 PRIMAR... |
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... | #Ada | Ada | with Ada.Containers.Doubly_Linked_Lists;
with Ada.Text_IO;
procedure Main is
package FIO is new Ada.Text_IO.Float_IO (Float);
type Point is record
X, Y : Float;
end record;
function "-" (Left, Right : Point) return Point is
begin
return (Left.X - Right.X, Left.Y - Right.Y);
end "-";
... |
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... | #Action.21 | Action! | SET EndProg=* |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_XOR is
type Person is (John, Bob, Mary, Serena, Jim);
type Group is array (Person) of Boolean;
procedure Put (Set : Group) is
First : Boolean := True;
begin
for I in Set'Range loop
if Set (I) then
if First then
... |
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... | #C.23 | C# | using System;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
using lbi = System.Collections.Generic.List<System.Numerics.BigInteger[]>;
using static System.Console;
class Program {
// provides 320 bits (90 decimal digits)
struct LI { public UInt64 lo, ml, mh, hi, tp; }
const ... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. NOTES.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OPTIONAL notes ASSIGN TO "NOTES.TXT"
ORGANIZATION LINE SEQUENTIAL
FILE STATUS note-status.
DATA DIVISION.
FILE SECTIO... |
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... | #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Superellipse(INT x0 BYTE y0 REAL POINTER n BYTE a)
INT ARRAY f(100)
REAL ar,xr,tmp1,tmp2,tmp3,one,invn
INT x
IntToReal(1,one)
RealDiv(one,n,invn) ;1/n
IntToReal(a,ar)
Power(ar,n,tmp1) ;a^n
Plot(x0,y0-a)
FOR x=0 TO a
DO
IntToReal(x,xr)
... |
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... | #AWK | AWK |
# syntax: GAWK --bignum -f SYLVESTERS_SEQUENCE.AWK
BEGIN {
start = 1
stop = 10
for (i=start; i<=stop; i++) {
sylvester = (i == 1) ? 2 : sylvester*sylvester-sylvester+1
printf("%2d: %d\n",i,sylvester)
sum += 1 / sylvester
}
printf("\nSylvester sequence %d-%d: sum of reciprocals %3... |
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... | #BASIC | BASIC |
PRINT "10 primeros términos de la sucesión de sylvester:"
PRINT
LET suma = 0
FOR i = 1 TO 10
IF i = 1 THEN
LET sylvester = 2
ELSE
LET sylvester = sylvester*sylvester-sylvester+1
END IF
PRINT i; ": "; sylvester
LET suma = suma + 1 / sylvester
NEXT i
PRINT
PRINT "suma de sus recípr... |
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... | #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
using integer = boost::multiprecision::cpp_int;
using rational = boost::rational<integer>;
integer sylvester_next(const integer& n) {
return n * n - n + 1;
}
int main() {
std::cout << "First 10... |
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... | #Go | Go | package main
import (
"container/heap"
"fmt"
"strings"
)
type CubeSum struct {
x, y uint16
value uint64
}
func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] }
type CubeSumHeap []*CubeSum
func (h CubeSumHeap) Len() int { return len(h) }
func (h CubeSumHeap) Less(i, j int) bool {... |
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'... | #D | D | import std.stdio, std.ascii, std.algorithm, core.memory, permutations2;
/** Uses greedy algorithm of adding another char (or two, or three, ...)
until an unseen perm is formed in the last n chars. */
string superpermutation(in uint n) nothrow
in {
assert(n > 0 && n < uppercase.length);
} out(result) {
// It's... |
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
| #Nim | Nim | import math, strutils
func divcount(n: Natural): Natural =
for i in 1..sqrt(n.toFloat).int:
if n mod i == 0:
inc result
if n div i != i: inc result
var count = 0
var n = 1
var tauNumbers: seq[Natural]
while true:
if n mod divcount(n) == 0:
tauNumbers.add n
inc count
if count == 100: ... |
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
| #Pascal | Pascal | program Tau_number;
{$IFDEF Windows} {$APPTYPE CONSOLE} {$ENDIF}
function CountDivisors(n: NativeUint): integer;
//tau function
var
q, p, cnt, divcnt: NativeUint;
begin
divCnt := 1;
if n > 1 then
begin
cnt := 1;
while not (Odd(n)) do
begin
n := n shr 1;
divCnt+... |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly... | #Wren | Wren | import "/seq" for Stack
import "/dynamic" for Tuple
class Node {
construct new(n) {
_n = n
_index = -1 // -1 signifies undefined
_lowLink = -1
_onStack = false
}
n { _n }
index { _index }
index=(v) { _index = v }
lowLink { _lowLink }
... |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three... | #Raku | Raku | my %*SUB-MAIN-OPTS = :named-anywhere;
unit sub MAIN ( $dict = 'unixdict.txt', :$min-chars = 3, :$mono = False );
my %words;
$dict.IO.slurp.words.map: { .chars < $min-chars ?? (next) !! %words{.uc.comb.sort.join}.push: .uc };
my @teacups;
my %seen;
for %words.values -> @these {
next if !$mono && @these < 2;
... |
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... | #AWK | AWK | # syntax: AWK -f TEMPERATURE_CONVERSION.AWK
BEGIN {
while (1) {
printf("\nKelvin degrees? ")
getline K
if (K ~ /^$/) {
break
}
if (K < 0) {
print("K must be >= 0")
continue
}
printf("K = %.2f\n",K)
printf("C = %.2f\n",K - 273.15)
printf("... |
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
| #FreeBASIC | FreeBASIC | function numdiv( n as uinteger ) as uinteger
dim as uinteger c = 1
for i as uinteger = 1 to (n+1)\2
if n mod i = 0 then c += 1
next i
if n=1 then c-=1
return c
end function
for i as uinteger = 1 to 100
print numdiv(i),
if i mod 10 = 0 then print
next i |
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
| #Go | Go | package main
import "fmt"
func countDivisors(n int) int {
count := 0
i := 1
k := 2
if n%2 == 0 {
k = 1
}
for i*i <= n {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
i += k
}
re... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
println("\u001Bc") // Esc + c
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Lasso | Lasso | local(
esc = decode_base64('Gw==')
)
stdout(#esc + '[2J') |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Logo | Logo | cleartext |
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... | #Alternative_version | Alternative version | # built-in: true, false and missing
using Printf
const tril = (true, missing, false)
@printf("\n%8s | %8s\n", "A", "¬A")
for A in tril
@printf("%8s | %8s\n", A, !A)
end
@printf("\n%8s | %8s | %8s\n", "A", "B", "A ∧ B")
for (A, B) in Iterators.product(tril, tril)
@printf("%8s | %8s | %8s\n", A, B, A & B)... |
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... | #Perl | Perl | use strict;
use warnings;
my $nodata = 0; # Current run of consecutive flags<0 in lines of file
my $nodata_max = -1; # Max consecutive flags<0 in lines of file
my $nodata_maxline = "!"; # ... and line number(s) where it occurs
my $infiles = join ", ", @ARGV;
my $tot_file = 0;
my $num_fi... |
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... | #JavaScript | JavaScript |
var days = [
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth',
];
var gifts = [
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
... |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #PicoLisp | PicoLisp | (unless (member (sys "TERM") '("linux" "xterm" "xterm-color" "xterm-256color" "rxvt"))
(quit "This application requires a colour terminal") )
# Coloured text
(for X '((1 . "Red") (4 . "Blue") (3 . "Yellow"))
(call 'tput "setaf" (car X))
(prinl (cdr X)) )
# Blinking
(out '(tput "-S")
(prinl "setab 1^Jset... |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #PowerShell | PowerShell |
foreach ($color in [enum]::GetValues([System.ConsoleColor])) {Write-Host "$color color." -ForegroundColor $color}
|
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #PureBasic | PureBasic | If OpenConsole()
PrintN("Background color# 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15")
PrintN(" -----------------------------------------------")
Define Foreground, Background
For Foreground = 0 To 15
ConsoleColor(7, 0) ;grey foreground, black background
Print("Foreground ... |
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... | #Crystal | Crystal | File.write("input.txt", "a\nb\nc")
lines = Channel(String).new
spawn do
File.each_line("input.txt") do |line|
lines.send(line)
end
lines.close
end
while line = lines.receive?
puts line
end
File.delete("input.txt") |
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... | #D | D | import std.algorithm, std.concurrency, std.stdio;
void main() {
auto printer = spawn(&printTask, thisTid);
auto f = File("input.txt","r");
foreach (string line; lines(f))
send(printer, line);
send(printer, true); //EOF
auto n = receiveOnly!(int)();
stdout.writefln("\n%d lines printe... |
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... | #Oz | Oz | declare
[Sqlite] = {Module.link ['x-ozlib:/sqlite/Sqlite.ozf']}
DB = {Sqlite.open 'test.db'}
in
try
{Sqlite.exec DB
"CREATE TABLE address ("
#"addrID INTEGER PRIMARY KEY,"
#"addrStreet TEXT NOT NULL,"
#"addrCity TEXT NOT NULL,"
#"addrState TEXT NOT NULL,"
#"addrZIP T... |
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... | #Perl | Perl | use DBI;
my $db = DBI->connect('DBI:mysql:database:server','login','password');
my $statment = <<EOF;
CREATE TABLE `Address` (
`addrID` int(11) NOT NULL auto_increment,
`addrStreet` varchar(50) NOT NULL default '',
`addrCity` varchar(25) NOT NULL default '',
`addrState` char... |
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... | #BBC_BASIC | BBC BASIC | VDU 23,22,200;200;8,16,16,128
VDU 23,23,2;0;0;0;
DIM SubjPoly{(8) x, y}
DIM ClipPoly{(3) x, y}
FOR v% = 0 TO 8 : READ SubjPoly{(v%)}.x, SubjPoly{(v%)}.y : NEXT
DATA 50,150,200,50,350,150,350,300,250,300,200,250,150,350,100,250,100,200
FOR v% = 0 TO 3 : READ ClipPoly{(v%)}.x, ... |
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... | #Aime | Aime | show_sdiff(record u, x)
{
record r;
text s;
r.copy(u);
for (s in x) {
if (r.key(s)) {
r.delete(s);
} else {
r.p_integer(s, 0);
}
}
r.vcall(o_, 0, "\n");
}
new_set(...)
{
record r;
ucall(r_p_integer, 1, r, 0);
r;
}
main(voi... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
int main() {
for (unsigned int d = 2; d <= 9; ++d) {
printf("First 10 super-%u numbers:\n", d);
char digits[16] = { 0 };
memset(digits, '0' + d, d);
mpz_t bignum;
mpz_init(bignum);
for (unsi... |
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... | #Common_Lisp | Common Lisp | (defparameter *notes* "NOTES.TXT")
(defun format-date-time (stream)
(multiple-value-bind (second minute hour date month year) (get-decoded-time)
(format stream "~D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D"
year month date hour minute second)))
(defun notes (args)
(if args
(with-open-file (s *not... |
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... | #D | D | void main(in string[] args) {
import std.stdio, std.file, std.datetime, std.range;
immutable filename = "NOTES.TXT";
if (args.length == 1) {
if (filename.exists && filename.isFile)
writefln("%-(%s\n%)", filename.File.byLine);
} else {
auto f = File(filename, "a+");
... |
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... | #Ada | Ada | with Ada.Numerics.Elementary_Functions;
with SDL.Video.Windows.Makers;
with SDL.Video.Renderers.Makers;
with SDL.Events.Events;
procedure Superelipse is
Width : constant := 600;
Height : constant := 600;
A : constant := 200.0;
B : constant := 200.0;
N : constant := 2.5;
Window ... |
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... | #F.23 | F# |
// Sylvester's sequence: Nigel Galloway. June 7th., 2021
let S10=Seq.unfold(fun(n,g)->printfn "*%A %A" n g; Some(n,(n*g+1I,n*g) ) )(2I,1I)|>Seq.take 10|>List.ofSeq
S10|>List.iteri(fun n g->printfn "%2d -> %A" (n+1) g)
let n,g=S10|>List.fold(fun(n,g) i->(n*i+g,g*i))(0I,1I) in printfn "\nThe sum of the reciprocals of S... |
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... | #Factor | Factor | USING: io kernel lists lists.lazy math prettyprint ;
: lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-by ;
"First 10 elements of Sylvester's sequence:" print
10 lsylvester ltake dup [ . ] leach nl
"Sum of the reciprocals of first 10 elements:" print
0 [ recip + ] foldl . |
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... | #Fermat | Fermat | Array syl[10];
syl[1]:=2;
for i=2 to 10 do syl[i]:=1+Prod<n=1,i-1>[syl[n]] od;
!![syl];
srec:=Sigma<i=1,10>[1/syl[i]];
!!srec; |
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... | #Haskell | Haskell | import Data.List (groupBy, sortOn, tails, transpose)
import Data.Function (on)
--------------------- TAXICAB NUMBERS --------------------
taxis :: Int -> [[(Int, ((Int, Int), (Int, Int)))]]
taxis nCubes =
filter ((> 1) . length) $
groupBy (on (==) fst) $
sortOn fst
[ (fst x + fst y, (x, y))
| (x:t) <-... |
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'... | #Delphi | Delphi |
program Superpermutation_minimisation;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
const
Max = 12;
var
super: ansistring;
pos: Integer;
cnt: TArray<Integer>;
function factSum(n: Integer): Uint64;
begin
var s: Uint64 := 0;
var f := 1;
var x := 0;
while x < n do
begin
inc(x);
f := f... |
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory 'divisors';
my(@x,$n);
do { push(@x,$n) unless $n % scalar(divisors(++$n)) } until 100 == @x;
say "Tau numbers - first 100:\n" .
((sprintf "@{['%5d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr); |
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
| #Phix | Phix | integer n = 1, found = 0
while found<100 do
if remainder(n,length(factors(n,1)))=0 then
found += 1
printf(1,"%,6d",n)
if remainder(found,10)=0 then puts(1,"\n") end if
end if
n += 1
end while
|
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly... | #zkl | zkl | class Tarjan{
// input: graph G = (V, Es)
// output: set of strongly connected components (sets of vertices)
// Ick: class holds global state for strongConnect(), otherwise inert
const INDEX=0, LOW_LINK=1, ON_STACK=2;
fcn init(graph){
var index=0, stack=List(), components=List(),
G=List.c... |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three... | #REXX | REXX | /*REXX pgm finds circular words (length>2), using a dictionary, suppress permutations.*/
parse arg iFID L . /*obtain optional arguments from the CL*/
if iFID==''|iFID=="," then iFID= 'wordlist.10k' /*Not specified? Then use the default.*/
if L==''| L=="," then L= 3 ... |
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... | #BASIC | BASIC |
10 REM TRANSLATION OF AWK VERSION
20 INPUT "KELVIN DEGREES",K
30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM
40 LET C = K - 273.15
50 LET F = K * 1.8 - 459.67
60 LET R = K * 1.8
70 PRINT K; " KELVIN IS EQUIVALENT TO"
80 PRINT C; " DEGREES CELSIUS"
90 PRINT F; " DEGREES FAHRENHEIT"
100 PRINT R; " ... |
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
| #GW-BASIC | GW-BASIC | 10 FOR N = 1 TO 100
20 IF N < 3 THEN T=N: GOTO 70
30 T=2
40 FOR A = 2 TO INT( (N+1)/2 )
50 IF N MOD A = 0 THEN T = T + 1
60 NEXT A
70 PRINT T;
80 IF N MOD 10 = 0 THEN PRINT
90 NEXT 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
| #Haskell | Haskell | tau :: Integral a => a -> a
tau n | n <= 0 = error "Not a positive integer"
tau n = go 0 (1, 1)
where
yo i = (i, i * i)
go r (i, ii)
| n < ii = r
| n == ii = r + 1
| 0 == mod n i = go (r + 2) (yo $ i + 1)
| otherwise = go r (yo $ i + 1)
main = print $ map tau [1..100] |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Lua | Lua | os.execute( "clear" ) |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Pen 14 ' yellow
\\ using form we set characters by rows
\\ this clear the screen
Form 80, 40
\\ magenta for background, all form for vertical scrolling
Cls 5, 0
Print "wait... half second"
Wait 500
\\ clear using background color
Cls
... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["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... | #Kotlin | Kotlin | // version 1.1.2
enum class Trit {
TRUE, MAYBE, FALSE;
operator fun not() = when (this) {
TRUE -> FALSE
MAYBE -> MAYBE
FALSE -> TRUE
}
infix fun and(other: Trit) = when (this) {
TRUE -> other
MAYBE -> if (other == FALSE) FALSE else MAYBE
FALSE -> F... |
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... | #Phix | Phix | -- demo\rosetta\TextProcessing1.exw
with javascript_semantics -- (include version/first of next three lines only)
include readings.e -- global constant lines, or:
--assert(write_lines("readings.txt",lines)!=-1) -- first run, then:
--constant lines = read_lines("readings.txt")
include builtins\timedate.e
integer cou... |
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... | #jq | jq | [ "one", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "eleven", "twelve"] as $cardinals
| [ "first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"] as $ordinals
| [ "a partridge in a pear tree.", "turtle doves", "French hen... |
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... | #Jsish | Jsish | #!/usr/bin/env jsish
"use strict";
/* Twelve Days Of Christmas, in Jsish */
var days = [
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth'
];
var gifts = [
"A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
... |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #Python | Python |
from colorama import init, Fore, Back, Style
init(autoreset=True)
print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
print Back.BLUE + Fore.YELLOW + "What a cute console!"
print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL)
print Fore.YELLOW + "Rosetta Code!"
print Fore... |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #Racket | Racket |
#lang racket
;; Utility interfaces to the low-level command
(define (capability? cap) (system (~a "tput "cap" > /dev/null 2>&1")))
(define (tput . xs) (system (apply ~a 'tput " " (add-between xs " "))) (void))
(define (colorterm?) (and (capability? 'setaf) (capability? 'setab)))
(define color-map '([black 0] [red 1... |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if ... | #Raku | Raku | use Terminal::ANSIColor;
say colored('RED ON WHITE', 'bold red on_white');
say colored('GREEN', 'bold green');
say colored('BLUE ON YELLOW', 'bold blue on_yellow');
say colored('MAGENTA', 'bold magenta');
say colored('CYAN ON RED', 'bold cyan on_red');
say colored('YELLOW', 'bold yellow'); |
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... | #Delphi | Delphi |
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes, Windows;
type
EThreadStackFinalized = class(Exception);
PLine = ^TLine;
TLine = record
Text: string;
end;
TThreadQueue = class
private
FFinalized: Boolean;
FQueue: THandle;
public
constructor Create;
destructor ... |
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... | #Phix | Phix | without js -- (file i/o)
include pSQLite.e
constant sqlcode = """
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL)"""
sqlite3 db = sqlite3_open("address.sqlite")
integer res = sqlite3_exec(... |
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... | #PHP.2BSQLite | PHP+SQLite | <?php
$db = new SQLite3(':memory:');
$db->exec("
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... | #PicoLisp | PicoLisp | (class +Adr +Entity)
(rel nm (+Sn +Idx +String)) # Name [Soundex index]
(rel str (+String)) # Street
(rel zip (+Ref +String)) # ZIP [Non-unique index]
(rel cit (+Fold +Idx +String)) # City [Folded substring index]
(rel st (+String)) # State
(rel te... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { double x, y; } vec_t, *vec;
inline double dot(vec a, vec b)
{
return a->x * b->x + a->y * b->y;
}
inline double cross(vec a, vec b)
{
return a->x * b->y - a->y * b->x;
}
inline vec vsub(vec a, vec b, vec res)
{
res->x = a->x - b->x;
r... |
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... | #ALGOL_68 | ALGOL 68 | # symetric difference using associative arrays to represent the sets #
# include the associative array code for string keys and values #
PR read "aArray.a68" PR
# adds the elements of s to the associative array a, #
# the elements will have empty strings for values ... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <sstream>
#include <vector>
uint64_t ipow(uint64_t base, uint64_t exp) {
uint64_t result = 1;
while (exp) {
if (exp & 1) {
result *= base;
}
exp >>= 1;
base *= base;
}
return result;
}
int main() {
using namespace std;
... |
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... | #Delphi | Delphi | program notes;
{$APPTYPE CONSOLE}
uses
Classes,
SysUtils,
IOUtils;
const
FILENAME = 'NOTES.TXT';
TAB = #9;
var
sw: TStreamWriter;
i : integer;
begin
if ParamCount = 0 then
begin
if TFile.Exists(FILENAME) then
write(TFile.ReadAllText(FILENAME));
end
else
begin
if TFile.Exi... |
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... | #AutoHotkey | AutoHotkey | n := 2.5
a := 200
b := 200
SuperEllipse(n, a, b)
return
SuperEllipse(n, a, b){
global
pToken := Gdip_Startup()
π := 3.141592653589793, oCoord := [], oX := [], oY := []
nn := 2/n
loop 361
{
t := (A_Index-1) * π/180
; https://en.wikipedia.org/wiki/Superellipse
x := abs... |
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... | #Go | Go | package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
two := big.NewInt(2)
next := new(big.Int)
sylvester := []*big.Int{two}
prod := new(big.Int).Set(two)
count := 1
for count < 10 {
next.Add(prod, one)
sylvester = append(sylvester, new(big.I... |
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... | #Haskell | Haskell | sylvester :: [Integer]
sylvester = map s [0 ..]
where
s 0 = 2
s n = succ $ foldr ((*) . s) 1 [0 .. pred n]
main :: IO ()
main = do
putStrLn "First 10 elements of Sylvester's sequence:"
putStr $ unlines $ map show $ take 10 sylvester
putStr "\nSum of reciprocals by sum over map: "
print $ sum $ map... |
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... | #J | J | cubes=: 3^~1+i.100 NB. first 100 cubes
triples=: /:~ ~. ,/ (+ , /:~@,)"0/~cubes NB. ordered pairs of cubes (each with their sum)
candidates=: ;({."#. <@(0&#`({.@{.(;,)<@}."1)@.(1<#))/. ])triples
NB. we just want the first 25 taxicab numbers
25{.(,.~ <@>:@i.@#) candidates
┌──┬──────┬────────────┬─────────────┐
│1 │172... |
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'... | #Elixir | Elixir | defmodule Superpermutation do
def minimisation(1), do: [1]
def minimisation(n) do
Enum.chunk(minimisation(n-1), n-1, 1)
|> Enum.reduce({[],nil}, fn sub,{acc,last} ->
if Enum.uniq(sub) == sub do
i = if acc==[], do: 0, else: Enum.find_index(sub, &(&1==last)) + 1
{acc ++ (Enum.drop(sub,i)... |
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'... | #FreeBASIC | FreeBASIC | ' version 28-06-2018
' compile with: fbc -s console
Function superpermsize(n As UInteger) As UInteger
Dim As UInteger x, y, sum, fac
For x = 1 To n
fac = 1
For y = 1 To x
fac *= y
Next
sum += fac
Next
Function = sum
End Function
Function superperm(n ... |
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
| #PILOT | PILOT | T :1
C :n=2
C :seen=1
C :max=100
*number
C :c=1
C :i=1
*divisor
C (n=i*(n/i)):c=c+1
C :i=i+1
J (i<=n/2):*divisor
T (n=c*(n/c)):#n
C (n=c*(n/c)):seen=seen+1
C :n=n+1
J (seen<max):*number
E : |
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
| #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
/* PRINT NUMBER RIGHT-ALIGNED IN 7 POSITIONS */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL (' .....$');
... |
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
| #PureBasic | PureBasic | OpenConsole()
Procedure.i numdiv(n)
c=2
For i=2 To (n+1)/2 : If n%i=0 : c+1 : EndIf : Next
ProcedureReturn c
EndProcedure
Procedure.b istau(n)
If n=1 : ProcedureReturn #True : EndIf
If n%numdiv(n)=0 : ProcedureReturn #True : Else : ProcedureReturn #False : EndIf
EndProcedure
c=0 : i=1
While c<100
If i... |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three... | #Rust | Rust | use std::collections::BTreeSet;
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, BufRead};
use std::iter::FromIterator;
fn load_dictionary(filename: &str) -> std::io::Result<BTreeSet<String>> {
let file = File::open(filename)?;
let mut dict = BTreeSet::new();
for line in io::BufReader... |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three... | #Swift | Swift | import Foundation
func loadDictionary(_ path: String) throws -> Set<String> {
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
return Set<String>(contents.components(separatedBy: "\n").filter{!$0.isEmpty})
}
func rotate<T>(_ array: inout [T]) {
guard array.count > 1 else ... |
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... | #BASIC256 | BASIC256 |
do
print "Kelvin degrees (>=0): ";
input K
until K>=0
print "K = " + string(K)
print "C = " + string(K - 273.15)
print "F = " + string(K * 1.8 - 459.67)
print "R = " + string(K * 1.8)
|
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... | #BBC_BASIC | BBC BASIC |
REPEAT
INPUT "Kelvin degrees (>=0): " K
UNTIL K>=0
@%=&20208
PRINT '"K = " K
PRINT "C = " K - 273.15
PRINT "F = " K * 1.8 - 459.67
PRINT "R = " K * 1.8
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
| #J | J | tau =: [:+/0=>:@i.|]
echo tau"0 [5 20$>:i.100
exit '' |
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
| #Java | Java | public class TauFunction {
private static long divisorCount(long n) {
long total = 1;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1) {
++total;
}
// Odd prime factors up to the square root
for (long p = 3; p * p <= n; p += 2) {
lo... |
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.