task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Stata | Stata | clear
gen str8 addrid=""
gen str50 street=""
gen str25 city=""
gen str2 state=""
gen str20 zip=""
save address |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Tcl.2BSQLite | Tcl+SQLite | package require sqlite3
sqlite3 db address.db
db eval {
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL
)
} |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Transact-SQL_.28MSSQL.29 | Transact-SQL (MSSQL) | CREATE TABLE #Address (
addrID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
addrStreet VARCHAR(50) NOT NULL ,
addrCity VARCHAR(25) NOT NULL ,
addrState CHAR(2) NOT NULL ,
addrZIP CHAR(10) NOT NULL
)
DROP TABLE #Address |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #VBScript | VBScript |
Option Explicit
Dim objFSO, DBSource
Set objFSO = CreateObject("Scripting.FileSystemObject")
DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb"
With CreateObject("ADODB.Connection")
.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource
.Execute "CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL," &_
"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)"
.Close
End With
|
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
Retrieving system time (wiki)
| #AmigaBASIC | AmigaBASIC | print date$,time$ |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #AppleScript | AppleScript | display dialog ((current date) as text) |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
Task
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Spelling of ordinal numbers
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Also see
The On-Line Encyclopedia of Integer Sequences.
| #BBC_BASIC | BBC BASIC | *FLOAT64
DIM list$(30)
maxiter% = 0
maxseed% = 0
FOR seed% = 0 TO 999999
list$(0) = STR$(seed%)
iter% = 0
REPEAT
list$(iter%+1) = FNseq(list$(iter%))
IF VALlist$(iter%+1) <= VALlist$(iter%) THEN
FOR try% = iter% TO 0 STEP -1
IF list$(iter%+1) = list$(try%) EXIT REPEAT
NEXT
ENDIF
iter% += 1
UNTIL FALSE
IF iter% >= maxiter% THEN
IF iter% > maxiter% CLS
maxiter% = iter%
maxseed% = seed%
PRINT "Seed " ;seed% " has "; iter% " iterations"
ENDIF
NEXT
PRINT '"Sequence:"
number$ = STR$(maxseed%)
FOR i% = 1 TO maxiter%
PRINT number$
number$ = FNseq(number$)
NEXT
END
DEF FNseq(n$)
LOCAL I%, o$, d%()
DIM d%(9)
FOR I% = 1 TO LEN(n$)
d%(ASCMID$(n$,I%)-&30) += 1
NEXT
FOR I% = 9 TO 0 STEP -1
IF d%(I%) o$ += STR$d%(I%) + STR$I%
NEXT
= o$ |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #C.2B.2B | C++ | #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
if (n % i == 0) {
return false;
}
i += 4;
}
return true;
}
int main() {
const int start = 1;
const int stop = 1000;
int sum = 0;
int count = 0;
int sc = 0;
for (int p = start; p < stop; p++) {
if (is_prime(p)) {
count++;
sum += p;
if (is_prime(sum)) {
printf("The sum of %3d primes in [2, %3d] is %5d which is also prime\n", count, p, sum);
sc++;
}
}
}
printf("There are %d summerized primes in [%d, %d)\n", sc, start, stop);
return 0;
} |
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 polygon that do not need to be displayed.
Task
Take the closed polygon defined by the points:
[
(
50
,
150
)
,
(
200
,
50
)
,
(
350
,
150
)
,
(
350
,
300
)
,
(
250
,
300
)
,
(
200
,
250
)
,
(
150
,
350
)
,
(
100
,
250
)
,
(
100
,
200
)
]
{\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}
and clip it by the rectangle defined by the points:
[
(
100
,
100
)
,
(
300
,
100
)
,
(
300
,
300
)
,
(
100
,
300
)
]
{\displaystyle [(100,100),(300,100),(300,300),(100,300)]}
Print the sequence of points that define the resulting clipped polygon.
Extra credit
Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.
(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
| #Go | Go | package main
import "fmt"
type point struct {
x, y float32
}
var subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}
var clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}
func main() {
var cp1, cp2, s, e point
inside := func(p point) bool {
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
}
intersection := func() (p point) {
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 / (dcx*dpy - dcy*dpx)
p.x = (n1*dpx - n2*dcx) * n3
p.y = (n1*dpy - n2*dcy) * n3
return
}
outputList := subjectPolygon
cp1 = clipPolygon[len(clipPolygon)-1]
for _, cp2 = range clipPolygon { // WP clipEdge is cp1,cp2 here
inputList := outputList
outputList = nil
s = inputList[len(inputList)-1]
for _, e = range inputList {
if inside(e) {
if !inside(s) {
outputList = append(outputList, intersection())
}
outputList = append(outputList, e)
} else if inside(s) {
outputList = append(outputList, intersection())
}
s = e
}
cp1 = cp2
}
fmt.Println(outputList)
} |
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\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #C | C | #include <stdio.h>
#include <string.h>
const char *A[] = { "John", "Serena", "Bob", "Mary", "Serena" };
const char *B[] = { "Jim", "Mary", "John", "Jim", "Bob" };
#define LEN(x) sizeof(x)/sizeof(x[0])
/* null duplicate items */
void uniq(const char *x[], int len)
{
int i, j;
for (i = 0; i < len; i++)
for (j = i + 1; j < len; j++)
if (x[j] && x[i] && !strcmp(x[i], x[j])) x[j] = 0;
}
int in_set(const char *const x[], int len, const char *match)
{
int i;
for (i = 0; i < len; i++)
if (x[i] && !strcmp(x[i], match))
return 1;
return 0;
}
/* x - y */
void show_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
int i;
for (i = 0; i < lenx; i++)
if (x[i] && !in_set(y, leny, x[i]))
printf(" %s\n", x[i]);
}
/* X ^ Y */
void show_sym_diff(const char *const x[], int lenx, const char *const y[], int leny)
{
show_diff(x, lenx, y, leny);
show_diff(y, leny, x, lenx);
}
int main()
{
uniq(A, LEN(A));
uniq(B, LEN(B));
printf("A \\ B:\n"); show_diff(A, LEN(A), B, LEN(B));
printf("\nB \\ A:\n"); show_diff(B, LEN(B), A, LEN(A));
printf("\nA ^ B:\n"); show_sym_diff(A, LEN(A), B, LEN(B));
return 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 function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Lua | Lua | for d = 2, 5 do
local n, found = 0, {}
local dds = string.rep(d, d)
while #found < 10 do
local dnd = string.format("%15.f", d * n ^ d)
if string.find(dnd, dds) then found[#found+1] = n end
n = n + 1
end
print("super-" .. d .. ": " .. table.concat(found,", "))
end |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[SuperD]
SuperD[d_, m_] := Module[{n, res, num},
res = {};
n = 1;
While[Length[res] < m,
num = IntegerDigits[d n^d];
If[MatchQ[num, {___, Repeated[d, {d}], ___}],
AppendTo[res, n]
];
n++;
];
res
]
Scan[Print[SuperD[#, 10]] &, Range[2, 6]] |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Nim | Nim | import sequtils, strutils, times
import bignum
iterator superDNumbers(d, maxCount: Positive): Natural =
var count = 0
var n = 2
let e = culong(d) # Bignum ^ requires a culong as exponent.
let pattern = repeat(chr(d + ord('0')), d)
while count != maxCount:
if pattern in $(d * n ^ e):
yield n
inc count
inc n, 1
let t0 = getTime()
for d in 2..9:
echo "First 10 super-$# numbers:".format(d)
echo toSeq(superDNumbers(d, 10)).join(" ")
echo "Time: ", getTime() - t0 |
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #FreeBASIC | FreeBASIC | If Len(Command) Then
Open "notes.txt" For Append As #1
Print #1, Date, Time
Print #1, Chr(9); Command
Close
Else
If Open("notes.txt" For Input As #1) = 0 Then
Dim As String lin
Print "Contenido del archivo:"
Do While Not Eof(1)
Line Input #1, lin
Print lin
Loop
Else
Open "notes.txt" For Output As #1
Print "Archivo 'NOTES.TXT' creado"
End If
End If
Close #1
Sleep |
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #Gambas | Gambas | 'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas'
Public Sub Main()
Dim sContents As String 'To store the file contents
Dim sArgs As String[] = Args.All 'To store all the Command line Arguments
If Not Exist(User.home &/ "NOTES.TXT") Then 'If NOTES.TXT doesn't already exist in the current directory then..
File.Save(User.home &/ "NOTES.TXT", "") 'a new NOTES.TXT file should be created.
Print "New file 'NOTES.TXT' created." 'A meassge
Endif
sContents = File.Load(User.home &/ "NOTES.TXT") 'Get the contents of the file
If Args.count < 2 Then 'If NOTES has arguments (other than the file name)
Print sContents 'Print the file contents
Else
sContents &= Format(Now, "dddd dd mmmm, yyyy, hh:nn:ss") & gb.NewLine & 'The current date and time are appended to the local NOTES.TXT followed by a newline and..
gb.Tab & sArgs.Join(" ") & gb.NewLine 'Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline
Print sContents 'Displays the current contents of the local NOTES.TXT
File.Save(User.home &/ "NOTES.TXT", sContents) 'Write contents to NOTES.TXT
Endif
End |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a = b = 200
| #J | J | selips=: 4 :0
'n a b'=. y
1 >: ((n^~a%~]) +&|/ n^~b%~]) i:x
)
require'viewmat'
viewmat 300 selips 2.5 200 200 |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a = b = 200
| #Java | Java | import java.awt.*;
import java.awt.geom.Path2D;
import static java.lang.Math.pow;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.event.*;
public class SuperEllipse extends JPanel implements ChangeListener {
private double exp = 2.5;
public SuperEllipse() {
setPreferredSize(new Dimension(650, 650));
setBackground(Color.white);
setFont(new Font("Serif", Font.PLAIN, 18));
}
void drawGrid(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0xEEEEEE));
int w = getWidth();
int h = getHeight();
int spacing = 25;
for (int i = 0; i < w / spacing; i++) {
g.drawLine(0, i * spacing, w, i * spacing);
g.drawLine(i * spacing, 0, i * spacing, w);
}
g.drawLine(0, h - 1, w, h - 1);
g.setColor(new Color(0xAAAAAA));
g.drawLine(0, w / 2, w, w / 2);
g.drawLine(w / 2, 0, w / 2, w);
}
void drawLegend(Graphics2D g) {
g.setColor(Color.black);
g.setFont(getFont());
g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45);
g.drawString("a = b = 200", getWidth() - 150, 75);
}
void drawEllipse(Graphics2D g) {
final int a = 200; // a = b
double[] points = new double[a + 1];
Path2D p = new Path2D.Double();
p.moveTo(a, 0);
// calculate first quadrant
for (int x = a; x >= 0; x--) {
points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); // solve for y
p.lineTo(x, -points[x]);
}
// mirror to others
for (int x = 0; x <= a; x++)
p.lineTo(x, points[x]);
for (int x = a; x >= 0; x--)
p.lineTo(-x, points[x]);
for (int x = 0; x <= a; x++)
p.lineTo(-x, -points[x]);
g.translate(getWidth() / 2, getHeight() / 2);
g.setStroke(new BasicStroke(2));
g.setColor(new Color(0x25B0C4DE, true));
g.fill(p);
g.setColor(new Color(0xB0C4DE)); // LightSteelBlue
g.draw(p);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
drawGrid(g);
drawLegend(g);
drawEllipse(g);
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
exp = source.getValue() / 2.0;
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Super Ellipse");
f.setResizable(false);
SuperEllipse panel = new SuperEllipse();
f.add(panel, BorderLayout.CENTER);
JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);
exponent.addChangeListener(panel);
exponent.setMajorTickSpacing(1);
exponent.setPaintLabels(true);
exponent.setBackground(Color.white);
exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
Hashtable<Integer, JLabel> labelTable = new Hashtable<>();
for (int i = 1; i < 10; i++)
labelTable.put(i, new JLabel(String.valueOf(i * 0.5)));
exponent.setLabelTable(labelTable);
f.add(exponent, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
} |
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 sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Swift | Swift | import BigNumber
func sylvester(n: Int) -> BInt {
var a = BInt(2)
for _ in 0..<n {
a = a * a - a + 1
}
return a
}
var sum = BDouble(0)
for n in 0..<10 {
let syl = sylvester(n: n)
sum += BDouble(1) / BDouble(syl)
print(syl)
}
print("Sum of the reciprocals of first ten in sequence: \(sum)") |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Verilog | Verilog |
module main;
integer i;
real suma, num;
initial begin
$display("10 primeros términos de la sucesión de sylvester:");
$display("");
suma = 0;
num = 0;
for(i=1; i<=10; i=i+1) begin
if (i==1) num = 2;
else num = num * num - num + 1;
$display(i, ": ", num);
suma = suma + 1 / num;
end
$display("");
$display("suma de sus recíprocos: ", suma);
$finish ;
end
endmodule
|
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 sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Wren | Wren | import "/big" for BigInt, BigRat
var sylvester = [BigInt.two]
var prod = BigInt.two
var count = 1
while (true) {
var next = prod + 1
sylvester.add(next)
count = count + 1
if (count == 10) break
prod = prod * next
}
System.print("The first 10 terms in the Sylvester sequence are:")
System.print(sylvester.join("\n"))
var sumRecip = sylvester.reduce(BigRat.zero) { |acc, s| acc + BigRat.new(1, s) }
System.print("\nThe sum of their reciprocals as a rational number is:")
System.print (sumRecip)
System.print("\nThe sum of their reciprocals as a decimal number (to 211 places) is:")
System.print(sumRecip.toDecimal(211)) |
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
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | findTaxi[n_] := Sort[Keys[Select[Counts[Flatten[Table[x^3 + y^3, {x, 1, n}, {y, x, n}]]], GreaterThan[1]]]];
Take[findTaxiNumbers[100], 25]
found=findTaxiNumbers[1200][[2000 ;; 2005]]
Map[Reduce[x^3 + y^3 == # && x >= y && x > 0 && y > 0, {x, y}, Integers] &, found] |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #Nim | Nim | import heapqueue, strformat
type
CubeSum = tuple[x, y, value: int]
# Comparison function needed for the heap queues.
proc `<`(c1, c2: CubeSum): bool = c1.value < c2.value
template cube(n: int): int = n * n * n
iterator cubesum(): CubeSum =
var queue: HeapQueue[CubeSum]
var n = 1
while true:
while queue.len == 0 or queue[0].value > cube(n):
queue.push (n, 1, cube(n) + 1)
inc n
var s = queue.pop()
yield s
inc s.y
if s.y < s.x: queue.push (s.x, s.y, cube(s.x) + cube(s.y))
iterator taxis(): seq[CubeSum] =
var result: seq[CubeSum] = @[(0, 0, 0)]
for s in cubesum():
if s.value == result[^1].value:
result.add s
else:
if result.len > 1: yield result
result.setLen(0)
result.add s # These two statements are faster than the single result = @[s].
var n = 0
for t in taxis():
inc n
if n > 2006: break
if n <= 25 or n >= 2000:
stdout.write &"{n:4}: {t[0].value:10}"
for s in t:
stdout.write &" = {s.x:4}^3 + {s.y:4}^3"
echo() |
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'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Perl | Perl | use ntheory qw/forperm/;
for my $len (1..8) {
my($pre, $post, $t) = ("","");
forperm {
$t = join "",@_;
$post .= $t unless index($post ,$t) >= 0;
$pre = $t . $pre unless index($pre, $t) >= 0;
} $len;
printf "%2d: %8d %8d\n", $len, length($pre), length($post);
} |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Phix | Phix | with javascript_semantics
constant nMax = iff(platform()=JS?8:12)
-- Aside: on desktop/Phix, strings can be modified in situ, whereas
-- JavaScript strings are immutable, and the equivalent code
-- in p2js.js ends up doing excessive splitting and splicing
-- hence nMax has to be significantly smaller in a browser.
atom t0 = time()
string superperm
sequence count
integer pos
function factSum(int n)
integer s = 0, f = 1
for i=1 to n do
f *= i
s += f
end for
return s
end function
function r(int n)
if (n == 0) then return false end if
integer c = superperm[pos-n+1]
count[n] -= 1
if count[n]=0 then
count[n] = n
if not r(n-1) then return false end if
end if
pos += 1
superperm[pos] = c
return true
end function
procedure superPerm(int n)
string chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[1..n]
pos = n
superperm = chars&repeat(' ',factSum(n)-n)
count = tagset(n)
while r(n) do end while
if n=0 then
if superperm!="" then ?9/0 end if
elsif n<=7 then
-- (I estimate it would take at least 5 days to validate
-- superPerm(12), feel free to try it on your own time)
for i=1 to factorial(n) do
if not match(permute(i,chars),superperm) then ?9/0 end if
end for
end if
end procedure
for n=0 to nMax do
superPerm(n)
integer l = length(superperm)
if l>40 then superperm[20..-20] = "..." end if
string e = elapsed(time()-t0)
printf(1,"superPerm(%2d) len = %d %s (%s)\n", {n, l, superperm, e})
end for
|
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Verilog | Verilog | module main;
integer n, m, num, limit, tau;
initial begin
$display("The first 100 tau numbers are:\n");
n = 0;
num = 0;
limit = 100;
while (num < limit) begin
n = n + 1;
tau = 0;
for (m = 1; m <= n; m=m+1) if (n % m == 0) tau = tau + 1;
if (n % tau == 0) begin
num = num + 1;
if (num % 5 == 1) $display("");
$write(n);
end
end
$finish ;
end
endmodule |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #VTL-2 | VTL-2 | 10 N=1100
20 I=1
30 :I)=1
40 I=I+1
50 #=N>I*30
60 I=2
70 J=I
80 :J)=:J)+1
90 J=J+I
100 #=N>J*80
110 I=I+1
120 #=N>I*70
130 C=0
140 I=1
150 #=I/:I)*0+0<%*210
160 ?=I
170 $=9
180 C=C+1
190 #=C/10*0+0<%*210
200 ?=""
210 I=I+1
220 #=C<100*150 |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Ceylon | Ceylon | shared void run() {
void printKelvinConversions(Float kelvin) {
value celsius = kelvin - 273.15;
value rankine = kelvin * 9.0 / 5.0;
value fahrenheit = rankine - 459.67;
print("Kelvin: ``formatFloat(kelvin, 2, 2)``
Celsius: ``formatFloat(celsius, 2, 2)``
Fahrenheit: ``formatFloat(fahrenheit, 2, 2)``
Rankine: ``formatFloat(rankine, 2, 2)``");
}
printKelvinConversions(21.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
| #PureBasic | PureBasic | If OpenConsole()
For i=1 To 100
If i<3 : Print(RSet(Str(i),4)) : Continue :EndIf
c=2
For j=2 To i/2+1 : c+Bool(i%j=0) : Next
Print(RSet(Str(c),4))
If i%10=0 : PrintN("") : EndIf
Next
Input()
EndIf
End |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Python | Python | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //= p
if 0 < k:
yield (p,k)
p += 2
if 1 < n:
yield (n,1)
def tau(n):
assert(n != 0)
ans = 1
for (p,k) in factorize(n):
ans *= 1 + k
return ans
if __name__ == "__main__":
print([tau(n) for n in range(1,101)]) |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #REXX | REXX | /*REXX boilerplate determines how to clear screen (under various REXXes)*/
trace off; parse arg ! /*turn off tracing; get C.L. args*/
if !all(arg()) then exit /*Doc request? Show, then exit.*/
if !cms then address '' /*Is this CMS? Use this address.*/
!cls /*clear the (terminal) screen. */ /* ◄═══ this is where "it" happens.*/
exit /*stick a fork in it, we're done.*/
/*═════════════════════════════general 1-line subs══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/
!all: !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
!cal: if symbol('!CALL')\=="VAR" then !call=; return !call
!env: !env='ENVIRONMENT'; if !sys=='MSDOS'|!brexx|!r4|!roo then !env='SYSTEM'; if !os2 then !env='OS2'!env; !ebcdic=1=='f0'x; if !crx then !env='DOS'; return
!fid: parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _=lastpos('\',!fn); !fm=left(!fn,_); !fn=substr(!fn,_+1); parse var !fn !fn '.' !ft; end; return word(0 !fn !ft !fm,1+('0'arg(1)))
!rex: parse upper version !ver !vernum !verdate .; !brexx='BY'==!vernum; !kexx='KEXX'==!ver; !pcrexx='REXX/PERSONAL'==!ver|'REXX/PC'==!ver; !r4='REXX-R4'==!ver; !regina='REXX-REGINA'==left(!ver,11); !roo='REXX-ROO'==!ver; call !env; return
!sys: !cms=!sys=='CMS'; !os2=!sys=='OS2'; !tso=!sys=='TSO'|!sys=='MVS'; !vse=!sys=='VSE'; !dos=pos('DOS',!sys)\==0|pos('WIN',!sys)\==0|!sys=='CMD'; !crx=left(!sys,6)=='DOSCRX'; call !rex; return
!var: call !fid; if !kexx then return space(dosenv(arg(1))); return space(value(arg(1),,!env)) |
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 logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #Perl | Perl | package Trit;
# -1 = false ; 0 = maybe ; 1 = true
use Exporter 'import';
our @EXPORT_OK = qw(TRUE FALSE MAYBE is_true is_false is_maybe);
our %EXPORT_TAGS = (
all => \@EXPORT_OK,
const => [qw(TRUE FALSE MAYBE)],
bool => [qw(is_true is_false is_maybe)],
);
use List::Util qw(min max);
use overload
'=' => sub { $_[0]->clone() },
'<=>'=> sub { $_[0]->cmp($_[1]) },
'cmp'=> sub { $_[0]->cmp($_[1]) },
'==' => sub { ${$_[0]} == ${$_[1]} },
'eq' => sub { $_[0]->equiv($_[1]) },
'>' => sub { ${$_[0]} > ${$_[1]} },
'<' => sub { ${$_[0]} < ${$_[1]} },
'>=' => sub { ${$_[0]} >= ${$_[1]} },
'<=' => sub { ${$_[0]} <= ${$_[1]} },
'|' => sub { $_[0]->or($_[1]) },
'&' => sub { $_[0]->and($_[1]) },
'!' => sub { $_[0]->not() },
'~' => sub { $_[0]->not() },
'""' => sub { $_[0]->tostr() },
'0+' => sub { $_[0]->tonum() },
;
sub new
{
my ($class, $v) = @_;
my $ret =
!defined($v) ? 0 :
$v eq 'true' ? 1 :
$v eq 'false'? -1 :
$v eq 'maybe'? 0 :
$v > 0 ? 1 :
$v < 0 ? -1 :
0;
return bless \$ret, $class;
}
sub TRUE() { new Trit( 1) }
sub FALSE() { new Trit(-1) }
sub MAYBE() { new Trit( 0) }
sub clone
{
my $ret = ${$_[0]};
return bless \$ret, ref($_[0]);
}
sub tostr { ${$_[0]} > 0 ? "true" : ${$_[0]} < 0 ? "false" : "maybe" }
sub tonum { ${$_[0]} }
sub is_true { ${$_[0]} > 0 }
sub is_false { ${$_[0]} < 0 }
sub is_maybe { ${$_[0]} == 0 }
sub cmp { ${$_[0]} <=> ${$_[1]} }
sub not { new Trit(-${$_[0]}) }
sub and { new Trit(min(${$_[0]}, ${$_[1]}) ) }
sub or { new Trit(max(${$_[0]}, ${$_[1]}) ) }
sub equiv { new Trit( ${$_[0]} * ${$_[1]} ) } |
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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #R | R | #Read in data from file
dfr <- read.delim("readings.txt")
#Calculate daily means
flags <- as.matrix(dfr[,seq(3,49,2)])>0
vals <- as.matrix(dfr[,seq(2,49,2)])
daily.means <- rowSums(ifelse(flags, vals, 0))/rowSums(flags)
#Calculate time between good measurements
times <- strptime(dfr[1,1], "%Y-%m-%d", tz="GMT") + 3600*seq(1,24*nrow(dfr),1)
hours.between.good.measurements <- diff(times[t(flags)])/3600 |
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
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MiniScript | MiniScript | days = ["first","second","third", "fourth","fifth","sixth",
"seventh","eigth","nineth","tenth","eleventh","twelfth"]
gifts = ["A partridge in a pear tree.","Two turtle doves, and",
"Three French hens,","Four calling birds,",
"Five gold rings,","Six geese a-laying,",
"Seven swans a-swimming,","Eight maids a-milking,",
"Nine ladies dancing,","Ten lords a-leaping,",
"Eleven pipers piping,","Twelve drummers drumming,"]
for i in range(0,11)
print "On the " + days[i] + " day of Christmas,"
print "my true love gave to me,"
for j in range(i,0)
print " " + gifts[j]
end for
print " ----------"
end for
|
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
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import strutils, algorithm
const
Gifts = ["A partridge in a pear tree.",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"]
Days = ["first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"]
for n, day in Days:
var g = reversed(Gifts[0..n])
echo "\nOn the ", day, " day of Christmas\nMy true love gave to me:\n",
g[0..^2].join("\n"), if n > 0: " and\n" & g[^1] else: capitalizeAscii(g[^1]) |
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #J | J | input=: 1 :0
nlines=: 0
u;._2@fread 'input.txt'
smoutput nlines
)
output=: 3 :0
nlines=: nlines+1
smoutput y
) |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Java | Java | import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
class SynchronousConcurrency
{
public static void main(String[] args) throws Exception
{
final AtomicLong lineCount = new AtomicLong(0);
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
final String EOF = new String();
final Thread writerThread = new Thread(new Runnable() {
public void run()
{
long linesWrote = 0;
while (true)
{
try
{
String line = queue.take();
// Reference equality
if (line == EOF)
break;
System.out.println(line);
linesWrote++;
}
catch (InterruptedException ie)
{ }
}
lineCount.set(linesWrote);
}
}
);
writerThread.start();
// No need to start a third thread for the reader, just use this thread
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = br.readLine()) != null)
queue.put(line);
br.close();
queue.put(EOF);
writerThread.join();
// AtomicLong is not needed here due to memory barrier created by thread join, but still need a mutable long since lineCount must be final to access it from an anonymous class
System.out.println("Line count: " + lineCount.get());
return;
}
}
|
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 zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Visual_FoxPro | Visual FoxPro |
CLOSE DATABASES ALL
CREATE DATABASE usdata.dbc
SET NULL OFF
CREATE TABLE address.dbf ;
(id I AUTOINC NEXTVALUE 1 STEP 1 PRIMARY KEY COLLATE "Machine", ;
street V(50), city V(25), state C(2), zipcode C(10))
CLOSE DATABASES ALL
*!* To use
CLOSE DATABASES ALL
OPEN DATABASE usdata.dbc
USE address.dbf SHARED
|
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Wren | Wren | import "/dynamic" for Enum, Tuple
import "/fmt" for Fmt
import "/sort" for Cmp, Sort
var FieldType = Enum.create("FieldType", ["text", "num", "int", "bool"])
var Field = Tuple.create("Field", ["name", "fieldType", "maxLen"])
class Table {
construct new(name, fields, keyIndex) {
_name = name
_fields = fields
_keyIndex = keyIndex // the zero based index of the field to sort on
_records = []
_fmt = ""
for (f in _fields) {
var c = f.name.count
var l = f.maxLen.max(c)
if (f.fieldType == FieldType.text ||f.fieldType == FieldType.bool) {
l = -l
}
_fmt = _fmt + "$%(l)s "
}
_fmt = _fmt.trimEnd()
}
name { _name }
showFields() {
System.print("Fields for %(_name) table:\n")
Fmt.print("$-20s $4s $s", "name", "type", "maxlen")
System.print("-" * 33)
for (f in _fields) {
Fmt.print("$-20s $-4s $d", f.name, FieldType.members[f.fieldType], f.maxLen)
}
}
cmp_ { Fn.new { |r1, r2|
return (Num.fromString(r1[_keyIndex]) - Num.fromString(r2[_keyIndex])).sign
}}
addRecord(record) {
var items = record.split(", ")
_records.add(items)
Sort.insertion(_records, cmp_) // move new record into sorted order
}
showRecords() {
System.print("Records for %(_name) table:\n")
var h = Fmt.slwrite(_fmt, _fields.map { |f| f.name }.toList)
System.print(h)
System.print("-" * h.count)
for (r in _records) {
Fmt.lprint(_fmt, r)
}
}
removeRecord(key) {
for (i in 0..._records.count) {
if (_records[i][_keyIndex] == key.toString) {
_records.removeAt(i)
return
}
}
}
findRecord(key) {
for (i in 0..._records.count) {
if (_records[i][_keyIndex] == key.toString) {
return _records[i].join(", ")
}
}
return null
}
}
var fields = []
fields.add(Field.new("id", FieldType.int, 2))
fields.add(Field.new("name", FieldType.text, 25))
fields.add(Field.new("street", FieldType.text, 50))
fields.add(Field.new("city", FieldType.text, 15))
fields.add(Field.new("state", FieldType.text, 2))
fields.add(Field.new("zipCode", FieldType.text, 10))
// create table
var table = Table.new("Addresses", fields, 0)
// add records in unsorted order
table.addRecord("2, FSF Inc., 51 Franklin Street, Boston, MA, 02110-1301")
table.addRecord("1, The White House, The Oval Office 1600 Pennsylvania Avenue NW, Washington, DC, 20500")
table.addRecord("3, National Security Council, 1700 Pennsylvania Avenue NW, Washington, DC, 20500")
// show the table's fields
table.showFields()
System.print()
// show the table's records in sorted order
table.showRecords()
// find a record by key
System.print("\nThe record with an id of 2 is:")
System.print(table.findRecord(2))
// delete a record by key
table.removeRecord(1)
System.print("\nThe record with an id of 1 will be deleted, leaving:\n")
table.showRecords() |
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
Retrieving system time (wiki)
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program sysTime.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BRK, 0x2d @ Linux syscall
.equ CHARPOS, '@'
.equ GETTIME, 0x4e @ call system linux gettimeofday
/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: @
.struct timeval_sec + 4
timeval_usec: @
.struct timeval_usec + 4
timeval_end:
.struct 0
timezone_min: @
.struct timezone_min + 4
timezone_dsttime: @
.struct timezone_dsttime + 4
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "GMT: @/@/@ @:@:@ @ms\n" @ message result
szCarriageReturn: .asciz "\n"
.align 4
tbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sZoneConv: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrstTVal
ldr r1,iAdrstTZone
mov r7,#GETTIME
svc 0
cmp r0,#-1 @ error ?
beq 99f
ldr r0,iAdrstTVal
ldr r1,[r0,#timeval_sec] @ timestemp in second
//ldr r1,iTStest1
//ldr r1,iTStest2
//ldr r1,iTStest3
ldr r2,iSecJan2020
sub r0,r1,r2 @ total secondes to 01/01/2020
mov r1,#60
bl division
mov r0,r2
mov r6,r3 @ compute secondes
mov r1,#60
bl division
mov r7,r3 @ compute minutes
mov r0,r2
mov r1,#24
bl division
mov r8,r3 @ compute hours
mov r0,r2
mov r11,r0
mov r1,#(365 * 4 + 1)
bl division
lsl r9,r2,#2 @ multiply by 4 = year1
mov r1,#(365 * 4 + 1)
mov r0,r11
bl division
mov r10,r3
ldr r1,iAdrtbDayMonthYear
mov r2,#3
mov r3,#12
1:
mul r11,r3,r2
ldr r12,[r1,r11,lsl #2] @ load days by year
cmp r10,r12
bge 2f
sub r2,r2,#1
cmp r2,#0
bne 1b
2: @ r2 = year2
mov r5,#11
mul r4,r3,r2
lsl r4,#2
add r4,r1
3:
ldr r12,[r4,r5,lsl #2] @ load days by month
cmp r10,r12
bge 4f
subs r5,r5,#1
bne 3b
4: @ r5 = month - 1
mul r11,r3,r2
add r11,r5
ldr r1,iAdrtbDayMonthYear
ldr r3,[r1,r11,lsl #2]
sub r0,r10,r3
add r0,r0,#1 @ final compute day
ldr r1,iAdrsZoneConv
bl conversion10 @ this function do not zero final
mov r4,#0 @ store zero final
strb r4,[r1,r0]
ldr r0,iAdrszMessResult
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at first @ character
mov r3,r0
add r0,r5,#1 @ final compute month
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
ldr r11,iYearStart
add r0,r9,r11
add r0,r0,r2 @ final compute year = 2020 + year1 + year2
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r8 @ hours
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r7 @ minutes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r6 @ secondes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
ldr r1,iAdrstTVal
ldr r0,[r1,#timeval_usec] @ millisecondes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
bl affichageMess
b 100f
99:
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0,#0 @ return code
mov r7,#EXIT @ request to exit program
svc 0 @ perform the system call
iAdrszMessError: .int szMessError
iAdrstTVal: .int stTVal
iAdrstTZone: .int stTZone
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iSecJan2020: .int 1577836800
iAdrtbDayMonthYear: .int tbDayMonthYear
iYearStart: .int 2020
iTStest1: .int 1609508339 @ 01/01/2021
iTStest2: .int 1657805939 @ 14/07/2022
iTStest3: .int 1767221999 @ 31/12/2025
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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 generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
Task
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Spelling of ordinal numbers
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Also see
The On-Line Encyclopedia of Integer Sequences.
| #Bracmat | Bracmat | ( ( self-referential
= seq N next
. ( next
= R S d f
. 0:?S
& whl
' (@(!arg:%@?d ?arg)&(.!d)+!S:?S)
& :?R
& whl
' ( !S:#?f*(.?d)+?S
& !f !d !R:?R
)
& str$!R
)
& 1:?N
& !arg:?seq
& whl
' ( next$!arg:?arg
& ~(!seq:? !arg ?)
& !arg !seq:?seq
& 1+!N:?N
)
& (!seq.!N)
)
& ( Perm
= permutations S p
. :?permutations
& ( perm
= prefix List original A Z p
. !arg:(?prefix.)
& str$!prefix:?p
& (!S:?+(.!p)+?|(.!p)+!S:?S)
| !arg:(0 ?.?)&
| !arg:(?prefix.?List:?original)
& whl
' ( @(!List:%?A ?Z)
& perm$(!prefix !A.!Z)
& str$(!Z !A):~!original:?List
)
)
& 0:?S
& perm$(.!arg)
& :?permutations
& whl
' ( !S:?*(.?p)+?S
& !p !permutations:?permutations
)
& !permutations
)
& -1:?i:?max
& :?seqs
& whl
' ( 1+!i:<1000000:?i
& ( @(!i:? %@?a >%@!a ?)
| self-referential$!i
: ( ?seq
. ( >!max:?max&:?seqs
| !max
)
& ( "Seed Value(s):" Perm$!i
. "Sequence: (same for all three seeds except for first element)
"
!seq
)
!seqs
: ?seqs
)
|
)
)
& out$("Iterations:" !max !seqs)
); |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #F.23 | F# |
// Summarize Primes: Nigel Galloway. April 16th., 2021
primes32()|>Seq.takeWhile((>)1000)|>Seq.scan(fun(n,g) p->(n+1,g+p))(0,0)|>Seq.filter(snd>>isPrime)|>Seq.iter(fun(n,g)->printfn "%3d->%d" n g)
|
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Factor | Factor | USING: assocs formatting kernel math.primes math.ranges
math.statistics prettyprint ;
1000 [ [1,b] ] [ primes-upto cum-sum ] bi zip
[ nip prime? ] assoc-filter
[ "The sum of the first %3d primes is %5d (which is prime).\n" printf ] assoc-each |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Fermat | Fermat | n:=0
s:=0
for i=1, 162 do s:=s+Prime(i);if Isprime(s)=1 then n:=n+1;!!(n,Prime(i),s) fi od
|
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Forth | Forth | : prime? ( n -- flag )
dup 2 < if drop false exit then
dup 2 mod 0= if 2 = exit then
dup 3 mod 0= if 3 = exit then
5
begin
2dup dup * >=
while
2dup mod 0= if 2drop false exit then
2 +
2dup mod 0= if 2drop false exit then
4 +
repeat
2drop true ;
: main
0 0 { count sum }
." count prime sum" cr
1000 2 do
i prime? if
count 1+ to count
sum i + to sum
sum prime? if
." " count 3 .r ." " i 3 .r ." " sum 5 .r cr
then
then
loop ;
main
bye |
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 polygon that do not need to be displayed.
Task
Take the closed polygon defined by the points:
[
(
50
,
150
)
,
(
200
,
50
)
,
(
350
,
150
)
,
(
350
,
300
)
,
(
250
,
300
)
,
(
200
,
250
)
,
(
150
,
350
)
,
(
100
,
250
)
,
(
100
,
200
)
]
{\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}
and clip it by the rectangle defined by the points:
[
(
100
,
100
)
,
(
300
,
100
)
,
(
300
,
300
)
,
(
100
,
300
)
]
{\displaystyle [(100,100),(300,100),(300,300),(100,300)]}
Print the sequence of points that define the resulting clipped polygon.
Extra credit
Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.
(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
| #Haskell | Haskell | module SuthHodgClip (clipTo) where
import Data.List
type Pt a = (a, a)
type Ln a = (Pt a, Pt a)
type Poly a = [Pt a]
-- Return a polygon from a list of points.
polyFrom ps = last ps : ps
-- Return a list of lines from a list of points.
linesFrom pps@(_:ps) = zip pps ps
-- Return true if the point (x,y) is on or to the left of the oriented line
-- defined by (px,py) and (qx,qy).
(.|) :: (Num a, Ord a) => Pt a -> Ln a -> Bool
(x,y) .| ((px,py),(qx,qy)) = (qx-px)*(y-py) >= (qy-py)*(x-px)
-- Return the intersection of two lines.
(><) :: Fractional a => Ln a -> Ln a -> Pt a
((x1,y1),(x2,y2)) >< ((x3,y3),(x4,y4)) =
let (r,s) = (x1*y2-y1*x2, x3*y4-y3*x4)
(t,u,v,w) = (x1-x2, y3-y4, y1-y2, x3-x4)
d = t*u-v*w
in ((r*w-t*s)/d, (r*u-v*s)/d)
-- Intersect the line segment (p0,p1) with the clipping line's left halfspace,
-- returning the point closest to p1. In the special case where p0 lies outside
-- the halfspace and p1 lies inside we return both the intersection point and
-- p1. This ensures we will have the necessary segment along the clipping line.
(-|) :: (Fractional a, Ord a) => Ln a -> Ln a -> [Pt a]
ln@(p0, p1) -| clipLn =
case (p0 .| clipLn, p1 .| clipLn) of
(False, False) -> []
(False, True) -> [isect, p1]
(True, False) -> [isect]
(True, True) -> [p1]
where isect = ln >< clipLn
-- Intersect the polygon with the clipping line's left halfspace.
(<|) :: (Fractional a, Ord a) => Poly a -> Ln a -> Poly a
poly <| clipLn = polyFrom $ concatMap (-| clipLn) (linesFrom poly)
-- Intersect a target polygon with a clipping polygon. The latter is assumed to
-- be convex.
clipTo :: (Fractional a, Ord a) => [Pt a] -> [Pt a] -> [Pt a]
targPts `clipTo` clipPts =
let targPoly = polyFrom targPts
clipLines = linesFrom (polyFrom clipPts)
in foldl' (<|) targPoly clipLines |
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\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace RosettaCode.SymmetricDifference
{
public static class IEnumerableExtension
{
public static IEnumerable<T> SymmetricDifference<T>(this IEnumerable<T> @this, IEnumerable<T> that)
{
return @this.Except(that).Concat(that.Except(@this));
}
}
class Program
{
static void Main()
{
var a = new[] { "John", "Bob", "Mary", "Serena" };
var b = new[] { "Jim", "Mary", "John", "Bob" };
foreach (var element in a.SymmetricDifference(b))
{
Console.WriteLine(element);
}
}
}
} |
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 function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Pascal | Pascal | program Super_D;
uses
sysutils,gmp;
var
s :ansistring;
s_comp : ansistring;
test : mpz_t;
i,j,dgt,cnt : NativeUint;
Begin
mpz_init(test);
for dgt := 2 to 9 do
Begin
//create '22' to '999999999'
i := dgt;
For j := 2 to dgt do
i := i*10+dgt;
s_comp := IntToStr(i);
writeln('Finding ',s_comp,' in ',dgt,'*i**',dgt);
i := dgt;
cnt := 0;
repeat
mpz_ui_pow_ui(test,i,dgt);
mpz_mul_ui(test,test,dgt);
setlength(s,mpz_sizeinbase(test,10));
mpz_get_str(pChar(s),10,test);
IF Pos(s_comp,s) <> 0 then
Begin
write(i,' ');
inc(cnt);
end;
inc(i);
until cnt = 10;
writeln;
end;
mpz_clear(test);
End. |
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #Go | Go | package main
import (
"fmt"
"io"
"os"
"strings"
"time"
)
func addNote(fn string, note string) error {
f, err := os.OpenFile(fn, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
_, err = fmt.Fprint(f, time.Now().Format(time.RFC1123), "\n\t", note, "\n")
// To be extra careful with errors from Close():
if cErr := f.Close(); err == nil {
err = cErr
}
return err
}
func showNotes(w io.Writer, fn string) error {
f, err := os.Open(fn)
if err != nil {
if os.IsNotExist(err) {
return nil // don't report "no such file"
}
return err
}
_, err = io.Copy(w, f)
f.Close()
return err
}
func main() {
const fn = "NOTES.TXT"
var err error
if len(os.Args) > 1 {
err = addNote(fn, strings.Join(os.Args[1:], " "))
} else {
err = showNotes(os.Stdout, fn)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
} |
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a = b = 200
| #JavaScript | JavaScript |
var n = 2.5, a = 200, b = 200, ctx;
function point( x, y ) {
ctx.fillRect( x, y, 1, 1);
}
function start() {
var can = document.createElement('canvas');
can.width = can.height = 600;
ctx = can.getContext( "2d" );
ctx.rect( 0, 0, can.width, can.height );
ctx.fillStyle = "#000000"; ctx.fill();
document.body.appendChild( can );
ctx.fillStyle = "#ffffff";
for( var t = 0; t < 1000; t += .1 ) {
x = Math.pow( Math.abs( Math.cos( t ) ), 2 / n ) * a * Math.sign( Math.cos( t ) );
y = Math.pow( Math.abs( Math.sin( t ) ), 2 / n ) * b * Math.sign( Math.sin( t ) );
point( x + ( can.width >> 1 ), y + ( can.height >> 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
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #PARI.2FGP | PARI/GP | taxicab(n)=my(t); for(k=sqrtnint((n-1)\2,3)+1, sqrtnint(n,3), if(ispower(n-k^3, 3), if(t, return(1), t=1))); 0;
cubes(n)=my(t); for(k=sqrtnint((n-1)\2,3)+1, sqrtnint(n,3), if(ispower(n-k^3, 3, &t), print(n" = \t"k"^3\t+ "t"^3")))
select(taxicab, [1..402597])
apply(cubes, %); |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #PureBasic | PureBasic | EnableExplicit
#MAX=10
Declare.i fact_sum(n.i) : Declare.i r(n.i) : Declare superperm(n.i)
Global pos.i, Dim cnt.i(#MAX), Dim super.s{1}(fact_sum(#MAX))
If OpenConsole() ;- MAIN: Superpermutation_minimisation
Define.i n
For n=0 To #MAX
superperm(n) : Print("superperm("+RSet(Str(n),2)+") len = "+LSet(Str(pos),10))
If n<=4 : Print(~"\t"+PeekS(@super(),pos)) : EndIf
PrintN("")
Next
Input()
EndIf
End ;- END: Superpermutation_minimisation
Procedure.i fact_sum(n.i)
Define.i s=0,f=1,x=0
While x<n : x+1 : f*x : s+f : Wend
ProcedureReturn s
EndProcedure
Procedure.i r(n.i)
If Not n : ProcedureReturn 0 : EndIf
Define c.s{1}=super(pos-n)
cnt(n)-1
If Not cnt(n)
cnt(n)=n
If Not r(n-1) : ProcedureReturn 0 : EndIf
EndIf
super(pos)=c : pos+1 : ProcedureReturn 1
EndProcedure
Procedure superperm(n.i)
pos=n
Define.i len=fact_sum(n),i
For i=0 To n : cnt(i)=i : Next
For i=1 To n : super(i-1)=Chr('0'+i) : Next
While r(n) : Wend
EndProcedure |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
System.print("The first 100 tau numbers are:")
var count = 0
var i = 1
while (count < 100) {
var tf = Int.divisors(i).count
if (i % tf == 0) {
Fmt.write("$,5d ", i)
count = count + 1
if (count % 10 == 0) System.print()
}
i = i + 1
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #XPL0 | XPL0 | func Divs(N); \Return number of divisors of N
int N, D, C;
[C:= 0;
for D:= 1 to N do
if rem(N/D) = 0 then C:= C+1;
return C;
];
int C, N;
[Format(5, 0);
C:= 0; N:= 1;
loop [if rem(N/Divs(N)) = 0 then
[RlOut(0, float(N));
C:= C+1;
if rem(C/10) = 0 then CrLf(0);
if C >= 100 then quit;
];
N:= N+1;
];
] |
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 zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #Clojure | Clojure | (defn to-celsius [k]
(- k 273.15))
(defn to-fahrenheit [k]
(- (* k 1.8) 459.67))
(defn to-rankine [k]
(* k 1.8))
(defn temperature-conversion [k]
(if (number? k)
(format "Celsius: %.2f Fahrenheit: %.2f Rankine: %.2f"
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(format "Error: Non-numeric value entered."))) |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Quackery | Quackery | [ factors size ] is tau ( n --> n )
[] []
100 times [ i^ 1+ tau join ]
witheach [ number$ nested join ]
70 wrap$
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #R | R | lengths(sapply(1:100, function(n) c(Filter(function(x) n %% x == 0, seq_len(n %/% 2)), n))) |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Raku | Raku | use Prime::Factor:ver<0.3.0+>;
use Lingua::EN::Numbers;
say "\nTau function - first 100:\n", # ID
(1..*).map({ +.&divisors })[^100]\ # the task
.batch(20)».fmt("%3d").join("\n"); # display formatting
say "\nTau numbers - first 100:\n", # ID
(1..*).grep({ $_ %% +.&divisors })[^100]\ # the task
.batch(10)».&comma».fmt("%5s").join("\n"); # display formatting
say "\nDivisor sums - first 100:\n", # ID
(1..*).map({ [+] .&divisors })[^100]\ # the task
.batch(20)».fmt("%4d").join("\n"); # display formatting
say "\nDivisor products - first 100:\n", # ID
(1..*).map({ [×] .&divisors })[^100]\ # the task
.batch(5)».&comma».fmt("%16s").join("\n"); # display formatting |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Ring | Ring | system('clear') |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Ruby | Ruby | system 'clear' |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Rust | Rust | print!("\x1B[2J"); |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Scala | Scala | object Cls extends App {print("\033[2J")} |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #Phix | Phix | enum T, M, F
type ternary(integer t) return find(t,{T,M,F}) end type
function t_not(ternary a)
return F+1-a
end function
function t_and(ternary a, ternary b)
return iff(a=T and b=T?T:iff(a=F or b=F?F:M))
end function
function t_or(ternary a, ternary b)
return iff(a=T or b=T?T:iff(a=F and b=F?F:M))
end function
function t_xor(ternary a, ternary b)
return iff(a=M or b=M?M:iff(a=b?F:T))
end function
function t_implies(ternary a, ternary b)
return iff(a=F or b=T?T:iff(a=T and b=F?F:M))
end function
function t_equal(ternary a, ternary b)
return iff(a=M or b=M?M:iff(a=b?T:F))
end function
function t_string(ternary a)
return iff(a=T?"T":iff(a=M?"?":"F"))
end function
procedure show_truth_table(integer rid, integer unary, string name)
printf(1,"%-3s |%s\n",{name,iff(unary?"":" T | ? | F")})
printf(1,"----+---%s\n",{iff(unary?"":"+---+---")})
for x=T to F do
printf(1," %s ",{t_string(x)})
if unary then
printf(1," | %s",{t_string(rid(x))})
else
for y=T to F do
printf(1," | %s",{t_string(rid(x,y))})
end for
end if
printf(1,"\n")
end for
printf(1,"\n")
end procedure
show_truth_table(t_not,1,"not")
show_truth_table(t_and,0,"and")
show_truth_table(t_or,0,"or")
show_truth_table(t_xor,0,"xor")
show_truth_table(t_implies,0,"imp")
show_truth_table(t_equal,0,"eq")
|
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 program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Racket | Racket | #lang racket
;; Use SRFI 48 to make %n.nf formats convenient.
(require (prefix-in srfi/48: srfi/48)) ; SRFI 48: Intermediate Format Strings
;; Parameter allows us to used exact decimal strings
(read-decimal-as-inexact #f)
;; files to read is a sequence, so it could be either a list or vector of files
(define (text-processing/1 files-to-read)
(define (print-line-info d r a t)
(srfi/48:format #t "Line: ~11F Reject: ~2F Accept: ~2F Line_tot: ~10,3F Line_avg: ~10,3F~%"
d r a t (if (zero? a) +nan.0 (/ t a))))
;; returns something that can be used as args to an apply
(define (handle-and-tag-max consecutive-false tag max-consecutive-false max-false-tags)
(let ((consecutive-false+1 (add1 consecutive-false)))
(list consecutive-false+1
(max max-consecutive-false consecutive-false+1)
(cond ((= consecutive-false+1 max-consecutive-false) (cons tag max-false-tags))
((= consecutive-false max-consecutive-false) (list tag))
(else max-false-tags)))))
(define (sub-t-p/1 N sum consecutive-false max-consecutive-false max-false-tags)
(for/fold ((N N) (sum sum) (consecutive-false consecutive-false) (max-consecutive-false max-consecutive-false) (max-false-tags max-false-tags))
((l (in-lines)))
(match l
[(app string-split `(,tag ,(app string->number vs.ss) ...))
(let get-line-pairs
((vs.ss vs.ss) (line-N 0) (reject 0) (line-sum 0) (consecutive-false consecutive-false)
(max-consecutive-false max-consecutive-false) (max-false-tags max-false-tags))
(match vs.ss
['()
(print-line-info tag reject line-N line-sum)
(values (+ N line-N) (+ sum line-sum) consecutive-false max-consecutive-false max-false-tags)]
[(list-rest v (? positive?) tl)
(get-line-pairs tl (add1 line-N) reject (+ line-sum v) 0 max-consecutive-false max-false-tags)]
[(list-rest _ _ tl)
(apply get-line-pairs tl line-N (add1 reject) line-sum
(handle-and-tag-max consecutive-false tag max-consecutive-false max-false-tags))]))]
(x (fprintf (current-error-port) "mismatch ~s~%" x)
(values N sum consecutive-false max-consecutive-false max-false-tags)))))
(for/fold ((N 0) (sum 0) (consecutive-false 0) (max-consecutive-false 0) (max-false-tags null))
((f files-to-read))
(with-input-from-file f
(lambda () (sub-t-p/1 N sum consecutive-false max-consecutive-false max-false-tags)))))
(let ((files (vector->list (current-command-line-arguments))))
(let-values (([N sum consecutive-false max-consecutive-false max-false-tags] (text-processing/1 files)))
(srfi/48:format #t "~%File(s) = ~a~%Total = ~10,3F~%Readings = ~6F~%" (string-join files) sum N)
(unless (zero? N) (srfi/48:format #t "Average = ~10,3F~%" (/ sum N)))
(srfi/48:format #t "~%Maximum run(s) of ~a consecutive false readings ends at line starting with date(s): ~a~%"
max-consecutive-false (string-join max-false-tags)))) |
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
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Objeck | Objeck |
class TwelveDaysOfChristmas {
function : Main(args : String[]) ~ Nil {
days := ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth",
"tenth", "eleventh", "twelfth"];
gifts := ["A partridge in a pear tree",
"Two turtle doves",
"Three french hens",
"Four calling birds",
"Five golden rings",
"Six geese a-laying",
"Seven swans a-swimming",
"Eight maids a-milking",
"Nine ladies dancing",
"Ten lords a-leaping",
"Eleven pipers piping",
"Twelve drummers drumming"];
for(i := 0; i < days->Size(); i+=1;) {
IO.Console->Print("On the ")->Print(days[i])->PrintLine(" day of Christmas, my true love gave to me");
j := i + 1;
while(j > 0 ) {
j -= 1;
gifts[j]->PrintLine();
};
IO.Console->PrintLine();
if (i = 0) {
gifts[0] := "And a partridge in a pear tree";
};
};
}
}
|
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Julia | Julia |
function inputlines(txtfile, iochannel)
for line in readlines(txtfile)
Base.put!(iochannel, line)
end
Base.put!(iochannel, nothing)
println("The other task printed $(take!(iochannel)) lines.")
end
function outputlines(iochannel)
totallines = 0
while (line = Base.take!(iochannel)) != nothing
totallines += 1
println(line)
end
Base.put!(iochannel, totallines)
end
c = Channel(0)
@async inputlines("filename.txt", c)
outputlines(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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Kotlin | Kotlin | import java.util.concurrent.SynchronousQueue
import kotlin.concurrent.thread
import java.io.File
const val EOT = "\u0004" // end of transmission
fun main(args: Array<String>) {
val queue = SynchronousQueue<String>()
val work = thread {
var count = 0
while (true) {
val line = queue.take()
if (line == EOT) {
queue.put(count.toString())
break
}
println(line)
count++
}
}
File("input.txt").forEachLine { line -> queue.put(line) }
queue.put(EOT)
work.join()
val count = queue.take().toInt()
println("\nNumber of lines printed = $count")
} |
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 zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #zkl | zkl | const NM="address.db";
dbExec(NM,"create table address (street, city, state, zip);"); |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Arturo | Arturo | print now |
http://rosettacode.org/wiki/System_time | System time | Task
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language.
The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
Related task
Date format
See also
Retrieving system time (wiki)
| #Asymptote | Asymptote | time();
time("%a %b %d %H:%M:%S %Z %Y");
//are equivalent ways of returning the current time in the default format used by the UNIX date command. |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
Task
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Spelling of ordinal numbers
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Also see
The On-Line Encyclopedia of Integer Sequences.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec_t rec_t;
struct rec_t {
int depth;
rec_t * p[10];
};
rec_t root = {0, {0}};
#define USE_POOL_ALLOC
#ifdef USE_POOL_ALLOC /* not all that big a deal */
rec_t *tail = 0, *head = 0;
#define POOL_SIZE (1 << 20)
inline rec_t *new_rec()
{
if (head == tail) {
head = calloc(sizeof(rec_t), POOL_SIZE);
tail = head + POOL_SIZE;
}
return head++;
}
#else
#define new_rec() calloc(sizeof(rec_t), 1)
#endif
rec_t *find_rec(char *s)
{
int i;
rec_t *r = &root;
while (*s) {
i = *s++ - '0';
if (!r->p[i]) r->p[i] = new_rec();
r = r->p[i];
}
return r;
}
/* speed up number to string conversion */
char number[100][4];
void init()
{
int i;
for (i = 0; i < 100; i++)
sprintf(number[i], "%d", i);
}
void count(char *buf)
{
int i, c[10] = {0};
char *s;
for (s = buf; *s; c[*s++ - '0']++);
for (i = 9; i >= 0; i--) {
if (!c[i]) continue;
s = number[c[i]];
*buf++ = s[0];
if ((*buf = s[1])) buf++;
*buf++ = i + '0';
}
*buf = '\0';
}
int depth(char *in, int d)
{
rec_t *r = find_rec(in);
if (r->depth > 0)
return r->depth;
d++;
if (!r->depth) r->depth = -d;
else r->depth += d;
count(in);
d = depth(in, d);
if (r->depth <= 0) r->depth = d + 1;
return r->depth;
}
int main(void)
{
char a[100];
int i, d, best_len = 0, n_best = 0;
int best_ints[32];
rec_t *r;
init();
for (i = 0; i < 1000000; i++) {
sprintf(a, "%d", i);
d = depth(a, 0);
if (d < best_len) continue;
if (d > best_len) {
n_best = 0;
best_len = d;
}
if (d == best_len)
best_ints[n_best++] = i;
}
printf("longest length: %d\n", best_len);
for (i = 0; i < n_best; i++) {
printf("%d\n", best_ints[i]);
sprintf(a, "%d", best_ints[i]);
for (d = 0; d <= best_len; d++) {
r = find_rec(a);
printf("%3d: %s\n", r->depth, a);
count(a);
}
putchar('\n');
}
return 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.
| #FreeBASIC | FreeBASIC | #include "isprime.bas"
print 1,2,2
dim as integer sum = 2, i, n=1
for i = 3 to 999 step 2
if isprime(i) then
sum += i
n+=1
if isprime(sum) then
print n, i, sum
end if
end if
next i |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum, n, c := 0, 0, 0
fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:")
fmt.Println(" n cumulative sum")
for _, p := range primes {
n++
sum += p
if rcu.IsPrime(sum) {
c++
fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum))
}
}
fmt.Println()
fmt.Println(c, "such prime sums found")
} |
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 polygon that do not need to be displayed.
Task
Take the closed polygon defined by the points:
[
(
50
,
150
)
,
(
200
,
50
)
,
(
350
,
150
)
,
(
350
,
300
)
,
(
250
,
300
)
,
(
200
,
250
)
,
(
150
,
350
)
,
(
100
,
250
)
,
(
100
,
200
)
]
{\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}
and clip it by the rectangle defined by the points:
[
(
100
,
100
)
,
(
300
,
100
)
,
(
300
,
300
)
,
(
100
,
300
)
]
{\displaystyle [(100,100),(300,100),(300,300),(100,300)]}
Print the sequence of points that define the resulting clipped polygon.
Extra credit
Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.
(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
| #J | J | NB. assumes counterclockwise orientation.
NB. determine whether point y is inside edge x.
isinside=:0< [:-/ .* {.@[ -~"1 {:@[,:]
NB. (p0,:p1) intersection (p2,:p3)
intersection=:|:@[ (+/ .* (,-.)) [:{. ,.&(-~/) %.~ -&{:
SutherlandHodgman=:4 :0 NB. clip S-H subject
clip=.2 ]\ (,{.) x
subject=.y
for_edge. clip do.
S=.{:input=.subject
subject=.0 2$0
for_E. input do.
if. edge isinside E do.
if. -.edge isinside S do.
subject=.subject,edge intersection S,:E end.
subject=.subject,E
elseif. edge isinside S do.
subject=.subject,edge intersection S,:E end.
S=.E
end.
end.
subject
) |
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\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #C.2B.2B | C++ | #include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;
int main( ) {
string setA[] = { "John", "Bob" , "Mary", "Serena" };
string setB[] = { "Jim" , "Mary", "John", "Bob" };
set<string>
firstSet( setA , setA + 4 ),
secondSet( setB , setB + 4 ),
symdiff;
set_symmetric_difference( firstSet.begin(), firstSet.end(),
secondSet.begin(), secondSet.end(),
inserter( symdiff, symdiff.end() ) );
copy( symdiff.begin(), symdiff.end(), ostream_iterator<string>( cout , " " ) );
cout << endl;
return 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 function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Perl | Perl | use strict;
use warnings;
use bigint;
use feature 'say';
sub super {
my $d = shift;
my $run = $d x $d;
my @super;
my $i = 0;
my $n = 0;
while ( $i < 10 ) {
if (index($n ** $d * $d, $run) > -1) {
push @super, $n;
++$i;
}
++$n;
}
@super;
}
say "\nFirst 10 super-$_ numbers:\n", join ' ', super($_) for 2..6; |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Phix | Phix | with javascript_semantics
include mpfr.e
procedure main()
atom t0 = time()
mpz k = mpz_init()
for i=2 to iff(platform()=JS?7:9) do
printf(1,"First 10 super-%d numbers:\n", i)
integer count := 0, j = 3
string tgt = repeat('0'+i,i)
while count<10 do
mpz_ui_pow_ui(k,j,i)
mpz_mul_si(k,k,i)
string s = mpz_get_str(k)
integer ix = match(tgt,s)
if ix then
count += 1
printf(1,"%d ", j)
end if
j += 1
end while
printf(1,"\nfound in %s\n\n", {elapsed(time()-t0)})
end for
end procedure
main()
|
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 all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #Groovy | Groovy | def notes = new File('./notes.txt')
if (args) {
notes << "${new Date().format('YYYY-MM-dd HH:mm:ss')}\t${args.join(' ')}\n"
} else {
println notes.text
}
|
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT.
If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
| #Haskell | Haskell | import System.Environment (getArgs)
import System.Time (getClockTime)
main :: IO ()
main = do
args <- getArgs
if null args
then catch (readFile "notes.txt" >>= putStr)
(\_ -> return ())
else
do ct <- getClockTime
appendFile "notes.txt" $ show ct ++ "\n\t" ++ unwords args ++ "\n" |
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 = b = 200
| #Julia | Julia | function superellipse(n, a, b, step::Int=100)
@assert n > 0 && a > 0 && b > 0
na = 2 / n
pc = 2π / step
t = 0
xp = Vector{Float64}(undef, step + 1)
yp = Vector{Float64}(undef, step + 1)
for i in 0:step
# because sin^n(x) is mathematically the same as (sin(x))^n...
xp[i+1] = abs((cos(t))) ^ na * a * sign(cos(t))
yp[i+1] = abs((sin(t))) ^ na * b * sign(sin(t))
t += pc
end
return xp, yp
end
using UnicodePlots
x, y = superellipse(2.5, 200, 200)
println(lineplot(x, y)) |
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 = b = 200
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import java.awt.geom.Path2D
import javax.swing.*
import java.lang.Math.pow
/* assumes a == b */
class SuperEllipse(val n: Double, val a: Int) : JPanel() {
init {
require(n > 0.0 && a > 0)
preferredSize = Dimension(650, 650)
background = Color.black
}
private fun drawEllipse(g: Graphics2D) {
val points = DoubleArray(a + 1)
val p = Path2D.Double()
p.moveTo(a.toDouble(), 0.0)
// calculate first quadrant
for (x in a downTo 0) {
points[x] = pow(pow(a.toDouble(), n) - pow(x.toDouble(), n), 1.0 / n)
p.lineTo(x.toDouble(), -points[x])
}
// mirror to others
for (x in 0..a) p.lineTo(x.toDouble(), points[x])
for (x in a downTo 0) p.lineTo(-x.toDouble(), points[x])
for (x in 0..a) p.lineTo(-x.toDouble(), -points[x])
with(g) {
translate(width / 2, height / 2)
color = Color.yellow
fill(p)
}
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
drawEllipse(g)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with (f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
title = "Super Ellipse"
isResizable = false
add(SuperEllipse(2.5, 200), BorderLayout.CENTER)
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
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
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #Pascal | Pascal | program taxiCabNo;
uses
sysutils;
type
tPot3 = Uint32;
tPot3Sol = record
p3Sum : tPot3;
i1,j1,
i2,j2 : Word;
end;
tpPot3 = ^tPot3;
tpPot3Sol = ^tPot3Sol;
var
//1290^3 = 2'146'689'000 < 2^31-1
//1190 is the magic number of the task ;-)
pot3 : array[0..1190{1290}] of tPot3;//
AllSol : array[0..3000] of tpot3Sol;
AllSolHigh : NativeInt;
procedure SolOut(const s:tpot3Sol;no: NativeInt);
begin
with s do
writeln(no:5,p3Sum:12,' = ',j1:5,'^3 +',i1:5,'^3 =',j2:5,'^3 +',i2:5,'^3');
end;
procedure InsertAllSol;
var
tmp: tpot3Sol;
p :tpPot3Sol;
p3Sum: tPot3;
i: NativeInt;
Begin
i := AllSolHigh;
IF i > 0 then
Begin
p := @AllSol[i];
tmp := p^;
p3Sum := p^.p3Sum;
//search the right place for insertion
repeat
dec(i);
dec(p);
IF (p^.p3Sum <= p3Sum) then
BREAK;
until (i<=0);
IF p^.p3Sum = p3Sum then
EXIT;
//free the right place by moving one place up
inc(i);
inc(p);
IF i<AllSolHigh then
Begin
move(p^,AllSol[i+1],SizeOf(AllSol[0])*(AllSolHigh-i));
p^ := tmp;
end;
end;
inc(AllSolHigh);
end;
function searchSameSum(var sol:tpot3Sol):boolean;
//try to find a new combination for the same sum
//within the limits given by lo and hi
var
Sum,
SumLo: tPot3;
hi,lo: NativeInt;
Begin
with Sol do
Begin
Sum := p3Sum;
lo:= i1;
hi:= j1;
end;
repeat
//Move hi down
dec(hi);
SumLo := Sum-Pot3[hi];
//Move lo up an check until new combination found or implicite lo> hi
repeat
inc(lo)
until (SumLo<=Pot3[lo]);
//found?
IF SumLo = Pot3[lo] then
BREAK;
until lo>=hi;
IF lo<hi then
Begin
sol.i2:= lo;
sol.j2:= hi;
searchSameSum := true;
end
else
searchSameSum := false;
end;
procedure Search;
var
i,j: LongInt;
Begin
AllSolHigh := 0;
For j := 2 to High(pot3)-1 do
Begin
For i := 1 to j-1 do
Begin
with AllSol[AllSolHigh] do
Begin
p3Sum:= pot3[i]+pot3[j];
i1:= i;
j1:= j;
end;
IF searchSameSum(AllSol[AllSolHigh]) then
BEGIN
InsertAllSol;
IF AllSolHigh>High(AllSol) then EXIT;
end;
end;
end;
end;
var
i: LongInt;
Begin
For i := Low(pot3) to High(pot3) do
pot3[i] := i*i*i;
AllSolHigh := 0;
Search;
For i := 0 to 24 do SolOut(AllSol[i],i+1);
For i := 1999 to 2005 do SolOut(AllSol[i],i+1);
writeln('count of solutions ',AllSolHigh);
end.
|
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'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Python | Python | "Generate a short Superpermutation of n characters A... as a string using various algorithms."
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
"""
Uses greedy algorithm of adding another char (or two, or three, ...)
until an unseen perm is formed in the last n chars
"""
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in permutations(allchars)]
sp, tofind = allperms[0], set(allperms[1:])
while tofind:
for skip in range(1, n):
for trial_add in (''.join(p) for p in permutations(sp[-n:][:skip])):
#print(sp, skip, trial_add)
trial_perm = (sp + trial_add)[-n:]
if trial_perm in tofind:
#print(sp, skip, trial_add)
sp += trial_add
tofind.discard(trial_perm)
trial_add = None # Sentinel
break
if trial_add is None:
break
assert all(perm in sp for perm in allperms) # Check it is a superpermutation
return sp
def s_perm1(n):
"""
Uses algorithm of concatenating all perms in order if not already part
of concatenation.
"""
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop()
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm2(n):
"""
Uses algorithm of concatenating all perms in order first-last-nextfirst-
nextlast... if not already part of concatenation.
"""
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
nxt = perms.pop(0)
if nxt not in sp:
sp += nxt
if perms:
nxt = perms.pop(-1)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def _s_perm3(n, cmp):
"""
Uses algorithm of concatenating all perms in order first,
next_with_LEASTorMOST_chars_in_same_position_as_last_n_chars, ...
"""
allchars = string.ascii_uppercase[:n]
allperms = [''.join(p) for p in sorted(permutations(allchars))]
perms, sp = allperms[::], ''
while perms:
lastn = sp[-n:]
nxt = cmp(perms,
key=lambda pm:
sum((ch1 == ch2) for ch1, ch2 in zip(pm, lastn)))
perms.remove(nxt)
if nxt not in sp:
sp += nxt
assert all(perm in sp for perm in allperms)
return sp
def s_perm3_max(n):
"""
Uses algorithm of concatenating all perms in order first,
next_with_MOST_chars_in_same_position_as_last_n_chars, ...
"""
return _s_perm3(n, max)
def s_perm3_min(n):
"""
Uses algorithm of concatenating all perms in order first,
next_with_LEAST_chars_in_same_position_as_last_n_chars, ...
"""
return _s_perm3(n, min)
longest = [factorial(n) * n for n in range(MAXN + 1)]
weight, runtime = {}, {}
print(__doc__)
for algo in [s_perm0, s_perm1, s_perm2, s_perm3_max, s_perm3_min]:
print('\n###\n### %s\n###' % algo.__name__)
print(algo.__doc__)
weight[algo.__name__], runtime[algo.__name__] = 1, datetime.timedelta(0)
for n in range(1, MAXN + 1):
gc.collect()
gc.disable()
t = datetime.datetime.now()
sp = algo(n)
t = datetime.datetime.now() - t
gc.enable()
runtime[algo.__name__] += t
lensp = len(sp)
wt = (lensp / longest[n]) ** 2
print(' For N=%i: SP length %5i Max: %5i Weight: %5.2f'
% (n, lensp, longest[n], wt))
weight[algo.__name__] *= wt
weight[algo.__name__] **= 1 / n # Geometric mean
weight[algo.__name__] = 1 / weight[algo.__name__]
print('%*s Overall Weight: %5.2f in %.1f seconds.'
% (29, '', weight[algo.__name__], runtime[algo.__name__].total_seconds()))
print('\n###\n### Algorithms ordered by shortest superpermutations first\n###')
print('\n'.join('%12s (%.3f)' % kv for kv in
sorted(weight.items(), key=lambda keyvalue: -keyvalue[1])))
print('\n###\n### Algorithms ordered by shortest runtime first\n###')
print('\n'.join('%12s (%.3f)' % (k, v.total_seconds()) for k, v in
sorted(runtime.items(), key=lambda keyvalue: keyvalue[1])))
|
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 zero.
The Fahrenheit and Rankine scales also have the same magnitude, but different null points.
0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.
0 degrees Rankine is absolute zero.
The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.
Task
Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result.
Example
K 21.00
C -252.15
F -421.87
R 37.80
| #CLU | CLU | kelvin = proc (k: real) returns (real)
return(k)
end kelvin
celsius = proc (k: real) returns (real)
return(k - 273.15)
end celsius
rankine = proc (k: real) returns (real)
return(k * 9./5.)
end rankine
fahrenheit = proc (k: real) returns (real)
return(rankine(k) - 459.67)
end fahrenheit
conv = struct[letter: char, func: proctype (real) returns (real)]
convs = sequence[conv]$[
conv${letter: 'K', func: kelvin},
conv${letter: 'C', func: celsius},
conv${letter: 'F', func: fahrenheit},
conv${letter: 'R', func: rankine}
]
start_up = proc ()
pi: stream := stream$primary_input()
po: stream := stream$primary_output()
stream$puts(po, "Enter temperature in Kelvin: ")
k: real := real$parse(stream$getl(pi))
for c: conv in sequence[conv]$elements(convs) do
stream$putc(po, c.letter)
stream$puts(po, " ")
stream$putl(po, f_form(c.func(k), 6, 2))
end
end start_up |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #REXX | REXX | /*REXX program counts the number of divisors (tau, or sigma_0) up to and including N.*/
parse arg LO HI cols . /*obtain optional argument from the CL.*/
if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= LO + 100 - 1 /*Not specified? Then use the default.*/
if cols=='' | cols=="," then cols= 20 /* " " " " " " */
w= 2 + (HI>45359) /*W: used to align the output columns.*/
say 'The number of divisors (tau) for integers up to ' n " (inclusive):"; say
say '─index─' center(" tau (number of divisors) ", cols * (w+1) + 1, '─')
$=; c= 0 /*$: the output list, shown ROW/line.*/
do j=LO to HI; c= c + 1 /*list # proper divisors (tau) 1 ──► N */
$= $ right( tau(j), w) /*add a tau number to the output list. */
if c//cols \== 0 then iterate /*Not a multiple of ROW? Don't display.*/
idx= j - cols + 1 /*calculate index value (for this row).*/
say center(idx, 7) $; $= /*display partial list to the terminal.*/
end /*j*/
if $\=='' then say center(idx+cols, 7) $ /*there any residuals left to display ?*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tau: procedure; parse arg x 1 y /*X and $ are both set from the arg.*/
if x<6 then return 2 + (x==4) - (x==1) /*some low #s should be handled special*/
odd= x // 2 /*check if X is odd (remainder of 1).*/
if odd then #= 2 /*Odd? Assume divisor count of 2. */
else do; #= 4; y= x % 2; end /*Even? " " " " 4. */
/* [↑] start with known number of divs*/
do j=3 for x%2-3 by 1+odd while j<y /*for odd number, skip even numbers. */
if x//j==0 then do /*if no remainder, then found a divisor*/
#= # + 2; y= x % j /*bump # of divisors; calculate limit.*/
if j>=y then do; #= # - 1; leave; end /*reached limit?*/
end /* ___ */
else if j*j>x then leave /*only divide up to √ x */
end /*j*/; return # /* [↑] this form of DO loop is faster.*/ |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "console.s7i";
const proc: main is func
local
var text: console is STD_NULL;
begin
console := open(CONSOLE);
clear(console);
# Terminal windows often restore the previous
# content, when a program is terminated. Therefore
# the program waits until Return/Enter is pressed.
readln;
end func; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Sidef | Sidef | func clear { print(static x = `clear`) };
clear(); |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Smalltalk | Smalltalk | Transcript clear. |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #PHP | PHP | #!/usr/bin/php
<?php
# defined as numbers, so I can use max() and min() on it
if (! define('triFalse',0)) trigger_error('Unknown error defining!', E_USER_ERROR);
if (! define('triMaybe',1)) trigger_error('Unknown error defining!', E_USER_ERROR);
if (! define('triTrue', 2)) trigger_error('Unknown error defining!', E_USER_ERROR);
$triNotarray = array(triFalse=>triTrue, triMaybe=>triMaybe, triTrue=>triFalse);
# output helper
function triString ($tri) {
if ($tri===triFalse) return 'false ';
if ($tri===triMaybe) return 'unknown';
if ($tri===triTrue) return 'true ';
trigger_error('triString: parameter not a tri value', E_USER_ERROR);
}
function triAnd() {
if (func_num_args() < 2)
trigger_error('triAnd needs 2 or more parameters', E_USER_ERROR);
return min(func_get_args());
}
function triOr() {
if (func_num_args() < 2)
trigger_error('triOr needs 2 or more parameters', E_USER_ERROR);
return max(func_get_args());
}
function triNot($t) {
global $triNotarray; # using result table
if (in_array($t, $triNotarray)) return $triNotarray[$t];
trigger_error('triNot: Parameter is not a tri value', E_USER_ERROR);
}
function triImplies($a, $b) {
if ($a===triFalse || $b===triTrue) return triTrue;
if ($a===triMaybe || $b===triMaybe) return triMaybe;
# without parameter type check I just would return triFalse here
if ($a===triTrue && $b===triFalse) return triFalse;
trigger_error('triImplies: parameter type error', E_USER_ERROR);
}
function triEquiv($a, $b) {
if ($a===triTrue) return $b;
if ($a===triMaybe) return $a;
if ($a===triFalse) return triNot($b);
trigger_error('triEquiv: parameter type error', E_USER_ERROR);
}
# data sampling
printf("--- Sample output for a equivalent b ---\n\n");
foreach ([triTrue,triMaybe,triFalse] as $a) {
foreach ([triTrue,triMaybe,triFalse] as $b) {
printf("for a=%s and b=%s a equivalent b is %s\n",
triString($a), triString($b), triString(triEquiv($a, $b)));
}
}
|
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Raku | Raku | my @gaps;
my $previous = 'valid';
for $*IN.lines -> $line {
my ($date, @readings) = split /\s+/, $line;
my @valid;
my $hour = 0;
for @readings -> $reading, $flag {
if $flag > 0 {
@valid.push($reading);
if $previous eq 'invalid' {
@gaps[*-1]{'end'} = "$date $hour:00";
$previous = 'valid';
}
}
else
{
if $previous eq 'valid' {
@gaps.push( {start => "$date $hour:00"} );
}
@gaps[*-1]{'count'}++;
$previous = 'invalid';
}
$hour++;
}
say "$date: { ( +@valid ?? ( ( [+] @valid ) / +@valid ).fmt("%.3f") !! 0 ).fmt("%8s") }",
" mean from { (+@valid).fmt("%2s") } valid.";
};
my $longest = @gaps.sort({-$^a<count>})[0];
say "Longest period of invalid readings was {$longest<count>} hours,\n",
"from {$longest<start>} till {$longest<end>}." |
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas | The Twelve Days of Christmas | Task
Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas.
The lyrics can be found here.
(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PARI.2FGP | PARI/GP | days=["first","second","third","fourth","fifth","sixth","seventh","eighth","ninth","tenth","eleventh","twelfth"];
gifts=["And a partridge in a pear tree.", "Two turtle doves", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming"];
{
for(i=1,#days,
print("On the "days[i]" day of Christmas, my true love gave to me:");
forstep(j=i,2,-1,print("\t"gifts[j]", "));
print(if(i==1,"\tA partridge in a pear tree.",Str("\t",gifts[1])))
)
} |
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Logtalk | Logtalk |
:- object(team).
:- threaded.
:- public(start/0).
start :-
threaded((
reader,
writer(0)
)).
reader :-
open('input.txt', read, Stream),
repeat,
read_term(Stream, Term, []),
threaded_notify(term(Term)),
Term == end_of_file,
!,
close(Stream),
threaded_wait(lines(Lines)),
write('Number of lines: '), write(Lines), nl.
writer(N0) :-
threaded_wait(term(Term)),
( Term == end_of_file ->
threaded_notify(lines(N0))
; N is N0 + 1,
write(Term), nl,
writer(N)
).
:- end_object.
|
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 the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #Lua | Lua | function ReadFile()
local fp = io.open( "input.txt" )
assert( fp ~= nil )
for line in fp:lines() do
coroutine.yield( line )
end
fp:close()
end
co = coroutine.create( ReadFile )
while true do
local status, val = coroutine.resume( co )
if coroutine.status( co ) == "dead" then break end
print( val )
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
Retrieving system time (wiki)
| #AutoHotkey | AutoHotkey | FormatTime, t
MsgBox,% t |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms generated grow in length geometrically and never converge.
Another way to generate a self-referential sequence is to summarize the previous term.
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
0, 10, 1110, 3110, 132110, 13123110, 23124110 ...
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
Task
Find all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted.
Seed Value(s): 9009 9090 9900
Iterations: 21
Sequence: (same for all three seeds except for first element)
9009
2920
192210
19222110
19323110
1923123110
1923224110
191413323110
191433125110
19151423125110
19251413226110
1916151413325110
1916251423127110
191716151413326110
191726151423128110
19181716151413327110
19182716151423129110
29181716151413328110
19281716151423228110
19281716151413427110
19182716152413228110
Related tasks
Fours is the number of letters in the ...
Look-and-say sequence
Number names
Self-describing numbers
Spelling of ordinal numbers
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Also see
The On-Line Encyclopedia of Integer Sequences.
| #C.2B.2B | C++ |
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
std::map<char, int> _map;
std::vector<std::string> _result;
size_t longest = 0;
void make_sequence( std::string n ) {
_map.clear();
for( std::string::iterator i = n.begin(); i != n.end(); i++ )
_map.insert( std::make_pair( *i, _map[*i]++ ) );
std::string z;
for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {
char c = ( *i ).second + 48;
z.append( 1, c );
z.append( 1, i->first );
}
if( longest <= z.length() ) {
longest = z.length();
if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {
_result.push_back( z );
make_sequence( z );
}
}
}
int main( int argc, char* argv[] ) {
std::vector<std::string> tests;
tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" );
for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {
make_sequence( *i );
std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n";
for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {
std::cout << *j << "\n";
}
std::cout << "\n\n";
}
return 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.
| #Go | Go | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(999)
sum, n, c := 0, 0, 0
fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:")
fmt.Println(" n cumulative sum")
for _, p := range primes {
n++
sum += p
if rcu.IsPrime(sum) {
c++
fmt.Printf("%3d %6s\n", n, rcu.Commatize(sum))
}
}
fmt.Println()
fmt.Println(c, "such prime sums found")
} |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Haskell | Haskell | import Data.List (scanl)
import Data.Numbers.Primes (isPrime, primes)
--------------- PRIME SUMS OF FIRST N PRIMES -------------
indexedPrimeSums :: [(Integer, Integer, Integer)]
indexedPrimeSums =
filter (\(_, _, n) -> isPrime n) $
scanl
(\(i, _, m) p -> (succ i, p, p + m))
(0, 0, 0)
primes
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_ print $
takeWhile (\(_, p, _) -> 1000 > p) indexedPrimeSums
|
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 polygon that do not need to be displayed.
Task
Take the closed polygon defined by the points:
[
(
50
,
150
)
,
(
200
,
50
)
,
(
350
,
150
)
,
(
350
,
300
)
,
(
250
,
300
)
,
(
200
,
250
)
,
(
150
,
350
)
,
(
100
,
250
)
,
(
100
,
200
)
]
{\displaystyle [(50,150),(200,50),(350,150),(350,300),(250,300),(200,250),(150,350),(100,250),(100,200)]}
and clip it by the rectangle defined by the points:
[
(
100
,
100
)
,
(
300
,
100
)
,
(
300
,
300
)
,
(
100
,
300
)
]
{\displaystyle [(100,100),(300,100),(300,300),(100,300)]}
Print the sequence of points that define the resulting clipped polygon.
Extra credit
Display all three polygons on a graphical surface, using a different color for each polygon and filling the resulting polygon.
(When displaying you may use either a north-west or a south-west origin, whichever is more convenient for your display mechanism.)
| #Java | Java | import java.awt.*;
import java.awt.geom.Line2D;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class SutherlandHodgman extends JFrame {
SutherlandHodgmanPanel panel;
public static void main(String[] args) {
JFrame f = new SutherlandHodgman();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public SutherlandHodgman() {
Container content = getContentPane();
content.setLayout(new BorderLayout());
panel = new SutherlandHodgmanPanel();
content.add(panel, BorderLayout.CENTER);
setTitle("SutherlandHodgman");
pack();
setLocationRelativeTo(null);
}
}
class SutherlandHodgmanPanel extends JPanel {
List<double[]> subject, clipper, result;
public SutherlandHodgmanPanel() {
setPreferredSize(new Dimension(600, 500));
// these subject and clip points are assumed to be valid
double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};
double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};
subject = new ArrayList<>(Arrays.asList(subjPoints));
result = new ArrayList<>(subject);
clipper = new ArrayList<>(Arrays.asList(clipPoints));
clipPolygon();
}
private void clipPolygon() {
int len = clipper.size();
for (int i = 0; i < len; i++) {
int len2 = result.size();
List<double[]> input = result;
result = new ArrayList<>(len2);
double[] A = clipper.get((i + len - 1) % len);
double[] B = clipper.get(i);
for (int j = 0; j < len2; j++) {
double[] P = input.get((j + len2 - 1) % len2);
double[] Q = input.get(j);
if (isInside(A, B, Q)) {
if (!isInside(A, B, P))
result.add(intersection(A, B, P, Q));
result.add(Q);
} else if (isInside(A, B, P))
result.add(intersection(A, B, P, Q));
}
}
}
private boolean isInside(double[] a, double[] b, double[] c) {
return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);
}
private double[] intersection(double[] a, double[] b, double[] p, double[] q) {
double A1 = b[1] - a[1];
double B1 = a[0] - b[0];
double C1 = A1 * a[0] + B1 * a[1];
double A2 = q[1] - p[1];
double B2 = p[0] - q[0];
double C2 = A2 * p[0] + B2 * p[1];
double det = A1 * B2 - A2 * B1;
double x = (B2 * C1 - B1 * C2) / det;
double y = (A1 * C2 - A2 * C1) / det;
return new double[]{x, y};
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.translate(80, 60);
g2.setStroke(new BasicStroke(3));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawPolygon(g2, subject, Color.blue);
drawPolygon(g2, clipper, Color.red);
drawPolygon(g2, result, Color.green);
}
private void drawPolygon(Graphics2D g2, List<double[]> points, Color color) {
g2.setColor(color);
int len = points.size();
Line2D line = new Line2D.Double();
for (int i = 0; i < len; i++) {
double[] p1 = points.get(i);
double[] p2 = points.get((i + 1) % len);
line.setLine(p1[0], p1[1], p2[0], p2[1]);
g2.draw(line);
}
}
} |
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\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Clojure | Clojure | (use '[clojure.set])
(defn symmetric-difference [s1 s2]
(union (difference s1 s2) (difference s2 s1)))
(symmetric-difference #{:john :bob :mary :serena} #{:jim :mary :john :bob}) |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\cap B)}
(the set of items that are in at least one of A or B minus the set of items that are in both A and B).
Optionally, give the individual differences (
A
∖
B
{\displaystyle A\setminus B}
and
B
∖
A
{\displaystyle B\setminus A}
) as well.
Test cases
A = {John, Bob, Mary, Serena}
B = {Jim, Mary, John, Bob}
Notes
If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing sets of a = ["John", "Serena", "Bob", "Mary", "Serena"] and b = ["Jim", "Mary", "John", "Jim", "Bob"] should produce the result of just two strings: ["Serena", "Jim"], in any order.
In the mathematical notation above A \ B gives the set of items in A that are not in B; A ∪ B gives the set of items in both A and B, (their union); and A ∩ B gives the set of items that are in both A and B (their intersection).
| #Common_Lisp | Common Lisp | (set-exclusive-or
(remove-duplicates '(John Serena Bob Mary Serena))
(remove-duplicates '(Jim Mary John Jim Bob))) |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Python | Python | from itertools import islice, count
def superd(d):
if d != int(d) or not 2 <= d <= 9:
raise ValueError("argument must be integer from 2 to 9 inclusive")
tofind = str(d) * d
for n in count(2):
if tofind in str(d * n ** d):
yield n
if __name__ == '__main__':
for d in range(2, 9):
print(f"{d}:", ', '.join(str(n) for n in islice(superd(d), 10))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.