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/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Nanoquery | Nanoquery | cls |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Nemerle | Nemerle | Console.Clear(); |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #NewLISP | NewLISP |
(! "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... | #langur | langur | # borrowing null for "maybe"
val .trSet = [false, null, true]
val .and = f given .a, .b {
case true, null:
case null, true:
case null: null
default: .a and .b
}
val .or = f given .a, .b {
case false, null:
case null, false:
case null: null
default: .a or .b
}
val .imply = f if(.a n... |
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... | #Liberty_BASIC | Liberty BASIC |
'ternary logic
'0 1 2
'F ? T
'False Don't know True
'LB has NOT AND OR XOR, so we implement them.
'LB has no EQ, but XOR could be expressed via EQ. In 'normal' boolean at least.
global tFalse, tDontKnow, tTrue
tFalse = 0
tDontKnow = 1
tTrue = 2
print "Short and long names for ternary logic values"
for i = tFalse ... |
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... | #Picat | Picat | go =>
File = "readings.txt",
Total = new_map([num_readings=0,num_good_readings=0,sum_readings=0.0]),
InvalidCount = 0,
MaxInvalidCount = 0,
InvalidRunEnd = "",
Id = 0,
foreach(Line in read_file_lines(File))
Id := Id + 1,
NumReadings = 0,
NumGoodReadings = 0,
SumReadings = 0,
Field... |
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... | #Julia | Julia | # v0.6.0
function printlyrics()
const gifts = split("""
A partridge in a pear tree.
Two turtle doves
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pip... |
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... | #Kotlin | Kotlin | enum class Day {
first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth;
val header = "On the " + this + " day of Christmas, my true love sent to me\n\t"
}
fun main(x: Array<String>) {
val gifts = listOf("A partridge in a pear tree",
"Two turtle... |
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 ... | #REXX | REXX | /*REXX program to display sixteen lines, each of a different color. */
parse arg !; if !all() then exit /*exit if documentation specified*/
if \!dos & \!os2 then exit /*if this isn't DOS, then exit. */
if \!pcrexx then exit /*if this isn't PC/REXX, exit. */
color.0 = 'black'... |
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... | #E | E | def printer := {
var count := 0
def printer {
to run(item) {
count += 1
println(item)
}
to getCount() {
return count
}
}
}
def sender(lines) {
switch (lines) {
match [] {
when (def count := printer <- getCount()) ... |
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... | #EchoLisp | EchoLisp |
(require 'sequences)
(require 'tasks)
;; inter-tasks message : (op-code . data)
(define (is-message? op message)
(and message (equal? op (first message))))
;; reader task
(define (reader infile )
(wait S)
(define message (semaphore-pop S))
(when (is-message? 'count message ) (writeln 'reader-> message) (task-... |
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... | #PostgreSQL | PostgreSQL | CREATE SEQUENCE address_seq START 100;
CREATE TABLE address (
addrID int4 PRIMARY KEY DEFAULT NEXTVAL('address_seq'),
street VARCHAR(50) NOT NULL,
city VARCHAR(25) NOT NULL,
state VARCHAR(2) NOT NULL,
zip VARCHAR(20) 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... | #PowerShell.2BSQLite | PowerShell+SQLite |
Import-Module -Name PSSQLite
## Create a database and a table
$dataSource = ".\Addresses.db"
$query = "CREATE TABLE SSADDRESS (Id INTEGER PRIMARY KEY AUTOINCREMENT,
LastName TEXT NOT NULL,
FirstName 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... | #PureBasic.2BSQLite | PureBasic+SQLite |
UseSQLiteDatabase()
Procedure CheckDatabaseUpdate(Database, Query$)
Result = DatabaseUpdate(Database, Query$)
If Result = 0
Print(DatabaseError())
EndIf
ProcedureReturn Result
EndProcedure
openconsole()
DatabaseFile$ = GetCurrentDirectory()+"/rosettadb.sdb"
If CreateFile(0, DatabaseFile$)
CloseFi... |
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.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace Sutherland
{
public static class SutherlandHodgman
{
#region Class: Edge
/// <summary>
/// This represents a line segment
/// </summary>
private class... |
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... | #Apex | Apex | Set<String> setA = new Set<String>{'John', 'Bob', 'Mary', 'Serena'};
Set<String> setB = new Set<String>{'Jim', 'Mary', 'John', 'Bob'};
// Option 1
Set<String> notInSetA = setB.clone();
notInSetA.removeAll(setA);
Set<String> notInSetB = setA.clone();
notInSetB.removeAll(setB);
Set<String> symmetricDifference = new... |
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... | #Clojure | Clojure | (defn super [d]
(let [run (apply str (repeat d (str d)))]
(filter #(clojure.string/includes? (str (* d (Math/pow % d ))) run) (range))))
(doseq [d (range 2 9)]
(println (str d ": ") (take 10 (super d)))) |
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... | #D | D | import std.bigint;
import std.conv;
import std.stdio;
import std.string;
void main() {
auto rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"];
BigInt one = 1;
BigInt nine = 9;
for (int ii = 2; ii <= 9; ii++) {
writefln("First 10 super-%d numbers:", ii);
... |
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... | #E | E | #!/usr/bin/env rune
def f := <file:notes.txt>
def date := makeCommand("date")
switch (interp.getArgs()) {
match [] {
if (f.exists()) {
for line in f { print(line) }
}
}
match noteArgs {
def w := f.textWriter(true)
w.print(date()[0], "\t", " ".rjoin(noteArgs), ... |
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... | #Elixir | Elixir | defmodule Take_notes do
@filename "NOTES.TXT"
def main( [] ), do: display_notes
def main( arguments ), do: save_notes( arguments )
def display_notes, do: IO.puts File.read!(@filename)
def save_notes( arguments ) do
notes = "#{inspect :calendar.local_time}\n\t" <> Enum.join(arguments, " ")
File.o... |
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... | #C | C |
#include<graphics.h>
#include<stdio.h>
#include<math.h>
#define pi M_PI
int main(){
double a,b,n,i,incr = 0.0001;
printf("Enter major and minor axes of the SuperEllipse : ");
scanf("%lf%lf",&a,&b);
printf("Enter n : ");
scanf("%lf",&n);
initwindow(500,500,"Superellipse");
for(i=0;i<2*pi;i+=incr){... |
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... | #jq | jq | # Generate the sylvester integers:
def sylvester:
foreach range(0; infinite) as $i ({prev: 1, product: 1};
.product *= .prev
| .prev = .product + 1;
.prev); |
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... | #Julia | Julia | sylvester(n) = (n == 1) ? big"2" : prod(sylvester, 1:n-1) + big"1"
foreach(n -> println(rpad(n, 3), " => ", sylvester(n)), 1:10)
println("Sum of reciprocals of first 10: ", sum(big"1.0" / sylvester(n) for n in 1:10))
|
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Rest[Nest[Append[#, (Times @@ #) + 1] &, {1}, 10]]
N[Total[1/%], 250] |
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... | #Nim | Nim | import sequtils
import bignum
proc sylverster(lim: Positive): seq[Int] =
result.add(newInt(2))
for _ in 2..lim:
result.add result.foldl(a * b) + 1
let list = sylverster(10)
echo "First 10 terms of the Sylvester sequence:"
for item in list: echo item
var sum = newRat()
for item in list: sum += newRat(1, it... |
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... | #PARI.2FGP | PARI/GP |
S=vector(10)
S[1]=2
for(i=2, 10, S[i]=prod(n=1,i-1,S[n])+1)
print(S)
print(sum(i=1,10,1/S[i])) |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
tax... | #Java | Java | import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
class CubeSum implements Comparable<CubeSum> {
public long x, y, value;
public CubeSum(long x, long y) {
this.x = x;
this.y = y;
this.value = x*x*x + y*y*y;
}
public String toString() {
return... |
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'... | #Go | Go | package main
import "fmt"
const max = 12
var (
super []byte
pos int
cnt [max]int
)
// 1! + 2! + ... + n!
func factSum(n int) int {
s := 0
for x, f := 0, 1; x < n; {
x++
f *= x
s += f
}
return s
}
func r(n int) bool {
if n == 0 {
return false
... |
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
| #Python | Python | def tau(n):
assert(isinstance(n, int) and 0 < n)
ans, i, j = 0, 1, 1
while i*i <= n:
if 0 == n%i:
ans += 1
j = n//i
if j != i:
ans += 1
i += 1
return ans
def is_tau_number(n):
assert(isinstance(n, int))
if n <= 0:
retu... |
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
| #Quackery | Quackery | [ dup factors size mod 0 = ] is taunumber ( n --> b )
[] 0
[ 1+ dup taunumber if
[ tuck join swap ]
over size 100 = until ]
drop
[] swap
witheach [ number$ nested join ]
80 wrap$ |
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... | #Wren | Wren | import "io" for File
import "/str" for Str
import "/sort" for Find
var readWords = Fn.new { |fileName|
var dict = File.read(fileName).split("\n")
return dict.where { |w| w.count >= 3 }.toList
}
var dicts = ["mit10000.txt", "unixdict.txt"]
for (dict in dicts) {
System.print("Using %(dict):\n")
var wo... |
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... | #Befunge | Befunge | 0000>0p~>"."-:!#v_2-::0\`\9`+!#v_$1>/\:3`#v_\>\:3 \`#v_v
1#<<^0 /2++g001!<1 \+g00\+*+55\< ^+55\-1< ^*+55\+1<v_
"K"\-+**"!Y]"9:\"C"\--\**"^CIT"/5*9:\"F"\/5*9:\"R"\0\0<v
v/+55\+*86%+55: /+55\+*86%+55: \0/+55+5*-\1*2 p00:`\0:,<
>"."\>:55+% 68*v >:#,_$55+,\:!#@_^
$_^#!:/+55\+< ... |
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
| #jq | jq | def count(s): reduce s as $x (0; .+1);
# For pretty-printing
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; |
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
| #Julia | Julia | using Primes
function numfactors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
length(f)
end
for i in 1:100
print(rpad(numfactors(i), 3), i % 25 == 0 ? " \n" : " ")
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
| #Lua | Lua | function divisorCount(n)
local total = 1
-- Deal with powers of 2 first
while (n & 1) == 0 do
total = total + 1
n = math.floor(n / 2)
end
-- Odd prime factors up tot eh square root
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Nim | Nim |
import terminal
eraseScreen() #puts cursor at down
setCursorPos(0, 0)
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #NS-HUBASIC | NS-HUBASIC | 10 CLS |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #OCaml | OCaml | #load "unix.cma"
#directory "+ANSITerminal"
#load "ANSITerminal.cma"
open ANSITerminal
let () =
erase Screen |
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... | #Maple | Maple | tv := [true, false, FAIL];
NotTable := Array(1..3, i->not tv[i] );
AndTable := Array(1..3, 1..3, (i,j)->tv[i] and tv[j] );
OrTable := Array(1..3, 1..3, (i,j)->tv[i] or tv[j] );
XorTable := Array(1..3, 1..3, (i,j)->tv[i] xor tv[j] );
ImpliesTable := Array(1..3, 1..3, (i,j)->tv[i] implies tv[j] ); |
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... | #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(let (NoData 0 NoDataMax -1 NoDataMaxline "!" TotFile 0 NumFile 0)
(let InFiles
(glue ","
(mapcar
'((File)
(in File
(while (split (line) "^I")
(let (Len (length @) Date (car @) TotLine... |
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... | #Lambdatalk | Lambdatalk |
{def days
first second third fourth fifth sixth
seventh eight ninth tenth eleventh twelfth}
-> days
{def texts
{quote A partridge in a pear tree.}
{quote Two turtle doves and}
{quote Three french hens}
{quote Four calling birds}
{quote Five golden rings}
{quote Six geese a-laying}
{quote ... |
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 ... | #Ring | Ring |
# Project : Terminal control/Coloured text
load "consolecolors.ring"
forecolors = [CC_FG_BLACK,CC_FG_RED,CC_FG_GREEN,CC_FG_YELLOW,
CC_FG_BLUE,CC_FG_MAGENTA,CC_FG_CYAN,CC_FG_GRAY,CC_BG_WHITE]
for n = 1 to len(forecolors)
forecolor = forecolors[n]
cc_print(forecolor | CC_BG_WHITE, "R... |
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 ... | #Ruby | Ruby | #!/usr/bin/ruby -w
require 'rubygems'
require 'colored'
print 'Colors are'.bold
print ' black'.black
print ' blue'.blue
print ' cyan'.cyan
print ' green'.green
print ' magenta'.magenta
print ' red'.red
print ' white '.white
print 'and'.underline, ' yellow'.yellow, "\n"
puts 'black on blue'.black_on_blue
puts 'black o... |
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... | #Elixir | Elixir | defmodule RC do
def start do
my_pid = self
pid = spawn( fn -> reader(my_pid, 0) end )
File.open( "input.txt", [:read], fn io ->
process( IO.gets(io, ""), io, pid )
end )
end
defp process( :eof, _io, pid ) do
send( pid, :count )
receive do
i -> IO.puts "Count:#{i}"
en... |
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... | #Erlang | Erlang | -module(cc).
-export([start/0]).
start() ->
My_pid = erlang:self(),
Pid = erlang:spawn( fun() -> reader(My_pid, 0) end ),
{ok, IO } = file:open( "input.txt", [read] ),
process( io:get_line(IO, ""), IO, Pid ),
file:close( IO ).
process( eof, _IO, Pid ) ->
Pid ! count,
receive
I -> io:fw... |
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... | #Python.2BSQLite | Python+SQLite | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.execute('''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.Cursor object at 0x013265C0>
>>> |
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... | #Racket | Racket |
#lang at-exp racket
(require db)
(define postal (sqlite3-connect #:database "/tmp/postal.db" #:mode 'create))
(define (add! name street city state zip)
(query-exec postal
@~a{INSERT INTO addresses (name, street, city, state, zip)
VALUES (?, ?, ?, ?, ?)}
name street city state zip))
(unless (ta... |
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... | #Raku | Raku | use DBIish;
my $dbh = DBIish.connect('SQLite', :database<addresses.sqlite3>);
my $sth = $dbh.do(q:to/STATEMENT/);
DROP TABLE IF EXISTS Address;
CREATE TABLE Address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrStat... |
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... | #11l | 11l | print(Time()) |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generat... | #11l | 11l | [String] result
V longest = 0
F make_sequence(n) -> N
DefaultDict[Char, Int] map
L(c) n
map[c]++
V z = ‘’
L(k) sorted(map.keys(), reverse' 1B)
z ‘’= Char(code' map[k] + ‘0’.code)
z ‘’= k
I :longest <= z.len
:longest = z.len
I z !C :result
:result [+]= z
... |
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.
| #11l | 11l | F is_prime(a)
I a == 2
R 1B
I a < 2 | a % 2 == 0
R 0B
L(i) (3 .. Int(sqrt(a))).step(2)
I a % i == 0
R 0B
R 1B
print(‘index prime prime sum’)
V s = 0
V idx = 0
L(n) 2..999
I is_prime(n)
idx++
s += n
I is_prime(s)
print(f:‘{idx:3} {n:5} {s:7}’) |
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.2B.2B | C++ | #include <iostream>
using namespace std;
struct point2D { float x, y; };
const int N = 99; // clipped (new) polygon size
// check if a point is on the LEFT side of an edge
bool inside(point2D p, point2D p1, point2D p2)
{
return (p2.y - p1.y) * p.x + (p1.x - p2.x) * p.y + (p2.x * p1.y - p1.x * p2.y) < 0;
}... |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A... | #APL | APL | symdiff ← ∪~∩ |
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... | #AppleScript | AppleScript | -- SYMMETRIC DIFFERENCE -------------------------------------------
-- symmetricDifference :: [a] -> [a] -> [a]
on symmetricDifference(xs, ys)
union(difference(xs, ys), difference(ys, xs))
end symmetricDifference
-- TEST -----------------------------------------------------------
on run
set a to ["John", "S... |
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... | #F.23 | F# |
// Generate Super-N numbers. Nigel Galloway: October 12th., 2019
let superD N=
let I=bigint(pown 10 N)
let G=bigint N
let E=G*(111111111I%I)
let rec fL n=match (E-n%I).IsZero with true->true |_->if (E*10I)<n then false else fL (n/10I)
seq{1I..999999999999999999I}|>Seq.choose(fun n->if fL (G*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... | #Factor | Factor | USING: arrays formatting io kernel lists lists.lazy math
math.functions math.ranges math.text.utils prettyprint sequences
;
IN: rosetta-code.super-d
: super-d? ( seq n d -- ? ) tuck ^ * 1 digit-groups subseq? ;
: super-d ( d -- list )
[ dup <array> ] [ drop 1 lfrom ] [ ] tri [ super-d? ] curry
with lfilter ... |
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... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one... |
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... | #Erlang | Erlang |
#! /usr/bin/env escript
main( Arguments ) ->
display_notes( Arguments ),
save_notes( Arguments ).
display_notes( [] ) -> io:fwrite( "~s", [erlang:binary_to_list(file_contents())] );
display_notes( _Arguments ) -> ok.
file() -> "NOTES.TXT".
file_contents() -> file_contents( file:read_file(file()) ).
fi... |
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... | #EchoLisp | EchoLisp |
(lib 'plot)
(define (eaxpt x n) (expt (abs x) n))
(define (Ellie x y) (+ (eaxpt (// x 200) 2.5) (eaxpt (// y 200) 2.5) -1))
(plot-xy Ellie -400 -400)
→ (("x:auto" -400 400) ("y:auto" -400 400))
|
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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use List::Util 'reduce';
use Math::AnyNum ':overload';
local $Math::AnyNum::PREC = 845;
my(@S,$sum);
push @S, 1 + reduce { $a * $b } @S for 0..10;
shift @S;
$sum += 1/$_ for @S;
say "First 10 elements of Sylvester's sequence: @S";
say "\nSum of the reciprocals of first 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... | #Phix | Phix | atom n, rn = 0,
lim = power(2,iff(machine_bits()=32?53:64))
for i=1 to 10 do
n = iff(i=1?2:n*n-n+1)
printf(1,iff(n<=lim?"%d: %d\n":"%d: %g\n"),{i,n})
rn += 1/n
end for
printf(1,"sum of reciprocals: %g\n",{rn})
|
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... | #JavaScript | JavaScript | var n3s = [],
s3s = {}
for (var n = 1, e = 1200; n < e; n += 1) n3s[n] = n * n * n
for (var a = 1; a < e - 1; a += 1) {
var a3 = n3s[a]
for (var b = a; b < e; b += 1) {
var b3 = n3s[b]
var s3 = a3 + b3,
abs = s3s[s3]
if (!abs) s3s[s3] = abs = []
abs.push([a, b])
... |
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'... | #Groovy | Groovy | import static java.util.stream.IntStream.rangeClosed
class Superpermutation {
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
| #R | R | tau <- function(t)
{
results <- integer(0)
resultsCount <- 0
n <- 1
while(resultsCount != t)
{
condition <- function(n) (n %% length(c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) == 0
if(condition(n))
{
resultsCount <- resultsCount + 1
results[resultsCount] <- n
}
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
| #Raku | Raku | use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;
say "\nTau function - first 100:\n", # ID
(1..*).map({ +.&divisors })[^100]\ # the task
.batch(20)».fmt("%3d").join("\n"); # display formatting
say "\nTau numbers - first 100:\n", # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\ ... |
http://rosettacode.org/wiki/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... | #zkl | zkl | // Limited to ASCII
// This is limited to the max items a Dictionary can hold
fcn teacut(wordFile){
words:=File(wordFile).pump(Dictionary().add.fp1(True),"strip");
seen :=Dictionary();
foreach word in (words.keys){
rots,w,sz := List(), word, word.len();
if(sz>2 and word.unique().len()>2 and not see... |
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... | #Bracmat | Bracmat | ( ( rational2fixedpoint
= minus fixedpointnumber number decimals
. !arg:(#?number.~<0:~/#?decimals)
& ( !number:0&"0.0"
| ( !number:>0&
| -1*!number:?number&"-"
)
: ?minus
& !number+1/2*10^(-1*!decimals):?number
& !minus div$(!numbe... |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DivisorSum[#, 1 &] & /@ Range[100] |
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
| #Modula-2 | Modula-2 | MODULE TauFunc;
FROM InOut IMPORT WriteCard, WriteLn;
VAR i: CARDINAL;
PROCEDURE tau(n: CARDINAL): CARDINAL;
VAR total, count, p: CARDINAL;
BEGIN
total := 1;
WHILE n MOD 2 = 0 DO
n := n DIV 2;
total := total + 1
END;
p := 3;
WHILE p*p <= n DO
count := 1;
WHILE... |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Octave | Octave | system clear; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Pascal | Pascal | clrscr; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Perl | Perl | system('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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Maybe /: ! Maybe = Maybe;
Maybe /: (And | Or | Nand | Nor | Xor | Xnor | Implies | Equivalent)[Maybe, Maybe] = Maybe; |
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... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П0 Сx С/П ^ 1 + 3 * + 1
+ 3 x^y ИП0 <-> / [x] ^ ^ 3
/ [x] 3 * - 1 - С/П 1 5
6 3 3 БП 00 1 9 5 6 9
БП 00 1 5 9 2 9 БП 00 1
5 6 6 5 БП 00 /-/ ЗН С/П |
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... | #PL.2FI | PL/I | text1: procedure options (main); /* 13 May 2010 */
declare line character (2000) varying;
declare 1 pairs(24),
2 value fixed (10,4),
2 flag fixed;
declare date character (12) varying;
declare no_items fixed decimal (10);
declare (nv, sum, line_no, ndud_values, max_ndud_va... |
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... | #Logo | Logo | make "numbers [first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth]
make "gifts [[And a partridge in a pear tree] [Two turtle doves] [Three French hens]
[Four calling birds] [Five gold rings] [Six geese a-laying]
[Seven swans a-swimming]... |
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... | #LOLCODE | LOLCODE | CAN HAS STDIO?
HAI 1.2
I HAS A Dayz ITZ A BUKKIT
Dayz HAS A SRS 1 ITZ "first"
Dayz HAS A SRS 2 ITZ "second"
Dayz HAS A SRS 3 ITZ "third"
Dayz HAS A SRS 4 ITZ "fourth"
Dayz HAS A SRS 5 ITZ "fifth"
Dayz HAS A SRS 6 ITZ "sixth"
Dayz HAS A SRS 7 ITZ "seventh"
Dayz HAS A SRS 8 ITZ "eighth"
Dayz HAS A SRS 9 ITZ "n... |
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 ... | #Rust | Rust | const ESC: &str = "\x1B[";
const RESET: &str = "\x1B[0m";
fn main() {
println!("Foreground¦Background--------------------------------------------------------------");
print!(" ¦");
for i in 40..48 {
print!(" ESC[{}m ", i);
}
println!("\n----------¦---------------------------------... |
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 ... | #Scala | Scala | object ColouredText extends App {
val ESC = "\u001B"
val (normal, bold, blink, black, white) =
(ESC + "[0", ESC + "[1"
, ESC + "[5" // not working on my machine
, ESC + "[0;40m" // black background
, ESC + "[0;37m" // normal white foreground
)
print(s"${ESC}c") // clear terminal first
... |
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... | #Euphoria | Euphoria | sequence lines
sequence count
lines = {}
count = {}
procedure read(integer fn)
object line
while 1 do
line = gets(fn)
if atom(line) then
exit
else
lines = append(lines, line)
task_yield()
end if
end while
lines = append(lines,0)
... |
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... | #REXX | REXX | ╔════════╤════════════════════════════════════════════════════════════════════════╤══════╗
╟────────┘ Format of an entry in the USA address/city/state/zip code structure: └──────╢
║ ║
║ The structure name can be any variable name, ... |
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... | #Ring | Ring |
# Project : Table creation/Postal addresses
load "stdlib.ring"
oSQLite = sqlite_init()
sqlite_open(oSQLite,"mytest.db")
sql = "CREATE TABLE ADDRESS (" +
"addrID INT NOT NULL," +
"street CHAR(50) NOT NULL," +
"city CHAR(25) NOT NULL," +
"state CHAR(2), NOT NULL" +
"z... |
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... | #Ruby | Ruby | require 'pstore'
require 'set'
Address = Struct.new :id, :street, :city, :state, :zip
db = PStore.new("addresses.pstore")
db.transaction do
db[:next] ||= 0 # Next available Address#id
db[:ids] ||= Set[] # Set of all ids in db
end |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sysTime64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM6... |
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... | #ABAP | ABAP | REPORT system_time.
WRITE: sy-uzeit. |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Vectors;
procedure SelfRef is
subtype Seed is Natural range 0 .. 1_000_000;
subtype Num is Natural range 0 .. 10;
type NumList is array (0 .. 10) of Num;
package IO is new Ada.Text_IO.Integer_IO (Natural);
package DVect is new Ada.Containers.Vectors ... |
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.
| #ALGOL_68 | ALGOL 68 | BEGIN # sum the primes below n and report the sums that are prime #
# sieve the primes to 999 #
PR read "primes.incl.a68" PR
[]BOOL prime = PRIMESIEVE 999;
# sum the primes and test the sum #
INT prime sum := 0;
INT prime count := 0;
... |
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.
| #ALGOL_W | ALGOL W | begin % sum the primes below n and report the sums that are prime %
integer MAX_NUMBER;
MAX_NUMBER := 999;
begin
logical array prime( 1 :: MAX_NUMBER );
integer primeCount, primeSum, primeSumCount;
% sieve the primes to MAX_NUMBER ... |
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... | #D | D | import std.stdio, std.array, std.range, std.typecons, std.algorithm;
struct Vec2 { // To be replaced with Phobos code.
double x, y;
Vec2 opBinary(string op="-")(in Vec2 other)
const pure nothrow @safe @nogc {
return Vec2(this.x - other.x, this.y - other.y);
}
typeof(x) cross(in Vec2 ot... |
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... | #Arturo | Arturo | a: ["John" "Bob" "Mary" "Serena"]
b: ["Jim" "Mary" "John" "Bob"]
print difference.symmetric a b |
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... | #AutoHotkey | AutoHotkey | setA = John, Bob, Mary, Serena
setB = Jim, Mary, John, Bob
MsgBox,, Singles, % SymmetricDifference(setA, setB)
setA = John, Serena, Bob, Mary, Serena
setB = Jim, Mary, John, Jim, Bob
MsgBox,, Duplicates, % SymmetricDifference(setA, setB)
;---------------------------------------------------------------------------
S... |
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... | #Go | Go | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one... |
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... | #Haskell | Haskell | import Data.List (isInfixOf)
import Data.Char (intToDigit)
isSuperd :: (Show a, Integral a) => a -> a -> Bool
isSuperd p n =
(replicate <*> intToDigit) (fromIntegral p) `isInfixOf` show (p * n ^ p)
findSuperd :: (Show a, Integral a) => a -> [a]
findSuperd p = filter (isSuperd p) [1 ..]
main :: IO ()
main =
ma... |
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... | #Euphoria | Euphoria | constant cmd = command_line()
constant filename = "notes.txt"
integer fn
object line
sequence date_time
if length(cmd) < 3 then
fn = open(filename,"r")
if fn != -1 then
while 1 do
line = gets(fn)
if atom(line) then
exit
end if
puts(1,line... |
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... | #F.23 | F# | open System;;
open System.IO;;
let file_path = "notes.txt";;
let show_notes () =
try
printfn "%s" <| File.ReadAllText(file_path)
with
_ -> printfn "Take some notes first!";;
let take_note (note : string) =
let now = DateTime.Now.ToString() in
let note = sprintf "%s\n\t%s" now not... |
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... | #FreeBASIC | FreeBASIC | ' version 23-10-2016
' compile with: fbc -s console
Const scr_x = 800 ' screen 800 x 800
Const scr_y = 600
Const m_x = scr_x \ 2 ' middle of screen
Const m_y = scr_y \ 2
Sub superellipse(a As Long, b As Long, n As Double)
ReDim As Long y(0 To a)
Dim As Long x
y(0) = b ' value for x = 0
... |
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... | #PL.2FM | PL/M | 100H: /* CALCULATE ELEMENTS OF SYLVESTOR'S SEQUENCE */
BDOS: PROCEDURE( FN, ARG ); /* CP/M BDOS SYSTEM CALL */
DECLARE FN BYTE, ARG ADDRESS;
GOTO 5;
END BDOS;
PRINT$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRINT$STRING: 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... | #Prolog | Prolog | sylvesters_sequence(N, S, R):-
sylvesters_sequence(N, S, 2, R, 0).
sylvesters_sequence(0, [X], X, R, S):-
!,
R is S + 1 rdiv X.
sylvesters_sequence(N, [X|Xs], X, R, S):-
Y is X * X - X + 1,
M is N - 1,
T is S + 1 rdiv X,
sylvesters_sequence(M, Xs, Y, R, T).
main:-
sylvesters_sequence... |
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... | #Python | Python | '''Sylvester's sequence'''
from functools import reduce
from itertools import count, islice
# sylvester :: [Int]
def sylvester():
'''Non-finite stream of the terms
of Sylvester's sequence.
(OEIS A000058)
'''
def go(n):
return 1 + reduce(
lambda a, x: a * go(x),
... |
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... | #jq | jq | # Output: an array of the form [i^3 + j^3, [i, j]] sorted by the sum.
# Only cubes of 1 to ($in-1) are considered; the listing is therefore truncated
# as it might not capture taxicab numbers greater than $in ^ 3.
def sum_of_two_cubes:
def cubed: .*.*.;
. as $in
| (cubed + 1) as $limit
| [range(1;$in) as $i | r... |
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.