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/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).
| #FreeBASIC | FreeBASIC |
redim shared as string Result(-1) 'represent our sets as strings;
'this'll do to illustrate the concept
sub sym( A() as string, B() as string )
dim as integer ai, bi, ri
dim as boolean add_it
for ai = lbound(A) to ubound(A)
add_it = true
for bi = lbound(B) to ubound(B)
if A(ai) = B(bi) then
add_it=false
exit for 'if item is common to both lists, don't include it
end if
next bi
if add_it then
for ri = 0 to ubound(Result)
if A(ai) = Result(ri) then
add_it=false
exit for
'if item is already in the result, don't include it again
end if
next ri
end if
if add_it then
redim preserve as string Result(0 to ubound(Result)+1)
Result(ubound(Result)) = A(ai)
end if
next ai
end sub
dim as string A(0 to 3) = {"John", "Bob", "Mary", "Serena"}
dim as string B(0 to 4) = {"Jim", "Mary", "John", "Bob", "Jim"}
'contains a double to show code can handle it
sym(A(), B())
sym(B(), A())
for i as uinteger = 0 to ubound(Result)
print Result(i)
next i
|
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.
| #PHP | PHP |
#!/usr/bin/php
<?php
if ($argc > 1)
file_put_contents(
'notes.txt',
date('r')."\n\t".implode(' ', array_slice($argv, 1))."\n",
FILE_APPEND
);
else
@readfile('notes.txt');
|
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.
| #PicoLisp | PicoLisp | #!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(load "@lib/misc.l")
(if (argv)
(out "+notes.txt" (prinl (stamp) "^J^I" (glue " " @)))
(and (info "notes.txt") (in "notes.txt" (echo))) )
(bye) |
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
| #Racket | Racket | #lang racket
(require plot)
#;(plot-new-window? #t)
(define ((superellipse a b n) x y)
(+ (expt (abs (/ x a)) n)
(expt (abs (/ y b)) n)))
(plot (isoline (superellipse 200 200 2.5) 1
-220 220 -220 220)) |
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
| #Raku | Raku | constant a = 200;
constant b = 200;
constant n = 2.5;
# y in terms of x
sub y ($x) { sprintf "%d", b * (1 - ($x / a).abs ** n ) ** (1/n) }
# find point pairs for one quadrant
my @q = flat map -> \x { x, y(x) }, (0, 1 ... 200);
# Generate an SVG image
INIT say qq:to/STOP/;
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="{b*2}" width="{a*2}" version="1.1" xmlns="http://www.w3.org/2000/svg">
STOP
END say '</svg>';
.put for
pline( @q ),
pline( @q «*» ( 1,-1) ), # flip and mirror
pline( @q «*» (-1,-1) ), # for the other
pline( @q «*» (-1, 1) ); # three quadrants
sub pline (@q) {
qq:to/END/;
<polyline points="{@q}"
style="fill:none; stroke:black; stroke-width:3" transform="translate({a}, {b})" />
END
} |
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).
| #Sidef | Sidef | var (start=1, end=25) = ARGV.map{.to_i}...
func display (h, start, end) {
var i = start
for n in [h.grep {|_,v| v.len > 1 }.keys.sort_by{.to_i}[start-1 .. end-1]] {
printf("%4d %10d =>\t%s\n", i++, n,
h{n}.map{ "%4d³ + %-s" % (.first, "#{.last}³") }.join(",\t"))
}
}
var taxi = Hash()
var taxis = 0
var terminate = 0
for c1 (1..Inf) {
if (0<terminate && terminate<c1) {
display(taxi, start, end)
break
}
var c = c1**3
for c2 (1..c1) {
var this = (c2**3 + c)
taxi{this} := [] << [c2, c1]
++taxis if (taxi{this}.len == 2)
if (taxis==end && !terminate) {
terminate = taxi.grep{|_,v| v.len > 1 }.keys.map{.to_i}.max.root(3)
}
}
} |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute 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
| #F.23 | F# |
// Define units of measure
[<Measure>] type k
[<Measure>] type f
[<Measure>] type c
[<Measure>] type r
// Define conversion functions
let kelvinToCelsius (t : float<k>) = ((float t) - 273.15) * 1.0<c>
let kelvinToFahrenheit (t : float<k>) = (((float t) * 1.8) - 459.67) * 1.0<f>
let kelvinToRankine (t : float<k>) = ((float t) * 1.8) * 1.0<r>
// Example code
let K = 21.0<k>
printfn "%A Kelvin is %A Celsius" K (kelvinToCelsius K)
printfn "%A Kelvin is %A Fahrenheit" K (kelvinToFahrenheit K)
printfn "%A Kelvin is %A Rankine" K (kelvinToRankine K)
|
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
| #Run_BASIC | Run BASIC | testFalse = 0 ' F
testDoNotKnow = 1 ' ?
testTrue = 2 ' T
print "Short and long names for ternary logic values"
for i = testFalse to testTrue
print shortName3$(i);" ";longName3$(i)
next i
print
print "Single parameter functions"
print "x";" ";"=x";" ";"not(x)"
for i = testFalse to testTrue
print shortName3$(i);" ";shortName3$(i);" ";shortName3$(not3(i))
next
print
print "Double parameter fuctions"
html "<table border=1><TR align=center bgcolor=wheat><TD>x</td><td>y</td><td>x AND y</td><td>x OR y</td><td>x EQ y</td><td>x XOR y</td></tr>"
for a = testFalse to testTrue
for b = testFalse to testTrue
html "<TR align=center><td>"
html shortName3$(a); "</td><td>";shortName3$(b); "</td><td>"
html shortName3$(and3(a,b));"</td><td>";shortName3$(or3(a,b)); "</td><td>"
html shortName3$(eq3(a,b)); "</td><td>";shortName3$(xor3(a,b));"</td></tr>"
next
next
html "</table>"
function and3(a,b)
and3 = min(a,b)
end function
function or3(a,b)
or3 = max(a,b)
end function
function eq3(a,b)
eq3 = testFalse
if a = tDontKnow or b = tDontKnow then eq3 = tDontKnow
if a = b then eq3 = testTrue
end function
function xor3(a,b)
xor3 = not3(eq3(a,b))
end function
function not3(b)
not3 = 2-b
end function
'------------------------------------------------
function shortName3$(i)
shortName3$ = word$("F ? T", i+1)
end function
function longName3$(i)
longName3$ = word$("False,Don't know,True", i+1, ",")
end function |
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
| #Rust | Rust | use std::{ops, fmt};
#[derive(Copy, Clone, Debug)]
enum Trit {
True,
Maybe,
False,
}
impl ops::Not for Trit {
type Output = Self;
fn not(self) -> Self {
match self {
Trit::True => Trit::False,
Trit::Maybe => Trit::Maybe,
Trit::False => Trit::True,
}
}
}
impl ops::BitAnd for Trit {
type Output = Self;
fn bitand(self, other: Self) -> Self {
match (self, other) {
(Trit::True, Trit::True) => Trit::True,
(Trit::False, _) | (_, Trit::False) => Trit::False,
_ => Trit::Maybe,
}
}
}
impl ops::BitOr for Trit {
type Output = Self;
fn bitor(self, other: Self) -> Self {
match (self, other) {
(Trit::True, _) | (_, Trit::True) => Trit::True,
(Trit::False, Trit::False) => Trit::False,
_ => Trit::Maybe,
}
}
}
impl Trit {
fn imp(self, other: Self) -> Self {
match self {
Trit::True => other,
Trit::Maybe => {
if let Trit::True = other {
Trit::True
} else {
Trit::Maybe
}
}
Trit::False => Trit::True,
}
}
fn eqv(self, other: Self) -> Self {
match self {
Trit::True => other,
Trit::Maybe => Trit::Maybe,
Trit::False => !other,
}
}
}
impl fmt::Display for Trit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Trit::True => 'T',
Trit::Maybe => 'M',
Trit::False => 'F',
}
)
}
}
static TRITS: [Trit; 3] = [Trit::True, Trit::Maybe, Trit::False];
fn main() {
println!("not");
println!("-------");
for &t in &TRITS {
println!(" {} | {}", t, !t);
}
table("and", |a, b| a & b);
table("or", |a, b| a | b);
table("imp", |a, b| a.imp(b));
table("eqv", |a, b| a.eqv(b));
}
fn table(title: &str, f: impl Fn(Trit, Trit) -> Trit) {
println!();
println!("{:3} | T M F", title);
println!("-------------");
for &t1 in &TRITS {
print!(" {} | ", t1);
for &t2 in &TRITS {
print!("{} ", f(t1, t2));
}
println!();
}
} |
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.
| #Wren | Wren | import "io" for File
import "/pattern" for Pattern
import "/fmt" for Fmt
var p = Pattern.new("+1/s")
var fileName = "readings.txt"
var lines = File.read(fileName).trimEnd().split("\r\n")
var f = "Line: $s Reject: $2d Accept: $2d Line_tot: $8.3f Line_avg: $7.3f"
var grandTotal = 0
var readings = 0
var date = ""
var run = 0
var maxRun = -1
var finishLine = ""
for (line in lines) {
var fields = p.splitAll(line)
date = fields[0]
if (fields.count == 49) {
var accept = 0
var total = 0
var i = 1
while (i < fields.count) {
if (Num.fromString(fields[i+1]) >= 1) {
accept = accept + 1
total = total + Num.fromString(fields[i])
if (run > maxRun) {
maxRun = run
finishLine = date
}
run = 0
} else {
run = run + 1
}
i = i + 2
}
grandTotal = grandTotal + total
readings = readings + accept
Fmt.print(f, date, 24-accept, accept, total, total/accept)
} else {
Fmt.print("Line: $s does not have 49 fields and has been ignored", date)
}
}
if (run > maxRun) {
maxRun = run
finishLine = date
}
var average = grandTotal / readings
Fmt.print("\nFile = $s", fileName)
Fmt.print("Total = $0.3f", grandTotal)
Fmt.print("Readings = $d", readings)
Fmt.print("Average = $0.3f", average)
Fmt.print("\nMaximum run of $d consecutive false readings", maxRun)
Fmt.print("ends at line starting with date: $s", finishLine) |
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
| #q | q |
days:" "vs"first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth"
gifts:(
"Twelve drummers drumming";
"Eleven pipers piping";
"Ten lords a-leaping";
"Nine ladies dancing";
"Eight maids a-milking";
"Seven swans a-swimming";
"Six geese a-laying";
"Five golden rings";
"Four calling birds";
"Three french hens";
"Two turtle doves";
"And a partridge in a pear tree.";
"")
verses:stanza 0 1,/:{(reverse x)+2+til each 2+x}til 12
lyric:raze .[;0 2;{"A",5_x}] verses{@[x;0;ssr[;"twelfth";y]]}'days
1 "\n"sv lyric; // print
|
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.
| #Python | Python | import sys
from Queue import Queue
from threading import Thread
lines = Queue(1)
count = Queue(1)
def read(file):
try:
for line in file:
lines.put(line)
finally:
lines.put(None)
print count.get()
def write(file):
n = 0
while 1:
line = lines.get()
if line is None:
break
file.write(line)
n += 1
count.put(n)
reader = Thread(target=read, args=(open('input.txt'),))
writer = Thread(target=write, args=(sys.stdout,))
reader.start()
writer.start()
reader.join()
writer.join() |
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)
| #Crystal | Crystal | # current time in system's time zone:
Time.local
# current time in UTC
Time.utc
# monotonic time (useful for measuring elapsed time)
Time.monotonic
|
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)
| #D | D | Stdout(Clock.now.span.days / 365).newline; |
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.
| #Go | Go | package main
import (
"fmt"
"strconv"
)
func main() {
var maxLen int
var seqMaxLen [][]string
for n := 1; n < 1e6; n++ {
switch s := seq(n); {
case len(s) == maxLen:
seqMaxLen = append(seqMaxLen, s)
case len(s) > maxLen:
maxLen = len(s)
seqMaxLen = [][]string{s}
}
}
fmt.Println("Max sequence length:", maxLen)
fmt.Println("Sequences:", len(seqMaxLen))
for _, seq := range seqMaxLen {
fmt.Println("Sequence:")
for _, t := range seq {
fmt.Println(t)
}
}
}
func seq(n int) []string {
s := strconv.Itoa(n)
ss := []string{s}
for {
dSeq := sortD(s)
d := dSeq[0]
nd := 1
s = ""
for i := 1; ; i++ {
if i == len(dSeq) {
s = fmt.Sprintf("%s%d%c", s, nd, d)
break
}
if dSeq[i] == d {
nd++
} else {
s = fmt.Sprintf("%s%d%c", s, nd, d)
d = dSeq[i]
nd = 1
}
}
for _, s0 := range ss {
if s == s0 {
return ss
}
}
ss = append(ss, s)
}
panic("unreachable")
}
func sortD(s string) []rune {
r := make([]rune, len(s))
for i, d := range s {
j := 0
for ; j < i; j++ {
if d > r[j] {
copy(r[j+1:], r[j:i])
break
}
}
r[j] = d
}
return r
} |
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.)
| #PureBasic | PureBasic | Structure point_f
x.f
y.f
EndStructure
Procedure isInside(*p.point_f, *cp1.point_f, *cp2.point_f)
If (*cp2\x - *cp1\x) * (*p\y - *cp1\y) > (*cp2\y - *cp1\y) * (*p\x - *cp1\x)
ProcedureReturn 1
EndIf
EndProcedure
Procedure intersection(*cp1.point_f, *cp2.point_f, *s.point_f, *e.point_f, *newPoint.point_f)
Protected.point_f dc, dp
Protected.f n1, n2, n3
dc\x = *cp1\x - *cp2\x: dc\y = *cp1\y - *cp2\y
dp\x = *s\x - *e\x: dp\y = *s\y - *e\y
n1 = *cp1\x * *cp2\y - *cp1\y * *cp2\x
n2 = *s\x * *e\y - *s\y * *e\x
n3 = 1 / (dc\x * dp\y - dc\y * dp\x)
*newPoint\x = (n1 * dp\x - n2 * dc\x) * n3: *newPoint\y = (n1 * dp\y - n2 * dc\y) * n3
EndProcedure
Procedure clip(List vPolygon.point_f(), List vClippedBy.point_f(), List vClippedPolygon.point_f())
Protected.point_f cp1, cp2, s, e, newPoint
CopyList(vPolygon(), vClippedPolygon())
If LastElement(vClippedBy())
cp1 = vClippedBy()
NewList vPreClipped.point_f()
ForEach vClippedBy()
cp2 = vClippedBy()
CopyList(vClippedPolygon(), vPreClipped())
ClearList(vClippedPolygon())
If LastElement(vPreClipped())
s = vPreClipped()
ForEach vPreClipped()
e = vPreClipped()
If isInside(e, cp1, cp2)
If Not isInside(s, cp1, cp2)
intersection(cp1, cp2, s, e, newPoint)
AddElement(vClippedPolygon()): vClippedPolygon() = newPoint
EndIf
AddElement(vClippedPolygon()): vClippedPolygon() = e
ElseIf isInside(s, cp1, cp2)
intersection(cp1, cp2, s, e, newPoint)
AddElement(vClippedPolygon()): vClippedPolygon() = newPoint
EndIf
s = e
Next
EndIf
cp1 = cp2
Next
EndIf
EndProcedure
DataSection
Data.f 50,150, 200,50, 350,150, 350,300, 250,300, 200,250, 150,350, 100,250, 100,200 ;subjectPolygon's vertices (x,y)
Data.f 100,100, 300,100, 300,300, 100,300 ;clipPolygon's vertices (x,y)
EndDataSection
NewList subjectPolygon.point_f()
For i = 1 To 9
AddElement(subjectPolygon())
Read.f subjectPolygon()\x
Read.f subjectPolygon()\y
Next
NewList clipPolygon.point_f()
For i = 1 To 4
AddElement(clipPolygon())
Read.f clipPolygon()\x
Read.f clipPolygon()\y
Next
NewList newPolygon.point_f()
clip(subjectPolygon(), clipPolygon(), newPolygon())
If OpenConsole()
ForEach newPolygon()
PrintN("(" + StrF(newPolygon()\x, 2) + ", " + StrF(newPolygon()\y, 2) + ")")
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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).
| #Frink | Frink | A = new set["John", "Bob", "Mary", "Serena"]
B = new set["Jim", "Mary", "John", "Bob"]
println["Symmetric difference: " + symmetricDifference[A,B]]
println["A - B : " + setDifference[A,B]]
println["B - A : " + setDifference[B,A]] |
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).
| #GAP | GAP | SymmetricDifference := function(a, b)
return Union(Difference(a, b), Difference(b, a));
end;
a := ["John", "Serena", "Bob", "Mary", "Serena"];
b := ["Jim", "Mary", "John", "Jim", "Bob"];
SymmetricDifference(a,b);
[ "Jim", "Serena" ] |
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.
| #PL.2FI | PL/I | NOTES: procedure (text) options (main); /* 8 April 2014 */
declare text character (100) varying;
declare note_file file;
on undefinedfile(note_file) go to file_does_not_exist;
open file (note_file) title ('/NOTES.TXT,recsize(100),type(text)');
revert error;
if text = '' then
do;
on endfile (note_file) stop;
do forever;
get file (note_file) edit (text) (L);
put skip list (text);
end;
end;
close file (note_file);
open file (note_file) output title ('/NOTES.TXT,recsize(100),type(text),append(y)');
put file (note_file) skip list (DATETIME('DDMmmYYYY'), TIME());
put file (note_file) skip list (text);
put file (note_file) skip;
put skip list ('Appended ' || text || ' to file');
return;
file_does_not_exist:
revert undefinedfile (note_file);
close file (note_file);
open file (note_file) output title ('/NOTES.TXT,recsize(100),type(text)');
put file (note_file) skip list (DATETIME('DDMmmYYYY'), TIME());
put file (note_file) skip list (text);
put file (note_file) skip;
put skip list ('The file, NOTES.TXT, has been created');
end NOTES; |
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.
| #PowerShell | PowerShell | $notes = "notes.txt"
if (($args).length -eq 0) {
if(Test-Path $notes) {
Get-Content $notes
}
} else {
Get-Date | Add-Content $notes
"`t" + $args -join " " | Add-Content $notes
} |
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
| #REXX | REXX | /* REXX ***************************************************************
* Create a BMP file showing a few super ellipses
**********************************************************************/
Parse Version v
If pos('Regina',v)>0 Then
superegg='superegga.bmp'
Else
superegg='supereggo.bmp'
'erase' superegg
s='424d4600000000000000360000002800000038000000280000000100180000000000'X||,
'1000000000000000000000000000000000000000'x
z.0=0
black='000000'x
white='ffffff'x
red ='00ff00'x
green='ff0000'x
blue ='0000ff'x
m=80
n=80
hor=m*8 /* 56 */
ver=n*8 /* 40 */
s=overlay(lend(hor),s,19,4)
s=overlay(lend(ver),s,23,4)
z.=copies('f747ff'x,3192%3)
z.=copies('ffffff'x,8*m)
z.0=648
u=320
v=320
Call supegg black,080,080,0.5,u,v
Call supegg black,110,110,1 ,u,v
Call supegg black,140,140,1.5,u,v
Call supegg blue ,170,170,2 ,u,v
Call supegg red ,200,200,2.5,u,v
Call supegg green,230,230,3 ,u,v
Call supegg black,260,260,4 ,u,v
Call supegg black,290,290,7 ,u,v
Do i=1 To z.0
s=s||z.i
End
Call lineout superegg,s
Call lineout superegg
Exit
supegg:
Parse Arg color,a,b,n,u,v
Do y=0 To b
t=(1-power(y/b,n))
x=a*power(t,1/n)
Call point color,format(u+x,4,0),format(v+y,4,0)
Call point color,format(u-x,4,0),format(v+y,4,0)
Call point color,format(u+x,4,0),format(v-y,4,0)
Call point color,format(u-x,4,0),format(v-y,4,0)
End
Do x=0 To a
t=(1-power(x/b,n))
y=a*power(t,1/n)
Call point color,format(u+x,4,0),format(v+y,4,0)
Call point color,format(u-x,4,0),format(v+y,4,0)
Call point color,format(u+x,4,0),format(v-y,4,0)
Call point color,format(u-x,4,0),format(v-y,4,0)
End
Return
lend:
Return reverse(d2c(arg(1),4))
point: Procedure Expose z.
Call trace 'O'
Parse Arg color,x0,y0
--Say x0 y0
Do x=x0-2 To x0+2
Do y=y0-2 To y0+2
z.y=overlay(copies(color,3),z.y,3*x)
End
End
Return
power: Procedure
/***********************************************************************
* Return b**x for any x -- with reasonable or specified precision
* 920903 Walter Pachl
***********************************************************************/
Parse Arg b,x,prec
If prec<9 Then prec=9
Numeric Digits (2*prec)
Numeric Fuzz 3
If b=0 Then Return 0
If b<>'' Then x=x*ln(b,prec+2)
o=1
u=1
r=1
Do i=1 By 1
ra=r
o=o*x
u=u*i
r=r+(o/u)
If r=ra Then Leave
End
Numeric Digits (prec)
Return r+0
ln: Procedure
/***********************************************************************
* Return ln(x) -- with specified precision
* Three different series are used for the ranges 0 to 0.5
* 0.5 to 1.5
* 1.5 to infinity
* 920903 Walter Pachl
***********************************************************************/
Parse Arg x,prec,b
If prec='' Then prec=9
Numeric Digits (2*prec)
Numeric Fuzz 3
Select
When x<=0 Then r='*** invalid argument ***'
When x<0.5 Then Do
z=(x-1)/(x+1)
o=z
r=z
k=1
Do i=3 By 2
ra=r
k=k+1
o=o*z*z
r=r+o/i
If r=ra Then Leave
End
r=2*r
End
When x<1.5 Then Do
z=(x-1)
o=z
r=z
k=1
Do i=2 By 1
ra=r
k=k+1
o=-o*z
r=r+o/i
If r=ra Then Leave
End
End
Otherwise /* 1.5<=x */ Do
z=(x+1)/(x-1)
o=1/z
r=o
k=1
Do i=3 By 2
ra=r
k=k+1
o=o/(z*z)
r=r+o/i
If r=ra Then Leave
End
r=2*r
End
End
If b<>'' Then
r=r/ln(b)
Numeric Digits (prec)
Return r+0 |
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).
| #Swift | Swift | extension Array {
func combinations(_ k: Int) -> [[Element]] {
return Self._combinations(slice: self[startIndex...], k)
}
static func _combinations(slice: Self.SubSequence, _ k: Int) -> [[Element]] {
guard k != 1 else {
return slice.map({ [$0] })
}
guard k != slice.count else {
return [slice.map({ $0 })]
}
let chopped = slice[slice.index(after: slice.startIndex)...]
var res = _combinations(slice: chopped, k - 1).map({ [[slice.first!], $0].flatMap({ $0 }) })
res += _combinations(slice: chopped, k)
return res
}
}
let cubes = (1...).lazy.map({ $0 * $0 * $0 })
let taxis =
Array(cubes.prefix(1201))
.combinations(2)
.reduce(into: [Int: [[Int]]](), { $0[$1[0] + $1[1], default: []].append($1) })
let res =
taxis
.lazy
.filter({ $0.value.count > 1 })
.sorted(by: { $0.key < $1.key })
.map({ ($0.key, $0.value) })
.prefix(2006)
print("First 25 taxicab numbers:")
for taxi in res[..<25] {
print(taxi)
}
print("\n2000th through 2006th taxicab numbers:")
for taxi in res[1999..<2006] {
print(taxi)
} |
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).
| #Tcl | Tcl | package require Tcl 8.6
proc heappush {heapName item} {
upvar 1 $heapName heap
set idx [lsearch -bisect -index 0 -integer $heap [lindex $item 0]]
set heap [linsert $heap [expr {$idx + 1}] $item]
}
coroutine cubesum apply {{} {
yield
set h {}
set n 1
while true {
while {![llength $h] || [lindex $h 0 0] > $n**3} {
heappush h [list [expr {$n**3 + 1}] $n 1]
incr n
}
set h [lassign $h item]
yield $item
lassign $item s x y
if {[incr y] < $x} {
heappush h [list [expr {$x**3 + $y**3}] $x $y]
}
}
}}
coroutine taxis apply {{} {
yield
set out {{0 0 0}}
while true {
set s [cubesum]
if {[lindex $s 0] == [lindex $out end 0]} {
lappend out $s
} else {
if {[llength $out] > 1} {yield $out}
set out [list $s]
}
}
}}
# Put a cache in front for convenience
variable taxis {}
proc taxi {n} {
variable taxis
while {$n > [llength $taxis]} {lappend taxis [taxis]}
return [lindex $taxis [expr {$n-1}]]
}
set 3 "\u00b3"
for {set n 1} {$n <= 25} {incr n} {
puts ${n}:[join [lmap t [taxi $n] {format " %d = %d$3 + %d$3" {*}$t}] ","]
}
for {set n 2000} {$n <= 2006} {incr n} {
puts ${n}:[join [lmap t [taxi $n] {format " %d = %d$3 + %d$3" {*}$t}] ","]
} |
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
| #Factor | Factor | USING: combinators formatting kernel math ;
IN: rosetta-code.temperature
: k>c ( kelvin -- celsius ) 273.15 - ;
: k>r ( kelvin -- rankine ) 9/5 * ;
: k>f ( kelvin -- fahrenheit ) k>r 459.67 - ;
: convert ( kelvin -- )
{ [ ] [ k>c ] [ k>f ] [ k>r ] } cleave
"K %.2f\nC %.2f\nF %.2f\nR %.2f\n" printf ;
21 convert |
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
| #Scala | Scala | sealed trait Trit { self =>
def nand(that:Trit):Trit=(this,that) match {
case (TFalse, _) => TTrue
case (_, TFalse) => TTrue
case (TMaybe, _) => TMaybe
case (_, TMaybe) => TMaybe
case _ => TFalse
}
def nor(that:Trit):Trit = this.or(that).not()
def and(that:Trit):Trit = this.nand(that).not()
def or(that:Trit):Trit = this.not().nand(that.not())
def not():Trit = this.nand(this)
def imply(that:Trit):Trit = this.nand(that.not())
def equiv(that:Trit):Trit = this.and(that).or(this.nor(that))
}
case object TTrue extends Trit
case object TMaybe extends Trit
case object TFalse extends Trit
object TernaryLogic extends App {
val v=List(TTrue, TMaybe, TFalse)
println("- NOT -")
for(a<-v) println("%6s => %6s".format(a, a.not))
println("\n- AND -")
for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a and b))
println("\n- OR -")
for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a or b))
println("\n- Imply -")
for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a imply b))
println("\n- Equiv -")
for(a<-v; b<-v) println("%6s : %6s => %6s".format(a, b, a equiv b))
} |
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
| #Quackery | Quackery | [ [ table
$ "first" $ "second" $ "third" $ "fourth"
$ "fifth" $ "sixth" $ "seventh" $ "eighth"
$ "ninth" $ "tenth" $ "eleventh" $ "twelfth" ]
do echo$ ] is day ( n --> )
[ [ table
$ "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," ] do echo$ ] is gift ( n --> )
[ say "On the " dup day say " day of Christmas," cr
say "My true love gave to me," cr
1+ times [ i gift cr ] cr ] is verse ( n --> )
[ 12 times [ i^ verse ] ] is song ( --> )
song |
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
| #R | R |
gifts <- c("A partridge in a pear tree.", "Two turtle doves and", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying", "Seven swans a-swimming", "Eight maids a-milking", "Nine ladies dancing", "Ten lords a-leaping", "Eleven pipers piping", "Twelve drummers drumming")
days <- c("first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth")
for (i in seq_along(days)) {
cat("On the", days[i], "day of Christmas\n")
cat("My true love gave to me:\n")
cat(paste(gifts[i:1], collapse = "\n"), "\n\n")
} |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use 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.
| #Racket | Racket |
(define (reader)
(for ([line (in-lines (open-input-file "input.txt"))])
(thread-send printer-thread line))
(thread-send printer-thread eof)
(printf "Number of lines: ~a\n" (thread-receive)))
(define (printer)
(thread-send reader-thread
(for/sum ([line (in-producer thread-receive eof)])
(displayln line)
1)))
(define printer-thread (thread printer))
(define reader-thread (thread reader))
(for-each thread-wait
(list printer-thread reader-thread))
|
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.
| #Raku | Raku | sub MAIN ($infile) {
$infile.IO.lines ==> printer() ==> my $count;
say "printed $count lines";
}
sub printer(*@lines) {
my $lines;
for @lines {
.say;
++$lines;
}
$lines;
} |
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)
| #DBL | DBL | XCALL TIME (D6) ;D6=hhmmss |
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)
| #DCL | DCL | $ start_time = f$time()
$ wait 0::10
$ end_time = f$time()
$ write sys$output "start time was ", start_time
$ write sys$output "end time was ", end_time
$ write sys$output "delta time is ", f$delta_time( start_time, end_time ) |
http://rosettacode.org/wiki/Summarize_and_say_sequence | Summarize and say sequence | There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...
The terms 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.
| #Groovy | Groovy | Number.metaClass.getSelfReferentialSequence = {
def number = delegate as String; def sequence = []
while (!sequence.contains(number)) {
sequence << number
def encoded = new StringBuilder()
((number as List).sort().join('').reverse() =~ /(([0-9])\2*)/).each { matcher, text, digit ->
encoded.append(text.size()).append(digit)
}
number = encoded.toString()
}
sequence
}
def maxSeqSize = { List values ->
values.inject([seqSize: 0, seeds: []]) { max, n ->
if (n % 100000 == 99999) println 'HT'
else if (n % 10000 == 9999) print '.'
def seqSize = n.selfReferentialSequence.size()
switch (seqSize) {
case max.seqSize: max.seeds << n
case { it < max.seqSize }: return max
default: return [seqSize: seqSize, seeds: [n]]
}
}
} |
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.)
| #Python | Python |
def clip(subjectPolygon, clipPolygon):
def inside(p):
return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])
def computeIntersection():
dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]
dp = [ s[0] - e[0], s[1] - e[1] ]
n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]
n2 = s[0] * e[1] - s[1] * e[0]
n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0])
return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]
outputList = subjectPolygon
cp1 = clipPolygon[-1]
for clipVertex in clipPolygon:
cp2 = clipVertex
inputList = outputList
outputList = []
s = inputList[-1]
for subjectVertex in inputList:
e = subjectVertex
if inside(e):
if not inside(s):
outputList.append(computeIntersection())
outputList.append(e)
elif inside(s):
outputList.append(computeIntersection())
s = e
cp1 = cp2
return(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).
| #Go | Go | package main
import "fmt"
var a = map[string]bool{"John": true, "Bob": true, "Mary": true, "Serena": true}
var b = map[string]bool{"Jim": true, "Mary": true, "John": true, "Bob": true}
func main() {
sd := make(map[string]bool)
for e := range a {
if !b[e] {
sd[e] = true
}
}
for e := range b {
if !a[e] {
sd[e] = true
}
}
fmt.Println(sd)
} |
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.
| #PureBasic | PureBasic | #FileName="notes.txt"
Define argc=CountProgramParameters()
If OpenConsole()
If argc=0
If ReadFile(0,#FileName)
While Eof(0)=0
PrintN(ReadString(0)) ; No new notes, so present the old
Wend
CloseFile(0)
EndIf
Else ; e.g. we have some arguments
Define d$=FormatDate("%yyyy-%mm-%dd %hh:%ii:%ss",date())
If OpenFile(0,#FileName)
Define args$=""
While argc
args$+" "+ProgramParameter() ; Read all arguments
argc-1
Wend
FileSeek(0,Lof(0)) ; Go to the end of this file
WriteStringN(0,d$+#CRLF$+#TAB$+args$) ; Append date & note
CloseFile(0)
EndIf
EndIf
EndIf |
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
| #Scala | Scala | import java.awt._
import java.awt.geom.Path2D
import java.util
import javax.swing._
import javax.swing.event.{ChangeEvent, ChangeListener}
object SuperEllipse extends App {
SwingUtilities.invokeLater(() => {
new JFrame("Super Ellipse") {
class SuperEllipse extends JPanel with ChangeListener {
setPreferredSize(new Dimension(650, 650))
setBackground(Color.white)
setFont(new Font("Serif", Font.PLAIN, 18))
private var exp = 2.5
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawGrid(g: Graphics2D): Unit = {
g.setStroke(new BasicStroke(2))
g.setColor(new Color(0xEEEEEE))
val w = getWidth
val h = getHeight
val spacing = 25
for (i <- 0 until (w / spacing)) {
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)
}
def drawLegend(g: Graphics2D): Unit = {
g.setColor(Color.black)
g.setFont(getFont)
g.drawString("n = " + String.valueOf(exp), getWidth - 150, 45)
g.drawString("a = b = 200", getWidth - 150, 75)
}
def drawEllipse(g: Graphics2D): Unit = {
val a = 200
// calculate first quadrant
val points = Array.tabulate(a + 1)(n =>
math.pow(math.pow(a, exp) - math.pow(n, exp), 1 / exp))
val p = new Path2D.Double
p.moveTo(a, 0)
for (n <- a to 0 by -1) p.lineTo(n, -points(n))
// mirror to others
for (x <- points.indices) p.lineTo(x, points(x))
for (y <- a to 0 by -1) p.lineTo(-y, points(y))
for (z <- points.indices) p.lineTo(-z, -points(z))
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)
}
super.paintComponent(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 def stateChanged(e: ChangeEvent): Unit = {
val source = e.getSource.asInstanceOf[JSlider]
exp = source.getValue / 2.0
repaint()
}
}
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setResizable(false)
val panel = new SuperEllipse
add(panel, BorderLayout.CENTER)
val exponent = new JSlider(SwingConstants.HORIZONTAL, 1, 9, 5)
exponent.addChangeListener(panel)
exponent.setBackground(Color.white)
exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20))
exponent.setMajorTickSpacing(1)
exponent.setPaintLabels(true)
val labelTable = new util.Hashtable[Integer, JLabel]
for (i <- 1 until 10) labelTable.put(i, new JLabel(String.valueOf(i * 0.5)))
exponent.setLabelTable(labelTable)
add(exponent, BorderLayout.SOUTH)
pack()
setLocationRelativeTo(null)
setVisible(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).
| #VBA | VBA | Public Type tuple
i As Variant
j As Variant
sum As Variant
End Type
Public Type tuple3
i1 As Variant
j1 As Variant
i2 As Variant
j2 As Variant
i3 As Variant
j3 As Variant
sum As Variant
End Type
Sub taxicab_numbers()
Dim i As Variant, j As Variant
Dim k As Long
Const MAX = 2019
Dim p(MAX) As Variant
Const bigMAX = (MAX + 1) * (MAX / 2)
Dim big(1 To bigMAX) As tuple
Const resMAX = 4400
Dim res(1 To resMAX) As tuple3
For i = 1 To MAX
p(i) = CDec(i * i * i) 'convert Variant to Decimal
Next i 'wich hold numbers upto 10^28
k = 1
For i = 1 To MAX
For j = i To MAX
big(k).i = CDec(i)
big(k).j = CDec(j)
big(k).sum = CDec(p(i) + p(j))
k = k + 1
Next j
Next i
n = 1
Quicksort big, LBound(big), UBound(big)
For i = 1 To bigMAX - 1
If big(i).sum = big(i + 1).sum Then
res(n).i1 = CStr(big(i).i)
res(n).j1 = CStr(big(i).j)
res(n).i2 = CStr(big(i + 1).i)
res(n).j2 = CStr(big(i + 1).j)
If big(i + 1).sum = big(i + 2).sum Then
res(n).i3 = CStr(big(i + 2).i)
res(n).j3 = CStr(big(i + 2).j)
i = i + 1
End If
res(n).sum = CStr(big(i).sum)
n = n + 1
i = i + 1
End If
Next i
Debug.Print n - 1; " taxis"
For i = 1 To 25
With res(i)
Debug.Print String$(4 - Len(CStr(i)), " "); i;
Debug.Print String$(11 - Len(.sum), " "); .sum; " = ";
Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +";
Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = ";
Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +";
Debug.Print String$(4 - Len(.j2), " "); .j2; "^3"
End With
Next i
Debug.Print
For i = 2000 To 2006
With res(i)
Debug.Print String$(4 - Len(CStr(i)), " "); i;
Debug.Print String$(11 - Len(.sum), " "); .sum; " = ";
Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +";
Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = ";
Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +";
Debug.Print String$(4 - Len(.j2), " "); .j2; "^3"
End With
Next i
Debug.Print
For i = 1 To resMAX
If res(i).i3 <> "" Then
With res(i)
Debug.Print String$(4 - Len(CStr(i)), " "); i;
Debug.Print String$(11 - Len(.sum), " "); .sum; " = ";
Debug.Print String$(4 - Len(.i1), " "); .i1; "^3 +";
Debug.Print String$(4 - Len(.j1), " "); .j1; "^3 = ";
Debug.Print String$(4 - Len(.i2), " "); .i2; "^3 +";
Debug.Print String$(4 - Len(.j2), " "); .j2; "^3";
Debug.Print String$(4 - Len(.i3), " "); .i3; "^3 +";
Debug.Print String$(4 - Len(.j3), " "); .j3; "^3"
End With
End If
Next i
End Sub
Sub Quicksort(vArray() As tuple, arrLbound As Long, arrUbound As Long)
'https://wellsr.com/vba/2018/excel/vba-quicksort-macro-to-sort-arrays-fast/
'Sorts a one-dimensional VBA array from smallest to largest
'using a very fast quicksort algorithm variant.
'Adapted to multidimensions/typedef
Dim pivotVal As Variant
Dim vSwap As tuple
Dim tmpLow As Long
Dim tmpHi As Long
tmpLow = arrLbound
tmpHi = arrUbound
pivotVal = vArray((arrLbound + arrUbound) \ 2).sum
While (tmpLow <= tmpHi) 'divide
While (vArray(tmpLow).sum < pivotVal And tmpLow < arrUbound)
tmpLow = tmpLow + 1
Wend
While (pivotVal < vArray(tmpHi).sum And tmpHi > arrLbound)
tmpHi = tmpHi - 1
Wend
If (tmpLow <= tmpHi) Then
vSwap.i = vArray(tmpLow).i
vSwap.j = vArray(tmpLow).j
vSwap.sum = vArray(tmpLow).sum
vArray(tmpLow).i = vArray(tmpHi).i
vArray(tmpLow).j = vArray(tmpHi).j
vArray(tmpLow).sum = vArray(tmpHi).sum
vArray(tmpHi).i = vSwap.i
vArray(tmpHi).j = vSwap.j
vArray(tmpHi).sum = vSwap.sum
tmpLow = tmpLow + 1
tmpHi = tmpHi - 1
End If
Wend
If (arrLbound < tmpHi) Then Quicksort vArray, arrLbound, tmpHi 'conquer
If (tmpLow < arrUbound) Then Quicksort vArray, tmpLow, arrUbound 'conquer
End Sub |
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
| #FOCAL | FOCAL | 01.10 ASK "TEMPERATURE IN KELVIN", K
01.20 TYPE "K ", %6.02, K, !
01.30 TYPE "C ", %6.02, K - 273.15, !
01.40 TYPE "F ", %6.02, K * 1.8 - 459.67, !
01.50 TYPE "R ", %6.02, K * 1.8, ! |
http://rosettacode.org/wiki/Temperature_conversion | Temperature conversion | There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones:
Kelvin, Celsius, Fahrenheit, and Rankine.
The Celsius and Kelvin scales have the same magnitude, but different null points.
0 degrees Celsius corresponds to 273.15 kelvin.
0 kelvin is absolute 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
| #Forth | Forth | : k>°C ( F: kelvin -- celsius ) 273.15e0 f- ;
: k>°R ( F: kelvin -- rankine ) 1.8e0 f* ;
: °R>°F ( F: rankine -- fahrenheit ) 459.67e0 f- ;
: k>°F ( F: kelvin -- fahrenheit ) k>°R °R>°F ;
: main
argc 1 > if 1 arg >float
fdup f. ." K" cr
fdup k>°C f. ." °C" cr
fdup k>°F f. ." °F" cr
fdup k>°R f. ." °R" cr
then ;
main bye |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: trit is new enum
False, Maybe, True
end enum;
# Enum types define comparisons (=, <, >, <=, >=, <>) and
# the conversions ord and conv.
const func string: str (in trit: aTrit) is
return [] ("False", "Maybe", "True")[succ(ord(aTrit))];
enable_output(trit); # Allow writing trit values
const array trit: tritNot is [] (True, Maybe, False);
const array array trit: tritAnd is [] (
[] (False, False, False),
[] (False, Maybe, Maybe),
[] (False, Maybe, True ));
const array array trit: tritOr is [] (
[] (False, Maybe, True ),
[] (Maybe, Maybe, True ),
[] (True, True, True ));
const array array trit: tritXor is [] (
[] (False, Maybe, True ),
[] (Maybe, Maybe, Maybe),
[] (True, Maybe, False));
const array array trit: tritImplies is [] (
[] (True, True, True ),
[] (Maybe, Maybe, True ),
[] (False, Maybe, True ));
const array array trit: tritEquiv is [] (
[] (True, Maybe, False),
[] (Maybe, Maybe, Maybe),
[] (False, Maybe, True ));
const func trit: not (in trit: aTrit) is
return tritNot[succ(ord(aTrit))];
const func trit: (in trit: aTrit1) and (in trit: aTrit2) is
return tritAnd[succ(ord(aTrit1))][succ(ord(aTrit2))];
const func trit: (in trit: aTrit1) and (ref func trit: aTrit2) is func
result
var trit: res is False;
begin
if aTrit1 = True then
res := aTrit2;
elsif aTrit1 = Maybe and aTrit2 <> False then
res := Maybe;
end if;
end func;
const func trit: (in trit: aTrit1) or (in trit: aTrit2) is
return tritOr[succ(ord(aTrit1))][succ(ord(aTrit2))];
const func trit: (in trit: aTrit1) or (ref func trit: aTrit2) is func
result
var trit: res is True;
begin
if aTrit1 = False then
res := aTrit2;
elsif aTrit1 = Maybe and aTrit2 <> True then
res := Maybe;
end if;
end func;
$ syntax expr: .().xor.() is -> 15;
const func trit: (in trit: aTrit1) xor (in trit: aTrit2) is
return tritImplies[succ(ord(aTrit1))][succ(ord(aTrit2))];
const func trit: (in trit: aTrit1) -> (in trit: aTrit2) is
return tritImplies[succ(ord(aTrit1))][succ(ord(aTrit2))];
const func trit: (in trit: aTrit1) == (in trit: aTrit2) is
return tritEquiv[succ(ord(aTrit1))][succ(ord(aTrit2))];
const func trit: rand (in trit: low, in trit: high) is
return trit conv (rand(ord(low), ord(high)));
# Begin of test code
var trit: operand1 is False;
var trit: operand2 is False;
const proc: writeTable (ref func trit: tritExpr, in string: name) is func
begin
writeln;
writeln(" " <& name rpad 7 <& " | False Maybe True");
writeln("---------+---------------------");
for operand1 range False to True do
write(" " <& operand1 rpad 7 <& " | ");
for operand2 range False to True do
write(tritExpr rpad 7);
end for;
writeln;
end for;
end func;
const proc: main is func
begin
writeln(" not" rpad 8 <& " | False Maybe True");
writeln("---------+---------------------");
write(" | ");
for operand1 range False to True do
write(not operand1 rpad 7);
end for;
writeln;
writeTable(operand1 and operand2, "and");
writeTable(operand1 or operand2, "or");
writeTable(operand1 xor operand2, "xor");
writeTable(operand1 -> operand2, "->");
writeTable(operand1 == operand2, "==");
end func; |
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
| #Racket | Racket | #lang racket
(define (ordinal-text d)
(vector-ref
(vector
"zeroth" "first" "second" "third" "fourth"
"fifth" "sixth" "seventh" "eighth" "ninth"
"tenth" "eleventh" "twelfth")
d))
(define (on-the... day)
(printf "On the ~a day of Christmas,~%" (ordinal-text day))
(printf "My True Love gave to me,~%"))
(define (prezzy prezzy-line day)
(match prezzy-line
[1 (string-append (if (= day 1) "A " "And a")" partridge in a pear tree")]
[2 "Two turtle doves"]
[3 "Three French hens"]
[4 "Four calling birds"]
[5 "FIVE GO-OLD RINGS"]
[6 "Six geese a-laying"]
[7 "Seven swans a-swimming"]
[8 "Eight maids a-milking"]
[9 "Nine ladies dancing"]
[10 "Ten lords a-leaping"]
[11 "Eleven pipers piping"]
[12 "Twelve drummers drumming"]))
(define (line-end prezzy-line day)
(match* (day prezzy-line) [(12 1) "."] [(x 1) ".\n"] [(_ _) ","]))
(for ((day (sequence-map add1 (in-range 12)))
#:when (on-the... day)
(prezzy-line (in-range day 0 -1)))
(printf "~a~a~%" (prezzy prezzy-line day) (line-end prezzy-line day))) |
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
| #Raku | Raku | my @days = <first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth>;
my @gifts = lines q:to/END/;
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,
END
sub nth($n) { say "On the @days[$n] day of Christmas, my true love gave to me:" }
nth(0);
say @gifts[0].subst('And a','A');
for 1 ... 11 -> $d {
say '';
nth($d);
say @gifts[$_] for $d ... 0;
} |
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.
| #Raven | Raven | 'input.txt' as src_file
class Queue
new list as items
condition as ready
define item_put
items push ready notify
define item_get
items empty if ready wait
items shift
Queue as lines
Queue as count
thread reader
"file://r:%(src_file)s" open each lines.item_put
NULL lines.item_put count.item_get "reader: %d\n" print
thread writer
0 repeat lines.item_get dup while
"writer: %s" print 1+
drop count.item_put
reader as r
writer as w |
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.
| #Ruby | Ruby | count = 0
IO.foreach("input.txt") { |line| print line; count += 1 }
puts "Printed #{count} lines." |
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)
| #Delphi | Delphi | lblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', 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)
| #DWScript | DWScript | PrintLn(FormatDateTime('dd mmmm yyyy hh:mm:ss', Now)); |
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.
| #Haskell | Haskell | import Data.Set (Set, member, insert, empty)
import Data.List (group, sort)
step :: String -> String
step = concatMap (\list -> show (length list) ++ [head list]) . group . sort
findCycle :: (Ord a) => [a] -> [a]
findCycle = aux empty where
aux set (x : xs)
| x `member` set = []
| otherwise = x : aux (insert x set) xs
select :: [[a]] -> [[a]]
select = snd . foldl (\(len, acc) xs -> case len `compare` length xs of
LT -> (length xs, [xs])
EQ -> (len, xs : acc)
GT -> (len, acc)) (0, [])
main :: IO ()
main = mapM_ (mapM_ print) $ -- Print out all the numbers
select $ -- find the longest ones
map findCycle $ -- run the sequences until there is a repeat
map (iterate step) $ -- produce the sequence
map show -- turn the numbers into digits
[1..1000000] -- The input seeds
|
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.)
| #Racket | Racket | #lang racket
(module sutherland-hodgman racket
(provide clip-to)
(provide make-edges)
(provide (struct-out point))
(struct point (x y) #:transparent)
(struct edge (p1 p2) #:transparent)
(struct polygon (points edges) #:transparent)
(define (make-edges points)
(let ([points-shifted
(match points
[(list a b ...) (append b (list a))])])
(map edge points points-shifted)))
(define (is-point-left? pt ln)
(match-let ([(point x y) pt]
[(edge (point px py) (point qx qy)) ln])
(>= (* (- qx px) (- y py))
(* (- qy py) (- x px)))))
;; Return the intersection of two lines
(define (isect-lines l1 l2)
(match-let ([(edge (point x1 y1) (point x2 y2)) l1]
[(edge (point x3 y3) (point x4 y4)) l2])
(let* ([r (- (* x1 y2) (* y1 x2))] [s (- (* x3 y4) (* y3 x4))]
[t (- x1 x2)] [u (- y3 y4)] [v (- y1 y2)] [w (- x3 x4)]
[d (- (* t u) (* v w))])
(point (/ (- (* 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.
(define (intersect segment clip-line)
(define (isect) (isect-lines segment clip-line))
(match-let ([(edge p0 p1) segment])
(match/values (values (is-point-left? p0 clip-line) (is-point-left? p1 clip-line))
[(#f #f) '()]
[(#f #t) (list (isect) p1)]
[(#t #f) (list (isect))]
[(#t #t) (list p1)])))
;; Intersect the polygon with the clipping line's left halfspace
(define (isect-polygon poly-edges clip-line)
(for/fold ([p '()]) ([e poly-edges])
(append p (intersect e clip-line))))
;; Intersect a subject polygon with a clipping polygon. The latter is assumed to be convex.
(define (clip-to sp-pts cp-edges)
(for/fold ([out-poly sp-pts]) ([clip-line cp-edges])
(isect-polygon (make-edges out-poly) clip-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).
| #Groovy | Groovy | def symDiff = { Set s1, Set s2 ->
assert s1 != null
assert s2 != null
(s1 + s2) - (s1.intersect(s2))
} |
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).
| #Haskell | Haskell | import Data.Set
a = fromList ["John", "Bob", "Mary", "Serena"]
b = fromList ["Jim", "Mary", "John", "Bob"]
(-|-) :: Ord a => Set a -> Set a -> Set a
x -|- y = (x \\ y) `union` (y \\ x)
-- Equivalently: (x `union` y) \\ (x `intersect` y) |
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.
| #Python | Python | import sys, datetime, shutil
if len(sys.argv) == 1:
try:
with open('notes.txt', 'r') as f:
shutil.copyfileobj(f, sys.stdout)
except IOError:
pass
else:
with open('notes.txt', 'a') as f:
f.write(datetime.datetime.now().isoformat() + '\n')
f.write("\t%s\n" % ' '.join(sys.argv[1:])) |
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.
| #R | R | #!/usr/bin/env Rscript --default-packages=methods
args <- commandArgs(trailingOnly=TRUE)
if (length(args) == 0) {
conn <- file("notes.txt", 'r')
cat(readLines(conn), sep="\n")
} else {
conn <- file("notes.txt", 'a')
cat(file=conn, date(), "\n\t", paste(args, collapse=" "), "\n", sep="")
}
close(conn) |
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
| #Sidef | Sidef | const (
a = 200,
b = 200,
n = 2.5,
)
# y in terms of x
func y(x) { b * (1 - abs(x/a)**n -> root(n)) -> int }
func pline(q) {
<<-"EOT";
<polyline points="#{q.join(' ')}"
style="fill:none; stroke:black; stroke-width:3" transform="translate(#{a}, #{b})" />
EOT
}
# Generate an SVG image
say <<-"EOT"
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="#{b*2}" width="#{a*2}" version="1.1" xmlns="http://www.w3.org/2000/svg">
EOT
# find point pairs for one quadrant
var q = { |x| (x, y(x)) }.map(0..200 `by` 2)
[
pline(q),
pline(q »*« [ 1,-1]), # flip and mirror
pline(q »*« [-1,-1]), # for the other
pline(q »*« [-1, 1]), # three quadrants
].each { .print }
say '</svg>' |
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).
| #Visual_Basic_.NET | Visual Basic .NET |
Imports System.Text
Module Module1
Function GetTaxicabNumbers(length As Integer) As IDictionary(Of Long, IList(Of Tuple(Of Integer, Integer)))
Dim sumsOfTwoCubes As New SortedList(Of Long, IList(Of Tuple(Of Integer, Integer)))
For i = 1 To Integer.MaxValue - 1
For j = 1 To Integer.MaxValue - 1
Dim sum = CLng(Math.Pow(i, 3) + Math.Pow(j, 3))
If Not sumsOfTwoCubes.ContainsKey(sum) Then
sumsOfTwoCubes.Add(sum, New List(Of Tuple(Of Integer, Integer)))
End If
sumsOfTwoCubes(sum).Add(Tuple.Create(i, j))
If j >= i Then
Exit For
End If
Next
REM Found that you need to keep going for a while after the length, because higher i values fill in gaps
If sumsOfTwoCubes.AsEnumerable.Count(Function(t) t.Value.Count >= 2) >= length * 1.1 Then
Exit For
End If
Next
Dim values = (From t In sumsOfTwoCubes Where t.Value.Count >= 2 Select t) _
.Take(2006) _
.ToDictionary(Function(u) u.Key, Function(u) u.Value)
Return values
End Function
Sub PrintTaxicabNumbers(values As IDictionary(Of Long, IList(Of Tuple(Of Integer, Integer))))
Dim i = 1
For Each taxicabNumber In values.Keys
Dim output As New StringBuilder
output.AppendFormat("{0,10}" + vbTab + "{1,4}", i, taxicabNumber)
For Each numbers In values(taxicabNumber)
output.AppendFormat(vbTab + "= {0}^3 + {1}^3", numbers.Item1, numbers.Item2)
Next
If i <= 25 OrElse (i >= 2000 AndAlso i <= 2006) Then
Console.WriteLine(output.ToString)
End If
i += 1
Next
End Sub
Sub Main()
Dim taxicabNumbers = GetTaxicabNumbers(2006)
PrintTaxicabNumbers(taxicabNumbers)
End Sub
End Module |
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
| #Fortran | Fortran | Program Temperature
implicit none
real :: kel, cel, fah, ran
write(*,*) "Input Kelvin temperature to convert"
read(*,*) kel
call temp_convert(kel, cel, fah, ran)
write(*, "((a10), f10.3)") "Kelvin", kel
write(*, "((a10), f10.3)") "Celsius", cel
write(*, "((a10), f10.3)") "Fahrenheit", fah
write(*, "((a10), f10.3)") "Rankine", ran
contains
subroutine temp_convert(kelvin, celsius, fahrenheit, rankine)
real, intent(in) :: kelvin
real, intent(out) :: celsius, fahrenheit, rankine
celsius = kelvin - 273.15
fahrenheit = kelvin * 1.8 - 459.67
rankine = kelvin * 1.8
end subroutine
end program |
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
| #Tcl | Tcl | package require Tcl 8.5
namespace eval ternary {
# Code generator
proc maketable {name count values} {
set sep ""
for {set i 0; set c 97} {$i<$count} {incr i;incr c} {
set v [format "%c" $c]
lappend args $v; append key $sep "$" $v
set sep ","
}
foreach row [split $values \n] {
if {[llength $row]>1} {
lassign $row from to
lappend table $from [list return $to]
}
}
proc $name $args \
[list ckargs $args]\;[concat [list switch -glob --] $key [list $table]]
namespace export $name
}
# Helper command to check argument syntax
proc ckargs argList {
foreach var $argList {
upvar 1 $var v
switch -exact -- $v {
true - maybe - false {
continue
}
default {
return -level 2 -code error "bad ternary value \"$v\""
}
}
}
}
# The "truth" tables; “*” means “anything”
maketable not 1 {
true false
maybe maybe
false true
}
maketable and 2 {
true,true true
false,* false
*,false false
* maybe
}
maketable or 2 {
true,* true
*,true true
false,false false
* maybe
}
maketable implies 2 {
false,* true
*,true true
true,false false
* maybe
}
maketable equiv 2 {
*,maybe maybe
maybe,* maybe
true,true true
false,false true
* false
}
} |
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
| #REXX | REXX | /*REXX program displays the verses of the song: "The 12 days of Christmas". */
ordD= 'first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth'
pad= left('', 20) /*used for indenting the shown verses. */
@.1= 'A partridge in a pear-tree.'; @.7 = "Seven swans a-swimming,"
@.2= 'Two Turtle Doves, and' ; @.8 = "Eight maids a-milking,"
@.3= 'Three French Hens,' ; @.9 = "Nine ladies dancing,"
@.4= 'Four Calling Birds,' ; @.10= "Ten lords a-leaping,"
@.5= 'Five Golden Rings,' ; @.11= "Eleven pipers piping,"
@.6= 'Six geese a-laying,' ; @.12= "Twelve drummers drumming,"
do day=1 for 12
say pad 'On the' word(ordD, day) "day of Christmas" /*display line 1 prologue.*/
say pad 'My True Love gave to me:' /* " " 2 " */
do j=day by -1 to 1; say pad @.j /* " the daily gifts.*/
end /*j*/
say /*add a blank line between the verses. */
end /*day*/ /*stick a fork in it, we're all done. */ |
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.
| #Rust | Rust | use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::sync::mpsc::{channel, sync_channel};
use std::thread;
fn main() {
// The reader sends lines to the writer via an async channel, so the reader is never blocked.
let (reader_send, writer_recv) = channel();
// The writer sends the final count via a blocking channel with bound 0,
// meaning the buffer is exactly the size of the result.
let (writer_send, reader_recv) = sync_channel(0);
// Define the work the reader will do.
let reader_work = move || {
let file = File::open("input.txt").expect("Failed to open input.txt");
let reader = BufReader::new(file);
for line in reader.lines() {
match line {
Ok(msg) => reader_send
.send(msg)
.expect("Failed to send via the channel"),
Err(e) => println!("{}", e),
}
}
// Dropping the sender disconnects it and tells the receiver the connection is closed.
drop(reader_send);
// Now that we've sent all the lines,
// block until the writer gives us the final count.
let count = reader_recv
.recv()
.expect("Failed to receive count from printer.");
println!("{}", count);
};
// Define the work the writer will do.
let writer_work = move || {
let mut line_count = 0;
loop {
match writer_recv.recv() {
Ok(msg) => {
println!("{}", msg);
line_count += 1;
}
Err(_) => break, // indicates the connection has been closed by the sender.
}
}
// Send the final count back to the reader.
writer_send
.send(line_count)
.expect("Failed to send line count from writer.");
drop(writer_send);
};
// Spawn each as a thread.
let reader_handle = thread::spawn(reader_work);
thread::spawn(writer_work);
reader_handle
.join()
.expect("Failed to join the reader thread.");
} |
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.
| #Scala | Scala | case class HowMany(asker: Actor)
val printer = actor {
var count = 0
while (true) {
receive {
case line: String =>
print(line); count = count + 1
case HowMany(asker: Actor) => asker ! count; exit()
}
}
}
def reader(printer: Actor) {
scala.io.Source.fromFile("c:\\input.txt").getLines foreach { printer ! _ }
printer ! HowMany(
actor {
receive {
case count: Int => println("line count = " + count)
}
})
}
reader(printer) |
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)
| #E | E | println(timer.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)
| #EasyLang | EasyLang | print timestr systime |
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.
| #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
every L := !longestselfrefseq(1000000) do
every printf(" %i : %i\n",i := 1 to *L,L[i])
end
procedure longestselfrefseq(N) #: find longest sequences from 1 to N
mlen := 0
every L := selfrefseq(n := 1 to N) do {
if mlen <:= *L then
ML := [L]
else if mlen = *L then
put(ML,L)
}
return ML
end
procedure selfrefseq(n) #: return list of sequence oeis:A036058 for seed n
S := set()
L := []
every p := seq(1) do
if member(S,n) then return L # ends at a repeat
else {
insert(S,n)
put(L,n)
n := nextselfrefseq(n)
}
end
procedure nextselfrefseq(n) #: return next element of sequence oeis:A036058
every (Counts := table(0))[integer(!n)] +:= 1 # count digits
every (n := "") ||:= (0 < Counts[i := 9 to 0 by -1]) || i # assemble counts
return integer(n)
end |
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.)
| #Raku | Raku | sub intersection ($L11, $L12, $L21, $L22) {
my ($Δ1x, $Δ1y) = $L11 »-« $L12;
my ($Δ2x, $Δ2y) = $L21 »-« $L22;
my $n1 = $L11[0] * $L12[1] - $L11[1] * $L12[0];
my $n2 = $L21[0] * $L22[1] - $L21[1] * $L22[0];
my $n3 = 1 / ($Δ1x * $Δ2y - $Δ2x * $Δ1y);
(($n1 * $Δ2x - $n2 * $Δ1x) * $n3, ($n1 * $Δ2y - $n2 * $Δ1y) * $n3)
}
sub is-inside ($p1, $p2, $p3) {
($p2[0] - $p1[0]) * ($p3[1] - $p1[1]) > ($p2[1] - $p1[1]) * ($p3[0] - $p1[0])
}
sub sutherland-hodgman (@polygon, @clip) {
my @output = @polygon;
my $clip-point1 = @clip.tail;
for @clip -> $clip-point2 {
my @input = @output;
@output = ();
my $start = @input.tail;
for @input -> $end {
if is-inside($clip-point1, $clip-point2, $end) {
@output.push: intersection($clip-point1, $clip-point2, $start, $end)
unless is-inside($clip-point1, $clip-point2, $start);
@output.push: $end;
} elsif is-inside($clip-point1, $clip-point2, $start) {
@output.push: intersection($clip-point1, $clip-point2, $start, $end);
}
$start = $end;
}
$clip-point1 = $clip-point2;
}
@output
}
my @polygon = (50, 150), (200, 50), (350, 150), (350, 300), (250, 300),
(200, 250), (150, 350), (100, 250), (100, 200);
my @clip = (100, 100), (300, 100), (300, 300), (100, 300);
my @clipped = sutherland-hodgman(@polygon, @clip);
say "Clipped polygon: ", @clipped;
# Output an SVG as well as it is easier to visualize
use SVG;
my $outfile = 'Sutherland-Hodgman-polygon-clipping-perl6.svg'.IO.open(:w);
$outfile.say: SVG.serialize(
svg => [
:400width, :400height,
:rect[ :400width, :400height, :fill<white> ],
:text[ :10x, :20y, "Polygon (blue)" ],
:text[ :10x, :35y, "Clip port (green)" ],
:text[ :10x, :50y, "Clipped polygon (red)" ],
:polyline[ :points(@polygon.join: ','), :style<stroke:blue>, :fill<blue>, :opacity<.3> ],
:polyline[ :points( @clip.join: ','), :style<stroke:green>, :fill<green>, :opacity<.3> ],
:polyline[ :points(@clipped.join: ','), :style<stroke:red>, :fill<red>, :opacity<.5> ],
],
); |
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).
| #HicEst | HicEst | CALL SymmDiff("John,Serena,Bob,Mary,Serena,", "Jim,Mary,John,Jim,Bob,")
CALL SymmDiff("John,Bob,Mary,Serena,", "Jim,Mary,John,Bob,")
SUBROUTINE SymmDiff(set1, set2)
CHARACTER set1, set2, answer*50
answer = " "
CALL setA_setB( set1, set2, answer )
CALL setA_setB( set2, set1, answer )
WRITE(Messagebox,Name) answer ! answer = "Serena,Jim," in both cases
END
SUBROUTINE setA_setB( set1, set2, differences )
CHARACTER set1, set2, differences, a*100
a = set1
EDIT(Text=a, $inLeXicon=set2) ! eg a <= $John,Serena,$Bob,$Mary,Serena,
EDIT(Text=a, Right="$", Mark1, Right=",", Mark2, Delete, DO) ! Serena,Serena,
EDIT(Text=a, Option=1, SortDelDbls=a) ! Option=1: keep case; Serena,
differences = TRIM( differences ) // a
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.
| #Racket | Racket |
#!/usr/bin/env racket
#lang racket
(define file "NOTES.TXT")
(require racket/date)
(command-line #:args notes
(if (null? notes)
(if (file-exists? file)
(call-with-input-file* file
(λ(i) (copy-port i (current-output-port))))
(raise-user-error 'notes "missing ~a file" file))
(call-with-output-file* file #:exists 'append
(λ(o) (fprintf o "~a\n\t~a\n"
(date->string (current-date) #t)
(string-join notes))))))
|
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.
| #Raku | Raku | my $file = 'notes.txt';
multi MAIN() {
print slurp($file);
}
multi MAIN(*@note) {
my $fh = open($file, :a);
$fh.say: DateTime.now, "\n\t", @note;
$fh.close;
} |
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
| #Stata | Stata | sca a=200
sca b=200
sca n=2.5
twoway function y=b*(1-(abs(x/a))^n)^(1/n), range(-200 200) || function y=-b*(1-(abs(x/a))^n)^(1/n), range(-200 200) |
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).
| #Wren | Wren | import "/sort" for Sort
import "/fmt" for Fmt
var cubesSum = {}
var taxicabs = []
for (i in 1..1199) {
for (j in i+1..1200) {
var sum = i*i*i + j*j*j
if (!cubesSum[sum]) {
cubesSum[sum] = [i, j]
} else {
taxicabs.add([sum, cubesSum[sum], [i, j]])
}
}
}
var cmp = Fn.new { |a, b| (a[0] - b[0]).sign }
Sort.quick(taxicabs, 0, taxicabs.count-1, cmp)
// remove those numbers which have additional pairs of cubes
for (i in taxicabs.count-2..0) {
if (taxicabs[i][0] == taxicabs[i+1][0]) taxicabs.removeAt(i+1)
}
System.print("The first 25 taxicab numbers are:")
for (i in 1..25) {
var t = taxicabs[i-1]
Fmt.lprint("$2d: $,7d = $2d³ + $2d³ = $2d³ + $2d³", [i, t[0], t[1][0], t[1][1], t[2][0], t[2][1]])
}
System.print("\nThe 2,000th to 2,006th taxicab numbers are:")
for (i in 2000..2006) {
var t = taxicabs[i-1]
Fmt.lprint("$,5d: $,13d = $3d³ + $,5d³ = $3d³ + $,5d³", [i, t[0], t[1][0], t[1][1], t[2][0], t[2][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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub convKelvin(temp As Double)
Dim f As String = "####.##"
Print Using f; temp;
Print " degrees Kelvin"
Print Using f; temp - 273.15;
Print " degrees Celsius"
Print Using f; (temp - 273.15) * 1.8 + 32.0;
Print " degrees Fahreneit"
Print Using f; (temp - 273.15) * 1.8 + 32.0 + 459.67;
Print " degrees Rankine"
End Sub
convKelvin(0.0)
Print
convKelvin(21.0)
Print
Print "Press any key to quit"
Sleep |
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
| #True_BASIC | True BASIC |
FUNCTION and3(a, b)
IF a < b then LET and3 = a else LET and3 = b
END FUNCTION
FUNCTION eq3(a, b)
IF a = tDontknow or b = tDontKnow then
LET eq3 = tdontknow
ELSEIF a = b then
LET eq3 = ttrue
ELSE
LET eq3 = tfalse
END IF
END FUNCTION
FUNCTION longname3$(i)
SELECT CASE i
CASE 1
LET longname3$ = "Don't know"
CASE 2
LET longname3$ = "True"
CASE else
LET longname3$ = "False"
END SELECT
END FUNCTION
FUNCTION not3(b)
LET not3 = 2-b
END FUNCTION
FUNCTION or3(a, b)
IF a > b then LET or3 = a else LET or3 = b
END FUNCTION
FUNCTION shortname3$(i)
LET shortname3$ = ("F?T")[i+1:i+1+1-1]
END FUNCTION
FUNCTION xor3(a, b)
LET xor3 = not3(eq3(a,b))
END FUNCTION
LET tfalse = 0
LET tdontknow = 1
LET ttrue = 2
PRINT "Nombres cortos y largos para valores lógicos ternarios:"
FOR i = tfalse to ttrue
PRINT shortname3$(i); " "; longname3$(i)
NEXT i
PRINT
PRINT "Funciones de parámetro único"
PRINT "x"; " "; "=x"; " "; "not(x)"
FOR i = tfalse to ttrue
PRINT shortname3$(i); " "; shortname3$(i); " "; shortname3$(not3(i))
NEXT i
PRINT
PRINT "Funciones de doble parámetro"
PRINT "x"; " "; "y"; " "; "x AND y"; " "; "x OR y"; " "; "x EQ y"; " "; "x XOR y"
FOR a = tfalse to ttrue
FOR b = tfalse to ttrue
PRINT shortname3$(a); " "; shortname3$(b); " ";
PRINT shortname3$(and3(a,b)); " "; shortname3$(or3(a,b)); " ";
PRINT shortname3$(eq3(a,b)); " "; shortname3$(xor3(a,b))
NEXT b
NEXT a
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
| #Ring | Ring |
# Project : The Twelve Days of Christmas
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"
lstgifts = str2list(substr(gifts,",", nl))
lstdays = str2list(substr(days, " ", nl))
for i = 1 to 12
see "On the "+ lstdays[i]+ " day of Christmas" + nl
see "My true love gave to me:" + nl
for j = i to 1 step -1
if i > 1 and j = 1
see "and " + nl
ok
see "" + lstgifts[j] + nl
next
see nl
next
|
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
| #Ruby | Ruby | gifts = "A partridge in a pear tree
Two turtle doves and
Three french hens
Four calling birds
Five golden rings
Six geese a-laying
Seven swans a-swimming
Eight maids a-milking
Nine ladies dancing
Ten lords a-leaping
Eleven pipers piping
Twelve drummers drumming".split("\n")
days = %w(first second third fourth fifth sixth
seventh eighth ninth tenth eleventh twelfth)
days.each_with_index do |day, i|
puts "On the #{day} day of Christmas"
puts "My true love gave to me:"
puts gifts[0, i+1].reverse
puts
end |
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.
| #Swift | Swift | //
// Reader.swift
//
import Foundation
class Reader: NSObject {
let inputPath = "~/Desktop/input.txt".stringByExpandingTildeInPath
var gotNumberOfLines = false
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "linesPrinted:",
name: "LinesPrinted", object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// Selector for the number of lines printed
func linesPrinted(not:NSNotification) {
println(not.object!)
self.gotNumberOfLines = true
exit(0)
}
func readFile() {
var err:NSError?
let fileString = NSString(contentsOfFile: self.inputPath,
encoding: NSUTF8StringEncoding, error: &err)
if let lines = fileString?.componentsSeparatedByString("\n") {
for line in lines {
NSNotificationCenter.defaultCenter().postNotificationName("Line", object: line)
}
NSNotificationCenter.defaultCenter().postNotificationName("LineNumberRequest", object: nil)
while !self.gotNumberOfLines {
sleep(1 as UInt32)
}
}
}
} |
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.
| #SystemVerilog | SystemVerilog | program main;
mailbox#(bit) p2c_cmd = new;
mailbox#(string) p2c_data = new;
mailbox#(int) c2p_data = new;
initial begin
int fh = $fopen("input.txt", "r");
string line;
int count;
while ($fgets(line, fh)) begin
p2c_cmd.put(0);
p2c_data.put(line);
end
p2c_cmd.put(1);
c2p_data.get(count);
$display( "COUNT: %0d", count );
end
initial begin
bit done;
int count;
while (!done) begin
p2c_cmd.get(done);
if (done) begin
c2p_data.put(count);
end
else begin
string line;
p2c_data.get(line);
$display( "LINE: %s", line);
count++;
end
end
end
endprogram |
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)
| #Elena | Elena | import extensions;
import system'calendar;
public program()
{
console.printLine(Date.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)
| #Elixir | Elixir | :os.timestamp # => {MegaSecs, Secs, MicroSecs}
:erlang.time # => {Hour, Minute, Second}
:erlang.date # => {Year, Month, Day}
:erlang.localtime # => {{Year, Month, Day}, {Hour, Minute, Second}}
:erlang.universaltime # => {{Year, Month, Day}, {Hour, Minute, Second}}
:calendar.local_time # => {{Year, Month, Day}, {Hour, Minute, Second}}
:calendar.universal_time # => {{Year, Month, Day}, {Hour, Minute, Second}} |
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.
| #J | J | require'stats'
digits=: 10&#.inv"0 :. ([: ".@; (<'x'),~":&.>)
summar=: (#/.~ ,@,. ~.)@\:~&.digits
sequen=: ~.@(, summar@{:)^:_
values=: ~. \:~&.digits i.1e6
allvar=: [:(#~(=&<.&(10&^.) >./))@~.({~ perm@#)&.(digits"1) |
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.)
| #Ruby | Ruby | Point = Struct.new(:x,:y) do
def to_s; "(#{x}, #{y})" end
end
def sutherland_hodgman(subjectPolygon, clipPolygon)
# These inner functions reduce the argument passing to
# "inside" and "intersection".
cp1, cp2, s, e = nil
inside = proc do |p|
(cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
end
intersection = proc do
dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y
dpx, dpy = s.x-e.x, s.y-e.y
n1 = cp1.x*cp2.y - cp1.y*cp2.x
n2 = s.x*e.y - s.y*e.x
n3 = 1.0 / (dcx*dpy - dcy*dpx)
Point[(n1*dpx - n2*dcx) * n3, (n1*dpy - n2*dcy) * n3]
end
outputList = subjectPolygon
cp1 = clipPolygon.last
for cp2 in clipPolygon
inputList = outputList
outputList = []
s = inputList.last
for e in inputList
if inside[e]
outputList << intersection[] unless inside[s]
outputList << e
elsif inside[s]
outputList << intersection[]
end
s = e
end
cp1 = cp2
end
outputList
end
subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300],
[250, 300], [200, 250], [150, 350], [100, 250],
[100, 200]].collect{|pnt| Point[*pnt]}
clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]].collect{|pnt| Point[*pnt]}
puts sutherland_hodgman(subjectPolygon, clipPolygon) |
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).
| #Icon_and_Unicon | Icon and Unicon | procedure main()
a := set(["John", "Serena", "Bob", "Mary", "Serena"])
b := set(["Jim", "Mary", "John", "Jim", "Bob"])
showset("a",a)
showset("b",b)
showset("(a\\b) \xef (b\\a)",(a -- b) ++ (b -- a))
showset("(a\\b)",a -- b)
showset("(b\\a)",b -- a)
end
procedure showset(n,x)
writes(n," = { ")
every writes(!x," ")
write("}")
return
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.
| #REBOL | REBOL | rebol [
Title: "Notes"
URL: http://rosettacode.org/wiki/Take_notes_on_the_command_line
]
notes: %notes.txt
either any [none? args: system/script/args empty? args] [
if exists? notes [print read notes]
] [
write/binary/append notes rejoin [now lf tab args lf]
] |
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.
| #REXX | REXX | /*REXX program implements the "NOTES" command (append text to a file from the C.L.).*/
timestamp=right(date(),11,0) time() date('W') /*create a (current) date & time stamp.*/
nFID = 'NOTES.TXT' /*the fileID of the "notes" file. */
if 'f2'x==2 then tab="05"x /*this is an EBCDIC system. */
else tab="09"x /* " " " ASCII " */
if arg()==0 then do while lines(nFID) /*No arguments? Then display the file.*/
say linein(Nfid) /*display a line of file ──► screen. */
end /*while*/
else do
call lineout nFID,timestamp /*append the timestamp to "notes" file.*/
call lineout nFID,tab||arg(1) /* " " text " " " */
end
/*stick a fork in it, we're all done. */ |
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
| #Wren | Wren | import "graphics" for Canvas, Color, Point
class Game {
static init() {
Canvas.resize(500, 500)
// draw 200 concentric superellipses with gradually decreasing 'n'.
for (a in 200..1) {
superEllipse(a/80, a)
}
}
static update() {}
static draw(alpha) {}
static superEllipse(n, a) {
var hw = Canvas.width / 2
var hh = Canvas.height / 2
// calculate y for each x
var y = List.filled(a + 1, 0)
for (x in 0..a) {
var aa = a.pow(n)
var xx = x.pow(n)
y[x] = (aa-xx).pow(1/n)
}
// draw quadrants
var prev = Point.new(hw + a, hh - y[a])
for (x in a-1..0) {
var curr = Point.new(hw + x, hh - y[x])
Canvas.line(prev.x, prev.y, curr.x, curr.y, Color.white)
prev = Point.new(curr.x, curr.y)
}
prev = Point.new(hw, hh + y[0])
for (x in 1..a) {
var curr = Point.new(hw + x, hh + y[x])
Canvas.line(prev.x, prev.y, curr.x, curr.y, Color.white)
prev = Point.new(curr.x, curr.y)
}
prev = Point.new(hw - a, hh + y[a])
for (x in a-1..0) {
var curr = Point.new(hw - x, hh + y[x])
Canvas.line(prev.x, prev.y, curr.x, curr.y, Color.white)
prev = Point.new(curr.x, curr.y)
}
prev = Point.new(hw, hh - y[0])
for (x in 1..a) {
var curr = Point.new(hw - x, hh - y[x])
Canvas.line(prev.x, prev.y, curr.x, curr.y, Color.white)
prev = Point.new(curr.x, curr.y)
}
}
} |
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).
| #XPL0 | XPL0 | int N, I, J, SI, SJ, Count, Tally;
[Count:= 0; N:= 0;
repeat Tally:= 0;
I:= 1;
repeat J:= I+1;
repeat if N = I*I*I + J*J*J then
[Tally:= Tally+1;
if Tally >= 2 then
[Count:= Count+1;
IntOut(0, Count); Text(0, ": ");
IntOut(0, N); Text(0, " = ");
IntOut(0, SI); Text(0, "^^3 + ");
IntOut(0, SJ); Text(0, "^^3 = ");
IntOut(0, I); Text(0, "^^3 + ");
IntOut(0, J); Text(0, "^^3");
CrLf(0);
J:= 1000; I:= J;
];
SI:= I; SJ:= J;
];
J:= J+1;
until I*I*I + J*J*J > N;
I:= I+1;
until I*I*I*2 > N;
N:= N+1;
until Count >= 25;
] |
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).
| #zkl | zkl | fcn taxiCabNumbers{
const HeapSZ=0d5_000_000;
iCubes:=[1..120].apply("pow",3);
sum2cubes:=Data(HeapSZ).fill(0); // BFheap of 1 byte zeros
taxiNums:=List();
foreach i,i3 in ([1..].zip(iCubes)){
foreach j,j3 in ([i+1..].zip(iCubes[i,*])){
ij3:=i3+j3;
if(z:=sum2cubes[ij3]){
taxiNums.append(T(ij3,
z,(ij3-z.pow(3)).toFloat().pow(1.0/3).round().toInt(),
i,j));
}
else sum2cubes[ij3]=i;
}
}
taxiNums.sort(fcn([(a,_)],[(b,_)]){ a<b })
} |
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
| #Gambas | Gambas | Public Sub Form_Open()
Dim fKelvin As Float
fKelvin = InputBox("Enter a Kelvin value", "Kelvin converter")
Print "Kelvin =\t" & Format(Str(fKelvin), "#.00")
Print "Celsius =\t" & Format(Str(fKelvin - 273.15), "#.00")
Print "Fahrenheit =\t" & Format(Str(fKelvin * 1.8 - 459.67), "#.00")
Print "Rankine =\t" & Format(Str(fKelvin * 1.8), "#.00")
End |
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
| #Wren | Wren | var False = -1
var Maybe = 0
var True = 1
var Chrs = ["F", "M", "T"]
class Trit {
construct new(v) {
if (v != False && v != Maybe && v != True) Fiber.abort("Invalid argument.")
_v = v
}
v { _v }
! { Trit.new(-_v) }
&(other) { (_v < other.v) ? this : other }
|(other) { (_v > other.v) ? this : other }
>>(other) { (-_v > other.v) ? !this : other }
==(other) { Trit.new(_v * other.v) }
toString { Chrs[_v + 1] }
}
var trits = [Trit.new(True), Trit.new(Maybe), Trit.new(False)]
System.print("not")
System.print("-------")
for (t in trits) System.print(" %(t) | %(!t)")
System.print("\nand | T M F")
System.print("-------------")
for (t in trits) {
System.write(" %(t) | ")
for (u in trits) System.write("%(t & u) ")
System.print()
}
System.print("\nor | T M F")
System.print("-------------")
for (t in trits) {
System.write(" %(t) | ")
for (u in trits) System.write("%(t | u) ")
System.print()
}
System.print("\nimp | T M F")
System.print("-------------")
for (t in trits) {
System.write(" %(t) | ")
for (u in trits) System.write("%(t >> u) ")
System.print()
}
System.print("\neqv | T M F")
System.print("-------------")
for (t in trits) {
System.write(" %(t) | ")
for (u in trits) System.write("%(t == u) ")
System.print()
} |
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
| #Run_BASIC | Run BASIC | 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 i = 1 to 12
print "On the ";word$(days$,i," ");" day of Christmas"
print "My true love gave to me:"
for j = i to 1 step -1
if i > 1 and j = 1 then print "and ";
print mid$(word$(gifts$,j,","),2)
next j
print
next i
|
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
| #Rust | Rust | fn main() {
let days = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth",
"ninth", "tenth", "eleventh", "twelfth"];
let gifts = ["A Patridge in a Pear Tree",
"Two Turtle Doves and",
"Three French Hens",
"Four Calling Birds",
"Five Golden Rings",
"Six Geese a Laying",
"Seven Swans a Swimming",
"Eight Maids a Milking",
"Nine Ladies Dancing",
"Ten Lords a Leaping",
"Eleven Pipers Piping",
"Twelve Drummers Drumming"];
for i in 0..12 {
println!("On the {} day of Christmas,", days[i]);
println!("My true love gave to me:");
for j in (0..i + 1).rev() {
println!("{}", gifts[j]);
}
println!()
}
} |
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.
| #Tcl | Tcl | package require Thread
# Define the input thread
set input [thread::create {
proc readFile {filename receiver} {
set f [open $filename]
while {[gets $f line] >= 0} {
thread::send $receiver [list line $line]
}
close $f
thread::send $receiver lineCount lines
puts "got $lines lines"
}
thread::wait
}]
# Define the output thread
set output [thread::create {
set lines 0
proc line {string} {
puts $string
incr ::lines
}
proc lineCount {} {return $::lines}
thread::wait
}]
# Connect everything together and start the processing
thread::send $input [list readFile "input.txt" $output] |
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.
| #TXR | TXR | (defstruct thread nil
suspended
cont
(:method resume (self)
[self.cont])
(:method give (self item)
[self.cont item])
(:method get (self)
(yield-from run nil))
(:method start (self)
(set self.cont (obtain self.(run)))
(unless self.suspended
self.(resume)))
(:postinit (self)
self.(start)))
(defstruct consumer thread
(count 0)
(:method run (self)
(whilet ((item self.(get)))
(prinl item)
(inc self.count))))
(defstruct producer thread
consumer
(:method run (self)
(whilet ((line (get-line)))
self.consumer.(give line))))
(let* ((con (new consumer))
(pro (new producer suspended t consumer con)))
pro.(resume)
(put-line `count = @{con.count}`)) |
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)
| #Emacs_Lisp | Emacs Lisp | (message "%s" (current-time-string))
;; => "Wed Oct 14 22:21:05 1987" |
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)
| #Erlang | Erlang | 1> os:timestamp().
{1250,222584,635452} |
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.
| #Java | Java | import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.IntStream;
public class SelfReferentialSequence {
static Map<String, Integer> cache = new ConcurrentHashMap<>(10_000);
public static void main(String[] args) {
Seeds res = IntStream.range(0, 1000_000)
.parallel()
.mapToObj(n -> summarize(n, false))
.collect(Seeds::new, Seeds::accept, Seeds::combine);
System.out.println("Seeds:");
res.seeds.forEach(e -> System.out.println(Arrays.toString(e)));
System.out.println("\nSequence:");
summarize(res.seeds.get(0)[0], true);
}
static int[] summarize(int seed, boolean display) {
String n = String.valueOf(seed);
String k = Arrays.toString(n.chars().sorted().toArray());
if (!display && cache.get(k) != null)
return new int[]{seed, cache.get(k)};
Set<String> seen = new HashSet<>();
StringBuilder sb = new StringBuilder();
int[] freq = new int[10];
while (!seen.contains(n)) {
seen.add(n);
int len = n.length();
for (int i = 0; i < len; i++)
freq[n.charAt(i) - '0']++;
sb.setLength(0);
for (int i = 9; i >= 0; i--) {
if (freq[i] != 0) {
sb.append(freq[i]).append(i);
freq[i] = 0;
}
}
if (display)
System.out.println(n);
n = sb.toString();
}
cache.put(k, seen.size());
return new int[]{seed, seen.size()};
}
static class Seeds {
int largest = Integer.MIN_VALUE;
List<int[]> seeds = new ArrayList<>();
void accept(int[] s) {
int size = s[1];
if (size >= largest) {
if (size > largest) {
largest = size;
seeds.clear();
}
seeds.add(s);
}
}
void combine(Seeds acc) {
acc.seeds.forEach(this::accept);
}
}
} |
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.)
| #Rust | Rust | #[derive(Debug, Clone)]
struct Point {
x: f64,
y: f64,
}
#[derive(Debug, Clone)]
struct Polygon(Vec<Point>);
fn is_inside(p: &Point, cp1: &Point, cp2: &Point) -> bool {
(cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)
}
fn compute_intersection(cp1: &Point, cp2: &Point, s: &Point, e: &Point) -> Point {
let dc = Point {
x: cp1.x - cp2.x,
y: cp1.y - cp2.y,
};
let dp = Point {
x: s.x - e.x,
y: s.y - e.y,
};
let n1 = cp1.x * cp2.y - cp1.y * cp2.x;
let n2 = s.x * e.y - s.y * e.x;
let n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x);
Point {
x: (n1 * dp.x - n2 * dc.x) * n3,
y: (n1 * dp.y - n2 * dc.y) * n3,
}
}
fn sutherland_hodgman_clip(subject_polygon: &Polygon, clip_polygon: &Polygon) -> Polygon {
let mut result_ring = subject_polygon.0.clone();
let mut cp1 = clip_polygon.0.last().unwrap();
for cp2 in &clip_polygon.0 {
let input = result_ring;
let mut s = input.last().unwrap();
result_ring = vec![];
for e in &input {
if is_inside(e, cp1, cp2) {
if !is_inside(s, cp1, cp2) {
result_ring.push(compute_intersection(cp1, cp2, s, e));
}
result_ring.push(e.clone());
} else if is_inside(s, cp1, cp2) {
result_ring.push(compute_intersection(cp1, cp2, s, e));
}
s = e;
}
cp1 = cp2;
}
Polygon(result_ring)
}
fn main() {
let _p = |x: f64, y: f64| Point { x, y };
let subject_polygon = Polygon(vec![
_p(50.0, 150.0), _p(200.0, 50.0), _p(350.0, 150.0), _p(350.0, 300.0), _p(250.0, 300.0),
_p(200.0, 250.0), _p(150.0, 350.0), _p(100.0, 250.0), _p(100.0, 200.0),
]);
let clip_polygon = Polygon(vec![
_p(100.0, 100.0),_p(300.0, 100.0),_p(300.0, 300.0),_p(100.0, 300.0),
]);
let result = sutherland_hodgman_clip(&subject_polygon, &clip_polygon);
println!("{:?}", result);
} |
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.)
| #Scala | Scala | import javax.swing.{ JFrame, JPanel }
object SutherlandHodgman extends JFrame with App {
import java.awt.BorderLayout
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setVisible(true)
val content = getContentPane()
content.setLayout(new BorderLayout())
content.add(SutherlandHodgmanPanel, BorderLayout.CENTER)
setTitle("SutherlandHodgman")
pack()
setLocationRelativeTo(null)
}
object SutherlandHodgmanPanel extends JPanel {
import java.awt.{ Color, Graphics, Graphics2D }
setPreferredSize(new java.awt.Dimension(600, 500))
// subject and clip points are assumed to be valid
val subject = Seq((50D, 150D), (200D, 50D), (350D, 150D), (350D, 300D), (250D, 300D), (200D, 250D), (150D, 350D), (100D, 250D), (100D, 200D))
val clipper = Seq((100D, 100D), (300D, 100D), (300D, 300D), (100D, 300D))
var result = subject
val len = clipper.size
for (i <- 0 until len) {
val len2 = result.size
val input = result
result = Seq()
val A = clipper((i + len - 1) % len)
val B = clipper(i)
for (j <- 0 until len2) {
val P = input((j + len2 - 1) % len2)
val Q = input(j)
if (inside(A, B, Q)) {
if (!inside(A, B, P))
result = result :+ intersection(A, B, P, Q)
result = result :+ Q
}
else if (inside(A, B, P))
result = result :+ intersection(A, B, P, Q)
}
}
override def paintComponent(g: Graphics) {
import java.awt.RenderingHints._
super.paintComponent(g)
val g2 = g.asInstanceOf[Graphics2D]
g2.translate(80, 60)
g2.setStroke(new java.awt.BasicStroke(3))
g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON)
g2.draw_polygon(subject, Color.blue)
g2.draw_polygon(clipper, Color.red)
g2.draw_polygon(result, Color.green)
}
private def inside(a: (Double, Double), b: (Double, Double), c: (Double, Double)) =
(a._1 - c._1) * (b._2 - c._2) > (a._2 - c._2) * (b._1 - c._1)
private def intersection(a: (Double, Double), b: (Double, Double), p: (Double, Double), q: (Double, Double)) = {
val A1 = b._2 - a._2
val B1 = a._1 - b._1
val C1 = A1 * a._1 + B1 * a._2
val A2 = q._2 - p._2
val B2 = p._1 - q._1
val C2 = A2 * p._1 + B2 * p._2
val det = A1 * B2 - A2 * B1
((B2 * C1 - B1 * C2) / det, (A1 * C2 - A2 * C1) / det)
}
private implicit final class Polygon_drawing(g: Graphics2D) {
def draw_polygon(points: Seq[(Double, Double)], color: Color) {
g.setColor(color)
val len = points.length
val line = new java.awt.geom.Line2D.Double()
for (i <- 0 until len) {
val p1 = points(i)
val p2 = points((i + 1) % len)
line.setLine(p1._1, p1._2, p2._1, p2._2)
g.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).
| #J | J | A=: ~.;:'John Serena Bob Mary Serena'
B=: ~. ;:'Jim Mary John Jim Bob'
(A-.B) , (B-.A) NB. Symmetric Difference
┌──────┬───┐
│Serena│Jim│
└──────┴───┘
A (-. , -.~) B NB. Tacit equivalent
┌──────┬───┐
│Serena│Jim│
└──────┴───┘ |
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.
| #Ruby | Ruby | notes = 'NOTES.TXT'
if ARGV.empty?
File.copy_stream(notes, $stdout) rescue nil
else
File.open(notes, 'a') {|file| file.puts "%s\n\t%s" % [Time.now, ARGV.join(' ')]}
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.
| #Rust | Rust | extern crate chrono;
use std::fs::OpenOptions;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::env;
const FILENAME: &str = "NOTES.TXT";
fn show_notes() -> Result<(), io::Error> {
let file = OpenOptions::new()
.read(true)
.create(true) // create the file if not found
.write(true) // necessary to create the file
.open(FILENAME)?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
println!("{}", contents);
Ok(())
}
fn add_to_notes(note: &str) -> Result<(), io::Error> {
let file = OpenOptions::new()
.append(true) // disables overwriting, writes to the end of the file
.create(true)
.open(FILENAME)?;
let mut buf_writer = BufWriter::new(file);
let date_and_time = chrono::Local::now();
writeln!(buf_writer, "{}", date_and_time)?;
writeln!(buf_writer, "\t{}", note)
}
fn main() {
let note = env::args().skip(1).collect::<Vec<_>>();
if note.is_empty() {
show_notes().expect("failed to print NOTES.TXT");
} else {
add_to_notes(¬e.join(" ")).expect("failed to write to NOTES.TXT");
}
} |
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
| #XPL0 | XPL0 | def X0=640/2, Y0=480/2, Scale=25.0, N=2.5;
real X, Y; int IX, IY;
proc OctPoint; [
Point(X0+IX, Y0-IY, $F);
Point(X0-IX, Y0-IY, $F);
Point(X0+IX, Y0+IY, $F);
Point(X0-IX, Y0+IY, $F);
Point(X0+IY, Y0-IX, $F);
Point(X0-IY, Y0-IX, $F);
Point(X0+IY, Y0+IX, $F);
Point(X0-IY, Y0+IX, $F);
];
[SetVid($101); \VESA graphics 640x480x8
IX:= 0;
repeat X:= float(IX)/Scale;
Y:= Pow(200.0 - Pow(X,N), 1.0/N);
IY:= fix(Y*Scale);
OctPoint;
IX:= IX+1;
until IX >= IY;
] |
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
| #Yabasic | Yabasic | open window 700, 600
backcolor 0,0,0
clear window
a=200
b=200
n=2.5
na=2/n
t=.01
color 0,0,255
for i = 0 to 314
xp=a*sig(cos(t))*abs((cos(t)))^na+350
yp=b*sig(sin(t))*abs((sin(t)))^na+275
t=t+.02
line to xp, yp
next i |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.