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/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... | #Julia | Julia | using Printf, DataStructures, IterTools
function findtaxinumbers(nmax::Integer)
cube2n = Dict{Int,Int}(x ^ 3 => x for x in 0:nmax)
sum2cubes = DefaultDict{Int,Set{NTuple{2,Int}}}(Set{NTuple{2,Int}})
for ((c1, _), (c2, _)) in product(cube2n, cube2n)
if c1 ≥ c2
push!(sum2cubes[c1 + c2], ... |
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'... | #J | J | approxmin=:3 :0
seqs=. y{~(A.&i.~ !)#y
r=.{.seqs
seqs=.}.seqs
while.#seqs do.
for_n. i.-#y do.
tail=. (-n){. r
b=. tail -:"1 n{."1 seqs
if. 1 e.b do.
j=. b i.1
r=. r, n}.j{seqs
seqs=. (<<<j) { seqs
break.
end.
end.
end.
r
) |
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'... | #Java | Java | import static java.util.stream.IntStream.rangeClosed;
public class Test {
final static int nMax = 12;
static char[] superperm;
static int pos;
static int[] count = new int[nMax];
static int factSum(int n) {
return rangeClosed(1, n)
.map(m -> rangeClosed(1, m).reduce(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
| #REXX | REXX | /*REXX pgm displays N tau numbers, an integer divisible by the # of its divisors). */
parse arg n cols . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 100 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 10 ... |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
double kelvinToCelsius(double k){
return k - 273.15;
}
double kelvinToFahrenheit(double k){
return k * 1.8 - 459.67;
}
double kelvinToRankine(double k){
return k * 1.8;
}
void convertKelvin(double kelvin) {
printf("K %.2f\n", kelvin);
printf("C %.2f\n", k... |
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
| #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
echo "Count of divisors for the first 100 positive integers:"
for i in 1..100:
stdout.write ($divcount(i)).align(3)
if i mod 20 == 0: echo() |
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
| #PARI.2FGP | PARI/GP | vector(100,X,numdiv(X)) |
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
| #Pascal | Pascal | program tauFunction(output);
type
{ name starts with `integer…` to facilitate sorting in documentation }
integerPositive = 1..maxInt value 1;
{ the `value …` will initialize all variables to this value }
{ returns Boolean value of the expression divisor ∣ dividend ----------- }
function divides(
protected divi... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Phix | Phix | clear_screen()
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #PicoLisp | PicoLisp | (call 'clear) |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Pike | Pike | int main() {
Process.system("clear");
return 0;
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #PowerShell | PowerShell | Clear-Host |
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... | #Nim | Nim | type Trit* = enum ttrue, tmaybe, tfalse
proc `$`*(a: Trit): string =
case a
of ttrue: "T"
of tmaybe: "?"
of tfalse: "F"
proc `not`*(a: Trit): Trit =
case a
of ttrue: tfalse
of tmaybe: tmaybe
of tfalse: ttrue
proc `and`*(a, b: Trit): Trit =
const t: array[Trit, array[Trit, Trit]] =
[ [ttrue, ... |
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... | #OCaml | OCaml | type trit = True | False | Maybe
let t_not = function
| True -> False
| False -> True
| Maybe -> Maybe
let t_and a b = match (a,b) with
| (True,True) -> True
| (False,_) | (_,False) -> False
| _ -> Maybe
let t_or a b = t_not (t_and (t_not a) (t_not b))
let t_eq a b = match (a,b) with
| (True,... |
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... | #PowerShell | PowerShell | $file = '.\readings.txt'
$lines = Get-Content $file # $args[0]
$valid = $true
$startDate = $currStart = $endDate = ''
$startHour = $endHour = $currHour = $max = $currMax = $total = $readings = 0
$task = @()
foreach ($var in $lines) {
$date, $rest = [regex]::Split($var,'\s+')
$reject = $accept = $sum = $cnt = 0
... |
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... | #Lua | Lua |
local days = {
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth',
'tenth', 'eleventh', 'twelfth',
}
local 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 ... | #Sidef | Sidef | var a = frequire('Term::ANSIColor');
say a.colored('RED ON WHITE', 'bold red on_white');
say a.colored('GREEN', 'bold green');
say a.colored('BLUE ON YELLOW', 'bold blue on_yellow');
say a.colored('MAGENTA', 'bold magenta');
say a.colored('CYAN ON RED', 'bold cyan on_red');
say a.colored('YELLOW', 'bold yellow'); |
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 ... | #Tcl | Tcl | # Utility interfaces to the low-level command
proc capability cap {expr {![catch {exec tput -S << $cap}]}}
proc colorterm {} {expr {[capability setaf] && [capability setab]}}
proc tput args {exec tput -S << $args >/dev/tty}
array set color {black 0 red 1 green 2 yellow 3 blue 4 magenta 5 cyan 6 white 7}
proc 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... | #F.23 | F# |
open System.IO
type Msg =
| PrintLine of string
| GetCount of AsyncReplyChannel<int>
let printer =
MailboxProcessor.Start(fun inbox ->
let rec loop count =
async {
let! msg = inbox.Receive()
match msg with
| PrintLine(s) ->
... |
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... | #Run_BASIC | Run BASIC | sqliteconnect #mem, ":memory:" ' make handle #mem
mem$ = "
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)"
#mem execute(mem$) |
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... | #SAS | SAS |
PROC SQL;
CREATE TABLE ADDRESS
(
ADDRID CHAR(8)
,STREET CHAR(50)
,CITY CHAR(25)
,STATE CHAR(2)
,ZIP CHAR(20)
)
;QUIT;
|
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... | #Scheme | Scheme |
(use sql-de-lite)
(define *db* (open-database "addresses"))
(exec ; create and run the SQL statement
(sql *db*
"CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZI... |
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... | #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
with Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones;
with Ada.Text_Io; use Ada.Text_Io;
procedure System_Time is
Now : Time := Clock;
begin
Put_line(Image(Date => Now, Time_Zone => -7*60));
end System_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... | #Aime | Aime | date d;
d_now(d);
o_form("~-/f2/-/f2/ /f2/:/f2/:/f2/\n", d_year(d), d_y_month(d), d_m_day(d),
d_d_hour(d), d_h_minute(d), d_m_second(d)); |
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... | #Aime | Aime | text
next(text s)
{
integer c, e, l;
index v;
data d;
l = ~s;
while (l) {
v[-s[l -= 1]] += 1;
}
for (c, e in v) {
b_form(d, "%d%c", e, -c);
}
return d;
}
integer
depth(text s, integer i, record r)
{
integer d;
d = 0;
r_j_integer(d, r, s);
if ... |
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.
| #Arturo | Arturo | print (pad "index" 6) ++ " | " ++
(pad "prime" 6) ++ " | " ++
(pad "prime sum" 11)
print "------------------------------"
s: 0
idx: 0
loop 2..999 'n [
if prime? n [
idx: idx + 1
s: s + n
if prime? s ->
print (pad to :string idx 6) ++ " | " ++
(pad ... |
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.
| #AWK | AWK |
# syntax: GAWK -f SUMMARIZE_PRIMES.AWK
BEGIN {
start = 1
stop = 999
for (i=start; i<=stop; i++) {
if (is_prime(i)) {
count1++
sum += i
if (is_prime(sum)) {
printf("the sum of %3d primes from primes 2-%-3s is %5d which is also prime\n",count1,i,sum)
count2+... |
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... | #Elixir | Elixir | defmodule SutherlandHodgman do
defp inside(cp1, cp2, p), do: (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
defp intersection(cp1, cp2, s, e) do
{dcx, dcy} = {cp1.x-cp2.x, cp1.y-cp2.y}
{dpx, dpy} = {s.x-e.x, s.y-e.y}
n1 = cp1.x*cp2.y - cp1.y*cp2.x
n2 = s.x*e.y - s.y*e.x
n3 = 1.0 / (dcx*... |
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... | #Fortran | Fortran |
module SutherlandHodgmanUtil
! functions and type needed for Sutherland-Hodgman algorithm
! -------------------------------------------------------- !
type polygon
!type for polygons
! when you define a polygon, the first and the last vertices have to be the same
integer :: n
double precisio... |
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... | #AWK | AWK |
# syntax: GAWK -f SYMMETRIC_DIFFERENCE.AWK
BEGIN {
load("John,Bob,Mary,Serena",A)
load("Jim,Mary,John,Bob",B)
show("A \\ B",A,B)
show("B \\ A",B,A)
printf("symmetric difference: ")
for (i in C) {
if (!(i in A && i in B)) {
printf("%s ",i)
}
}
printf("\n")
exit(0... |
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... | #J | J | superD=: 1 e. #~@[ E. 10 #.inv ([ * ^~)&x:
assert 3 superD 753
assert -. 2 superD 753
2 3 4 5 6 ,. _ 10 {. I. 2 3 4 5 6 superD&>/i.1e6
2 19 31 69 81 105 106 107 119 127 131
3 261 462 471 481 558 753 1036 1046 1471 1645
4 1168 4972 7423 7... |
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... | #Java | Java |
import java.math.BigInteger;
public class SuperDNumbers {
public static void main(String[] args) {
for ( int i = 2 ; i <= 9 ; i++ ) {
superD(i, 10);
}
}
private static final void superD(int d, int max) {
long start = System.currentTimeMillis();
String test... |
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... | #Factor | Factor | #! /usr/bin/env factor
USING: kernel calendar calendar.format io io.encodings.utf8 io.files
sequences command-line namespaces ;
command-line get [
"notes.txt" utf8 file-contents print
] [
" " join "\t" prepend
"notes.txt" utf8 [
now timestamp>ymdhms print
print flush
] with-file-append... |
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... | #Fantom | Fantom |
class Notes
{
public static Void main (Str[] args)
{
notesFile := File(`notes.txt`) // the backticks make a URI
if (args.isEmpty)
{
if (notesFile.exists)
{
notesFile.eachLine |line| { echo (line) }
}
}
else
{
// notice the following uses a block so the 'pri... |
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... | #Go | Go | package main
import (
"github.com/fogleman/gg"
"math"
)
/* assumes a and b are always equal */
func superEllipse(dc *gg.Context, n float64, a int) {
hw := float64(dc.Width() / 2)
hh := float64(dc.Height() / 2)
// calculate y for each x
y := make([]float64, a+1)
for x := 0; x <= a; x++ ... |
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... | #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
' [ 2 ] 9 times [ dup -1 peek dup 2 ** swap - 1+ join ]
dup witheach [ echo cr ] cr
0 n->v rot witheach [ n->v 1/v v+ ] 222 point$ echo$ |
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... | #Raku | Raku | my @S = {1 + [*] @S[^($++)]} … *;
put 'First 10 elements of Sylvester\'s sequence: ', @S[^10];
say "\nSum of the reciprocals of first 10 elements: ", sum @S[^10].map: { FatRat.new: 1, $_ }; |
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... | #REXX | REXX | /*REXX pgm finds N terms of the Sylvester's sequence & the sum of the their reciprocals.*/
parse arg n . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 10 /*Not specified? Then use the default.*/
numeric digits max(9, 2**(n-7) * 13 + 1) ... |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Kotlin | Kotlin | // version 1.0.6
import java.util.PriorityQueue
class CubeSum(val x: Long, val y: Long) : Comparable<CubeSum> {
val value: Long = x * x * x + y * y * y
override fun toString() = String.format("%4d^3 + %3d^3", x, y)
override fun compareTo(other: CubeSum) = value.compareTo(other.value)
}
class SumIt... |
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'... | #Julia | Julia | const nmax = 12
function r!(n, s, pos, count)
if n == 0
return false
end
c = s[pos + 1 - n]
count[n + 1] -= 1
if count[n + 1] == 0
count[n + 1] = n
if r!(n - 1, s, pos, count) == 0
return false
end
end
s[pos + 1] = c
pos += 1
true
end
f... |
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'... | #Kotlin | Kotlin | // version 1.1.2
const val MAX = 12
var sp = CharArray(0)
val count = IntArray(MAX)
var pos = 0
fun factSum(n: Int): Int {
var s = 0
var x = 0
var f = 1
while (x < n) {
f *= ++x
s += f
}
return s
}
fun r(n: Int): Boolean {
if (n == 0) return false
val c = sp[p... |
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
| #Ring | Ring |
see "The first 100 tau numbers are:" + nl + nl
n = 1
num = 0
limit = 100
while num < limit
n = n + 1
tau = 0
for m = 1 to n
if n%m = 0
tau = tau + 1
ok
next
if n%tau = 0
num = num + 1
if num%10 = 1
see nl
ok
... |
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
| #Ruby | Ruby | require 'prime'
taus = Enumerator.new do |y|
(1..).each do |n|
num_divisors = n.prime_division.inject(1){|prod, n| prod *= n[1] + 1 }
y << n if n % num_divisors == 0
end
end
p taus.take(100)
|
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... | #C.23 | C# | using System;
namespace TemperatureConversion
{
class Program
{
static Func<double, double> ConvertKelvinToFahrenheit = x => (x * 1.8) - 459.67;
static Func<double, double> ConvertKelvinToRankine = x => x * 1.8;
static Func<double, double> ConvertKelvinToCelsius = x => x = 273.13;
... |
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory 'divisors';
my @x;
push @x, scalar divisors($_) for 1..100;
say "Tau function - first 100:\n" .
((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr); |
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
| #Phix | Phix | for i=1 to 100 do
printf(1,"%3d",{length(factors(i,1))})
if remainder(i,20)=0 then puts(1,"\n") end if
end for
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #ProDOS | ProDOS | clearscurrentscreentext |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Python | Python | import os
os.system("clear") |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Quackery | Quackery | [ $ &print("\33[2J",end='')& python ] is clearscreen |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #R | R | cat("\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... | #ooRexx | ooRexx |
tritValues = .array~of(.trit~true, .trit~false, .trit~maybe)
tab = '09'x
say "not operation (\)"
loop a over tritValues
say "\"a":" (\a)
end
say
say "and operation (&)"
loop aa over tritValues
loop bb over tritValues
say (aa" & "bb":" (aa&bb))
end
end
say
say "or operation (|)"
loop aa over ... |
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... | #PureBasic | PureBasic | #TASK="Text processing/1"
Define File$, InLine$, Part$, i, Out$, ErrEnds$, Errcnt, ErrMax
Define lsum.d, tsum.d, rejects, val.d, readings
File$=OpenFileRequester(#TASK,"readings.txt","",0)
If OpenConsole() And ReadFile(0,File$)
While Not Eof(0)
InLine$=ReadString(0)
For i=1 To 1+2*24
Part$=StringField... |
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... | #MAD | MAD | NORMAL MODE IS INTEGER
THROUGH VERSE, FOR I=1, 1, I.G.12
PRINT FORMAT XMS,ORD(I)
PRINT FORMAT TLV
TRANSFER TO GIFT(13-I)
GIFT(1) PRINT FORMAT G12
GIFT(2) PRINT FORMAT G11
GIFT(3) PRINT FORMAT G10
GIFT(4) PRINT FORMAT G9
GIFT(5) PRINT FORM... |
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... | #Maple | Maple | gifts := ["Twelve drummers drumming",
"Eleven pipers piping", "Ten lords a-leaping",
"Nine ladies dancing", "Eight maids a-milking",
"Seven swans a-swimming", "Six geese a-laying",
"Five golden rings", "Four calling birds",
"Three french hens", "Two turtle doves and", "A partridge in a pear tree"]:
days := ["... |
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 ... | #TPP | TPP | --color red
This is red
--color green
This is green
--color blue
This is blue
--color cyan
This is cyan
--color magenta
This is magenta
--color yellow
This is yellow |
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 ... | #True_BASIC | True BASIC | FOR n = 1 TO 15
SET COLOR n
PRINT "Rosetta Code"
NEXT n
END |
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 ... | #UNIX_Shell | UNIX Shell | #!/bin/sh
# Check if the terminal supports colour
# We should know from the TERM evironment variable whether the system
# is comfigured for a colour terminal or not, but we can also check the
# tput utility to check the terminal capability records.
COLORS=8 # Assume initially that the system supports eight colou... |
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 ... | #Wren | Wren | import "timer" for Timer
var colors = ["Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"]
// display words using 'bright' colors
for (i in 1..7) System.print("\e[%(30+i);1m%(colors[i])") // red to white
Timer.sleep(3000) // wait for 3 seconds
System.write("\e[47m") // set background c... |
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... | #Forth | Forth | \
\ co.fs Coroutines by continuations.
\
\ * Circular Queue. Capacity is power of 2.
\
VARIABLE HEAD VARIABLE TAIL
128 CELLS CONSTANT CQ#
\ * align by queue capacity
HERE DUP
CQ# 1- INVERT AND CQ# +
SWAP - ALLOT
\
HERE CQ# ALLOT CONSTANT START
\
: ADJUST ( -- ) [ CQ# 1- ]L AND START + ;
: PUT ( n-- )... |
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... | #Go | Go | package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
lines := make(chan string)
count := make(chan int)
go func() {
c := 0
for l := range lines {
fmt.Println(l)
c++
}
count <- c
}()
f, err := os.Open("input.txt")... |
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... | #Sidef | Sidef | require('DBI');
var db = %s'DBI'.connect('DBI:mysql:database:server','login','password');
var statment = <<'EOF';
CREATE TABLE `Address` (
`addrID` int(11) NOT NULL auto_increment,
`addrStreet` varchar(50) NOT NULL default '',
`addrCity` varchar(25) NOT NULL default '',
`addrSt... |
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... | #SQL_PL | SQL PL |
CREATE TABLE Address (
addrID INTEGER generated BY DEFAULT AS IDENTITY,
addrStreet VARCHAR(50) NOT NULL,
addrCity VARCHAR(25) NOT NULL,
addrState CHAR(2) NOT NULL,
addrZIP CHAR(10) 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... | #SQLite | SQLite |
CREATE TABLE address_USA (
address_ID INTEGER PRIMARY KEY,
address_Street TEXT,
address_City TEXT,
address_State TEXT,
address_Zip INTEGER
);
|
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... | #ALGOL_68 | ALGOL 68 | FORMAT time repr = $"year="4d,", month="2d,", day="2d,", hours="2d,", \
minutes="2d,", seconds="2d,", day of week="d,", \
daylight-saving-time flag="dl$;
printf((time repr, local time));
printf((time repr, utc time)) |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #AutoHotkey | AutoHotkey |
; The following directives and commands speed up execution:
#NoEnv
SetBatchlines -1
ListLines Off
Process, Priority,, high
iterations := 0, seed := "Seeds: "
Loop 1000000
If (newIterations := CountSubString(list := ListSequence(A_Index), "`n")) > iterations
iterations := newiterations
,final := "`nIterations... |
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 | C | #include <stdbool.h>
#include <stdio.h>
bool is_prime(int n) {
int i = 5;
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
while (i * i <= n) {
if (n % i == 0) {
return false;
}
... |
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... | #FreeBASIC | FreeBASIC |
Type Point
As Double x,y
End Type
Type Line
As Point s,f'start/finish
End Type
Function isleft(L As Line,p As Point) As Long
Return -Sgn((L.s.x-L.f.x)*(p.y-L.f.y)-(p.x-L.f.x)*(L.s.y-L.f.y))
End Function
Function segmentintersections(L1 As Line,L2 As Line) As Long
If isleft(L2,L1.s) = 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... | #BBC_BASIC | BBC BASIC | DIM list$(4)
list$() = "Bob", "Jim", "John", "Mary", "Serena"
setA% = %11101
PRINT "Set A: " FNlistset(list$(), setA%)
setB% = %01111
PRINT "Set B: " FNlistset(list$(), setB%)
REM Compute symmetric difference:
setC% = setA% EOR setB%
PRINT '"Symmetric difference... |
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... | #Bracmat | Bracmat | (SymmetricDifference=
A B x symdiff
. !arg:(?A.?B)
& :?symdiff
& ( !A !B
: ?
( %@?x
& ( !A:? !x ?&!B:? !x ?
| !symdiff:? !x ?
| !symdiff !x:?symdiff
)
& ~
)
?
| !symdiff
)); |
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... | #jq | jq | # To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
# Input is $d, the number of consecutive digits, 2 <= $d <= 9
# $max is the number of superd numbers to be emitted.
def superd($number):
. as $d
| tostring as $s
| ($s * $d) as ... |
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... | #Julia | Julia | function superd(N)
println("First 10 super-$N numbers:")
count, j = 0, BigInt(3)
target = Char('0' + N)^N
while count < 10
if occursin(target, string(j^N * N))
count += 1
print("$j ")
end
j += 1
end
println()
end
for n in 2:9
@time superd(n)
... |
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... | #Kotlin | Kotlin | import java.math.BigInteger
fun superD(d: Int, max: Int) {
val start = System.currentTimeMillis()
var test = ""
for (i in 0 until d) {
test += d
}
var n = 0
var i = 0
println("First $max super-$d numbers:")
while (n < max) {
i++
val value: Any = BigInteger.val... |
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... | #Forth | Forth | vocabulary note-words
get-current also note-words definitions
\ -- notes.txt
variable file
: open s" notes.txt" r/w open-file if
s" notes.txt" r/w create-file throw then file ! ;
: appending file @ file-size throw file @ reposition-file throw ;
: write file @ write-file throw ;
: close ... |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then al... | #Fortran | Fortran |
program notes
implicit none
integer :: i, length, iargs, lun, ios
integer,dimension(8) :: values
character(len=:),allocatable :: arg
character(len=256) :: line
character(len=1),parameter :: tab=char(9)
iargs = command_argument_count()
open(file='notes.txt',newunit=lun,ac... |
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... | #Haskell | Haskell | {-# LANGUAGE OverloadedStrings, RankNTypes #-}
import Reflex
import Reflex.Dom
import Data.Text (Text, pack, unpack)
import Data.Map (Map, fromList, empty)
import Text.Read (readMaybe)
width = 600
height = 500
type Point = (Float,Float)
type Segment = (Point,Point)
data Ellipse = Ellipse {a :: Float, b :: Float,... |
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... | #Ruby | Ruby | def sylvester(n) = (1..n).reduce(2){|a| a*a - a + 1 }
(0..9).each {|n| puts "#{n}: #{sylvester n}" }
puts "
Sum of reciprocals of first 10 terms:
#{(0..9).sum{|n| 1.0r / sylvester(n)}.to_f }"
|
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... | #Scheme | Scheme | (define sylvester
(lambda (x)
(if (= x 1)
2
(let ((n (sylvester (- x 1)))) (- (* n n) n -1)))))
(define list (map sylvester '(1 2 3 4 5 6 7 8 9 10)))
(print list)
(newline)
(print (apply + (map / list))) |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
include "bigrat.s7i";
const func bigInteger: nextSylvester (in bigInteger: prev) is
return prev * prev - prev + 1_;
const proc: main is func
local
var bigInteger: number is 2_;
var bigRational: reciprocalSum is 0_ / 1_;
var integer: n is 0;
begin... |
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... | #Sidef | Sidef | func sylvester_sequence(n) {
1..n -> reduce({|a| a*(a-1) + 1 }, 2)
}
say "First 10 terms in Sylvester's sequence:"
10.of(sylvester_sequence).each_kv{|k,v| '%2s: %s' % (k,v) -> say }
say "\nSum of reciprocals of first 10 terms: "
say 10.of(sylvester_sequence).sum {|n| 1/n }.as_dec(230) |
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... | #Lua | Lua | sums, taxis, limit = {}, {}, 1200
for i = 1, limit do
for j = 1, i-1 do
sum = i^3 + j^3
sums[sum] = sums[sum] or {}
table.insert(sums[sum], i.."^3 + "..j.."^3")
end
end
for k,v in pairs(sums) do
if #v > 1 then table.insert(taxis, { sum=k, num=#v, terms=table.concat(v," = ") }) end
end
table.sort(taxis... |
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'... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[OverlapDistance, ConstructDistances]
OverlapDistance[{s1_List, s2_List}] := OverlapDistance[s1, s2]
OverlapDistance[s1_List, s2_List] := Module[{overlaprange, overlap, l},
overlaprange = {Min[Length[s1], Length[s2]], 0};
l = LengthWhile[Range[Sequence @@ overlaprange, -1], Take[s1, -#] =!= Take[s2, #] &];
... |
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'... | #Nim | Nim | import strformat
const MAX = 12
var super: seq[char] = @[]
var pos: int
var cnt: array[MAX, int]
proc factSum(n: int): int =
var s, x = 0
var f = 1
while x < n:
inc x
f *= x
inc s, f
s
proc r(n: int): bool =
if n == 0:
return false
var c = super[pos - n]
dec cnt[n]
if cnt[n] == ... |
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'... | #Objeck | Objeck | class SuperPermutation {
@super : static : Char[];
@pos : static : Int;
@cnt : static : Int[];
function : Main(args : String[]) ~ Nil {
max := 12;
@cnt := Int->New[max];
@super := Char->New[0];
for(n := 0; n < max; n += 1;) {
"superperm({$n}) "->Print();
SuperPerm(n);
len :... |
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
| #Rust | Rust |
/// Gets all divisors of a number, including itself
fn get_divisors(n: u32) -> Vec<u32> {
let mut results = Vec::new();
for i in 1..(n / 2 + 1) {
if n % i == 0 {
results.push(i);
}
}
results.push(n);
results
}
fn is_tau_number(i: u32) -> bool {
0 == i % get_divi... |
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
| #Sidef | Sidef | func is_tau_number(n) {
n % n.sigma0 == 0
}
say is_tau_number.first(100).join(' ') |
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
| #Swift | Swift | import Foundation
// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
// Deal with powers of 2 first
while (n & 1) == 0 {
total += 1
n >>= 1
}
// Odd prime factors up to the square root
var p = 3
whi... |
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... | #C.2B.2B | C++ |
#include <iostream>
#include <iomanip>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
class converter
{
public:
converter() : KTC( 273... |
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
| #PL.2FI | PL/I | taufunc: procedure options(main);
tau: procedure(nn) returns(fixed);
declare (n, nn, tot, pf, cnt) fixed;
tot = 1;
do n=nn repeat(n/2) while(mod(n,2)=0);
tot = tot + 1;
end;
do pf=3 repeat(pf+2) while(pf*pf<=n);
do cnt=1 repeat(cnt+1) while(mod(n,pf)=0);
... |
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
| #PL.2FM | PL/M | 100H:
/* CP/M BDOS FUNCTIONS */
BDOS: PROCEDURE(F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; GO TO 0; END EXIT;
PR$CHAR: PROCEDURE(C); DECLARE C BYTE; CALL BDOS(2,C); END PR$CHAR;
PR$STR: PROCEDURE(S); DECLARE S ADDRESS; CALL BDOS(9,S); END PR$STR;
/* PRINT BYTE IN A 3-CHAR COLUMN */
PRINT3... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Racket | Racket |
#lang racket
(require (planet neil/charterm:3:0))
(with-charterm
(void (charterm-clear-screen)))
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Raku | Raku | sub clear { print qx[clear] }
clear; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Retro | Retro | 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... | #Pascal | Pascal | Program TernaryLogic (output);
type
trit = (terTrue, terMayBe, terFalse);
function terNot (a: trit): trit;
begin
case a of
terTrue: terNot := terFalse;
terMayBe: terNot := terMayBe;
terFalse: terNot := terTrue;
end;
end;
function terAnd (a, b: trit): trit;
begin
terAnd := te... |
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... | #Python | Python | import fileinput
import sys
nodata = 0; # Current run of consecutive flags<0 in lines of file
nodata_max=-1; # Max consecutive flags<0 in lines of file
nodata_maxline=[]; # ... and line number(s) where it occurs
tot_file = 0 # Sum of file data
num_file = 0 # Number of... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | daysarray = {"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"};
giftsarray = {"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-swimmi... |
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 ... | #XPL0 | XPL0 | code ChOut=8, Attrib=69;
def Black, Blue, Green, Cyan, Red, Magenta, Brown, White, \attribute colors
Gray, LBlue, LGreen, LCyan, LRed, LMagenta, Yellow, BWhite; \EGA palette
[ChOut(6,^C); \default white on black background
Attrib(Red<<4+White); \white on red
ChOut(6,^o);
Attrib(Green<<4+Red); \red on... |
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 ... | #zkl | zkl | fcn table(title,mode){
println("\n\e[1m%s\e[m\n bg\t fg".fmt(title));
foreach b in ([40..48].chain([100..107])){
print("%3d\t\e[%s%dm".fmt(b,mode,b));
foreach f in ([30..38].chain([90..97])){ print("\e[%dm%3d ".fmt(f,f)) }
println("\e[m");
}
}
table("normal ( ESC[22m or ESC[m )", "22;");
... |
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 ... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR l=0 TO 7
20 READ c$: REM get our text for display
30 INK l: REM set the text colour
40 PRINT c$
50 NEXT l
60 PAPER 2: REM red background
70 INK 6: REM yellow forground
80 FLASH 1: REM activate flashing
90 PRINT "Flashing!": REM this will flash red and yellow (alternating inverse)
100 PAPER 7: INK 0: FLASH 0: REM... |
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... | #Haskell | Haskell | import Control.Concurrent
import Control.Concurrent.MVar
main =
do lineVar <- newEmptyMVar
countVar <- newEmptyMVar
let takeLine = takeMVar lineVar
putLine = putMVar lineVar . Just
putEOF = putMVar lineVar Nothing
takeCount = takeMVar countVar
putC... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
fName := A[1]|"index.txt"
p := thread produce(fName)
c := thread consume(p)
every wait(p | c)
end
procedure produce(fName)
every !open(fName)@>> # drop messages in p's outbox (blocking whenever box is full)
@>> # Signal consumer that p is done
writ... |
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.