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/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #R | R | library(Rmpfr)
options(scipen = 999)
find_super_d_number <- function(d, N = 10){
super_number <- c(NA)
n = 0
n_found = 0
while(length(super_number) < N){
n = n + 1
test = d * mpfr(n, precBits = 200) ** d #Here I augment precision
test_formatted = .mpfr2str(test)$str #and I extract the string from S4 class object
iterable = strsplit(test_formatted, "")[[1]]
if (length(iterable) < d) next
for(i in d:length(iterable)){
if (iterable[i] != d) next
equalities = 0
for(j in 1:d) {
if (i == j) break
if(iterable[i] == iterable[i-j])
equalities = equalities + 1
else break
}
if (equalities >= (d-1)) {
n_found = n_found + 1
super_number[n_found] = n
break
}
}
}
message(paste0("First ", N, " super-", d, " numbers:"))
print((super_number))
return(super_number)
}
for(d in 2:6){find_super_d_number(d, N = 10)}
|
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Raku | Raku | sub super (\d) {
my \run = d x d;
^∞ .hyper.grep: -> \n { (d * n ** d).Str.contains: run }
}
(2..9).race(:1batch).map: {
my $now = now;
put "\nFirst 10 super-$_ numbers:\n{.&super[^10]}\n{(now - $now).round(.1)} sec."
} |
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.
| #HicEst | HicEst | SYSTEM(RUN) ! start this script in RUN-mode
CHARACTER notes="Notes.txt", txt*1000
! Remove file name from the global variable $CMD_LINE:
EDIT(Text=$CMD_LINE, Mark1, Right=".hic ", Right=4, Mark2, Delete)
IF($CMD_LINE == ' ') THEN
READ(FIle=notes, LENgth=Lnotes)
IF( Lnotes ) THEN
WINDOW(WINdowhandle=hdl, TItle=notes)
WRITE(Messagebox="?Y") "Finished ?"
ENDIF
ELSE
WRITE(Text=txt, Format="UWWW CCYY-MM-DD HH:mm:SS, A") 0, $CRLF//$TAB//TRIM($CMD_LINE)//$CRLF
OPEN(FIle=notes, APPend)
WRITE(FIle=notes, CLoSe=1) txt
ENDIF
ALARM(999) ! quit HicEst immediately |
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.
| #Icon_and_Unicon | Icon and Unicon |
procedure write_out_notes (filename)
file := open (filename, "rt") | stop ("no notes file yet")
every write (!file)
end
procedure add_to_notes (filename, strs)
file := open (filename, "at") | # append to file if it exists
open (filename, "cat") | # create the file if not there
stop ("unable to open " || filename)
writes (file, ctime(&now) || "\n\t")
every writes (file, !strs || " ")
write (file, "")
end
procedure main (args)
notes_file := "notes.txt"
if *args = 0
then write_out_notes (notes_file)
else add_to_notes (notes_file, args)
end
|
http://rosettacode.org/wiki/Superellipse | Superellipse | A superellipse is a geometric figure defined as the set of all points (x, y) with
|
x
a
|
n
+
|
y
b
|
n
=
1
,
{\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,}
where n, a, and b are positive numbers.
Task
Draw a superellipse with n = 2.5, and a = b = 200
| #Liberty_BASIC | Liberty BASIC |
[start]
nomainwin
UpperLeftX=1:UpperLeftY=1
WindowWidth=800:WindowHeight=600
open "Super Ellipse" for graphics_nf_nsb as #1
#1 "trapclose [q];down;fill black;flush;color green;size 1"
n=1.5
a=200
b=200
for n = 0.1 to 5 step .1
na=2/n
t=.01
for i = 0 to 314
xp=a*sign(cos(t))*abs((cos(t)))^na+350
yp=b*sign(sin(t))*abs((sin(t)))^na+275
t=t+.02
#1 "set ";xp;" ";yp
next i
next n
'plot only the super ellipse for the task
n=2.5
na=2/n
t=.01
#1 "color white;size 4"
for i = 0 to 314
xp=a*sign(cos(t))*abs((cos(t)))^na+350
yp=b*sign(sin(t))*abs((sin(t)))^na+275
t=t+.02
#1 "set ";xp;" ";yp
next i
wait
[q]
close #1
end
function sign(x)
if x<0 then sign=1
if x>0 then sign=-1
if x=0 then sign=0
end function
|
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).
| #Perl | Perl | my($beg, $end) = (@ARGV==0) ? (1,25) : (@ARGV==1) ? (1,shift) : (shift,shift);
my $lim = 1e14; # Ought to be dynamic as should segment size
my @basis = map { $_*$_*$_ } (1 .. int($lim ** (1.0/3.0) + 1));
my $paira = 2; # We're looking for Ta(2) and larger
my ($segsize, $low, $high, $i) = (500_000_000, 0, 0, 0);
while ($i < $end) {
$low = $high+1;
die "lim too low" if $low > $lim;
$high = $low + $segsize - 1;
$high = $lim if $high > $lim;
foreach my $p (_find_pairs_segment(\@basis, $paira, $low, $high,
sub { sprintf("%4d^3 + %4d^3", $_[0], $_[1]) }) ) {
$i++;
next if $i < $beg;
last if $i > $end;
my $n = shift @$p;
printf "%4d: %10d = %s\n", $i, $n, join(" = ", @$p);
}
}
sub _find_pairs_segment {
my($p, $len, $start, $end, $formatsub) = @_;
my $plen = $#$p;
my %allpairs;
foreach my $i (0 .. $plen) {
my $pi = $p->[$i];
next if ($pi+$p->[$plen]) < $start;
last if (2*$pi) > $end;
foreach my $j ($i .. $plen) {
my $sum = $pi + $p->[$j];
next if $sum < $start;
last if $sum > $end;
push @{ $allpairs{$sum} }, $i, $j;
}
# If we wanted to save more memory, we could filter and delete every entry
# where $n < 2 * $p->[$i+1]. This can cut memory use in half, but is slow.
}
my @retlist;
foreach my $list (grep { scalar @$_ >= $len*2 } values %allpairs) {
my $n = $p->[$list->[0]] + $p->[$list->[1]];
my @pairlist;
while (@$list) {
push @pairlist, $formatsub->(1 + shift @$list, 1 + shift @$list);
}
push @retlist, [$n, @pairlist];
}
@retlist = sort { $a->[0] <=> $b->[0] } @retlist;
return @retlist;
} |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Racket | Racket | #lang racket/base
(require racket/list racket/format)
(define (index-of1 x l) (for/first ((i (in-naturals 1)) (m (in-list l)) #:when (equal? m x)) i))
(define (sprprm n)
(define n-1 (- n 1))
(define sp:n-1 (superperm n-1))
(let loop ((subs (let loop ((sp sp:n-1) (i (- (length sp:n-1) n-1 -1)) (rv null))
(cond
[(zero? i) (reverse rv)]
[else
(define sub (take sp n-1))
(loop (cdr sp)
(- i 1)
(if (check-duplicates sub) rv (cons sub rv)))])))
(ary null))
(if (null? subs)
ary
(let ((sub (car subs)))
(define i (if (null? ary) 0 (index-of1 (last ary) sub)))
(loop (cdr subs) (append ary (drop sub i) (list n) sub))))))
(define superperm
(let ((hsh (make-hash (list (cons 1 (list 1))))))
(lambda (n) (hash-ref! hsh n (lambda () (sprprm n))))))
(define (20..20 ary)
(if (< (length ary) 41) ary (append (take ary 20) (cons '.. (take-right ary 20)))))
(for* ((n (in-range 1 (add1 8))) (ary (in-value (superperm n))))
(printf "~a: len = ~a : ~a~%" (~a n #:width 3) (~a (length ary) #:width 8) (20..20 ary))) |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Raku | Raku | for 1..8 -> $len {
my $pre = my $post = my $t = '';
for ('a'..'z')[^$len].permutations -> @p {
$t = @p.join('');
$post ~= $t unless index($post, $t);
$pre = $t ~ $pre unless index($pre, $t);
}
printf "%1d: %8d %8d\n", $len, $pre.chars, $post.chars;
} |
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. temp-conversion.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 Kelvin-Rankine-Ratio VALUE 0.5556. *> 5 / 9 to 4 d.p.
78 Kelvin-Celsius-Diff VALUE 273.15.
78 Rankine-Fahrenheit-Diff VALUE 459.67.
01 temp-kelvin PIC S9(8)V99.
01 temp-rankine PIC S9(8)V99.
01 kelvin PIC -(7)9.99.
01 celsius PIC -(7)9.99.
01 rankine PIC -(7)9.99.
01 fahrenheit PIC -(7)9.99.
PROCEDURE DIVISION.
DISPLAY "Enter a temperature in Kelvin to convert: " NO ADVANCING
ACCEPT temp-kelvin
MOVE temp-kelvin TO kelvin
DISPLAY "K " kelvin
SUBTRACT Kelvin-Celsius-Diff FROM temp-kelvin GIVING celsius
DISPLAY "C " celsius
DIVIDE temp-kelvin BY Kelvin-Rankine-Ratio
GIVING temp-rankine, rankine
SUBTRACT Rankine-Fahrenheit-Diff FROM temp-rankine GIVING fahrenheit
DISPLAY "F " fahrenheit
DISPLAY "R " rankine
GOBACK
. |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Ring | Ring |
see "The tau functions for the first 100 positive integers are:" + nl
n = 0
num = 0
limit = 100
while num < limit
n = n + 1
tau = 0
for m = 1 to n
if n%m = 0
tau = tau + 1
ok
next
num = num + 1
if num%10 = 1
see nl
ok
tau = string(tau)
if len(tau) = 1
tau = " " + tau
ok
see "" + tau + " "
end
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Ruby | Ruby | require 'prime'
def tau(n) = n.prime_division.inject(1){|res, (d, exp)| res *= exp + 1}
(1..100).map{|n| tau(n).to_s.rjust(3) }.each_slice(20){|ar| puts ar.join}
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Rust | Rust | // returns the highest power of i that is a factor of n,
// and n divided by that power of i
fn factor_exponent(n: i32, i: i32) -> (i32, i32) {
if n % i == 0 {
let (a, b) = factor_exponent(n / i, i);
(a + 1, b)
} else {
(0, n)
}
}
fn tau(n: i32) -> i32 {
for i in 2..(n+1) {
if n % i == 0 {
let (count, next) = factor_exponent(n, i);
return (count + 1) * tau(next);
}
}
return 1;
}
fn main() {
for i in 1..101 {
print!("{} ", tau(i));
}
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #SmileBASIC | SmileBASIC | CLS |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #SPL | SPL | #.clear() |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Standard_ML | Standard ML | fun clearScreen () =
let
val strm = TextIO.openOut (Posix.ProcEnv.ctermid ())
in
TextIO.output (strm, "\^[[H\^[[2J");
TextIO.closeOut strm
end |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Stata | Stata | puts -nonewline "\033\[2J"
flush stdout |
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
| #Picat | Picat | main =>
(show_op1('!') ; true),
nl,
foreach(Op in ['/\\','\\/','->','=='])
(show_op2(Op) ; nl,true)
end.
ternary(true,'!') = false.
ternary(maybe,'!') = maybe.
ternary(false,'!') = true.
ternary(Cond,'!') = Res =>
C1 = cond(Cond == maybe,maybe,cond(Cond,true,false)),
Res = ternary(C1,'!').
ternary(true,'/\\',A) = A.
ternary(maybe,'/\\',A) = cond(A==false,false,maybe).
ternary(false,'/\\',_A) = false.
ternary(true,'\\/',_A) = true.
ternary(maybe,'\\/',A) = cond(A==true,true, maybe).
ternary(false,'\\/',A) = A.
ternary(true,'->',A) = A.
ternary(maybe,'->',A) = cond(A==true,true,maybe).
ternary(false,'->',_) = true.
ternary(true,'==',A) = A.
ternary(maybe,'==',_) = maybe.
ternary(false,'==',A) = ternary(A,'!').
ternary(Cond1,Op,Cond2) = Res =>
C1 = cond(Cond1 == maybe,maybe,cond(Cond1,true,false)),
C2 = cond(Cond2 == maybe,maybe,cond(Cond2,true,false)),
Res = ternary(C1,Op,C2).
show_op1(Op) =>
println(Op),
println(['_' : _ in 1..11]),
foreach(V1 in [true,maybe,false])
V2 = ternary(V1,Op),
printf("%5w %5w \n",V1,V2)
end,
nl.
show_op2(Op) =>
Vs = [true,maybe,false],
printf("%2w %5w %5w %5w\n",Op,Vs[1],Vs[2],Vs[3]),
println(['_' : _ in 1..25]),
foreach(V1 in Vs)
printf("%-5w | ", V1),
foreach(V2 in Vs)
C = ternary(V1,Op,V2),
printf("%5w ",C)
end,
nl
end,
nl. |
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.
| #REXX | REXX | /*REXX program to process instrument data from a data file. */
numeric digits 20 /*allow for bigger (precision) numbers.*/
ifid='READINGS.TXT' /*the name of the input file. */
ofid='READINGS.OUT' /* " " " " output " */
grandSum=0 /*the grand sum of whole file. */
grandFlg=0 /*the grand number of flagged data. */
grandOKs=0
Lflag=0 /*the longest period of flagged data. */
Cflag=0 /*the longest continous flagged data. */
w=16 /*the width of fields when displayed. */
do recs=1 while lines(ifid)\==0 /*keep reading records until finished. */
rec=linein(ifid) /*read the next record (line) of file. */
parse var rec datestamp Idata /*pick off the dateStamp and the data. */
sum=0
flg=0
OKs=0
do j=1 until Idata='' /*process the instrument data. */
parse var Idata data.j flag.j Idata
if flag.j>0 then do /*process good data ··· */
OKs=OKs+1
sum=sum+data.j
if Cflag>Lflag then do
Ldate=datestamp
Lflag=Cflag
end
Cflag=0
end
else do /*process flagged data ··· */
flg=flg+1
Cflag=Cflag+1
end
end /*j*/
if OKs\==0 then avg=format(sum/OKs,,3)
else avg='[n/a]'
grandOKs=grandOKs+OKs
_=right(commas(avg),w)
grandSum=grandSum+sum
grandFlg=grandFlg+flg
if flg==0 then call sy datestamp ' average='_
else call sy datestamp ' average='_ ' flagged='right(flg,2)
end /*recs*/
recs=recs-1 /*adjust for reading the end─of─file. */
if grandOKs\==0 then Gavg=format(grandSum/grandOKs,,3)
else Gavg='[n/a]'
call sy
call sy copies('═',60)
call sy ' records read:' right(commas(recs), w)
call sy ' grand sum:' right(commas(grandSum), w+4)
call sy ' grand average:' right(commas(Gavg), w+4)
call sy ' grand OK data:' right(commas(grandOKs), w)
call sy ' grand flagged:' right(commas(grandFlg), w)
if Lflag\==0 then call sy ' longest flagged:' right(commas(Lflag),w) " ending at " Ldate
call sy copies('═',60)
exit /*stick a fork in it, we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M")
e=verify(n,#'0',,verify(n,#"0.",'M'))-4
do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _
/*────────────────────────────────────────────────────────────────────────────*/
sy: say arg(1); call lineout ofid,arg(1); return |
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
| #Pascal | Pascal | program twelve_days(output);
const
days: array[1..12] of string =
( 'first', 'second', 'third', 'fourth', 'fifth', 'sixth',
'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth' );
gifts: array[1..12] of string =
( '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,' );
var
day, gift: integer;
begin
for day := 1 to 12 do begin
writeln('On the ', days[day], ' day of Christmas, my true love sent to me:');
for gift := day downto 1 do
writeln(gifts[gift]);
writeln
end
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.
| #Mercury | Mercury | :- module synchronous_concurrency.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.
:- implementation.
:- import_module int, list, string, thread, thread.channel, thread.mvar.
:- type line_or_stop
---> line(string)
; stop.
main(!IO) :-
io.open_input("input.txt", Res, !IO),
(
Res = ok(Input),
channel.init(Channel, !IO),
mvar.init(MVar, !IO),
thread.spawn(writer(Channel, MVar, 0), !IO),
reader(Input, Channel, MVar, !IO)
;
Res = error(Err),
io.format("Error opening file: %s\n", [s(io.error_message(Err))], !IO)
).
:- pred reader(io.text_input_stream::in, channel(line_or_stop)::in, mvar(int)::in,
io::di, io::uo) is det.
reader(Input, Channel, MVar, !IO) :-
io.read_line_as_string(Input, Res, !IO),
(
Res = ok(Line),
channel.put(Channel, line(Line), !IO),
reader(Input, Channel, MVar, !IO)
;
Res = eof,
channel.put(Channel, stop, !IO),
mvar.take(MVar, Count, !IO),
io.format("%d lines printed.\n", [i(Count)], !IO)
;
Res = error(Err),
channel.put(Channel, stop, !IO),
io.format("Error reading file: %s\n", [s(io.error_message(Err))], !IO)
).
:- pred writer(channel(line_or_stop)::in, mvar(int)::in, int::in,
io::di, io::uo) is cc_multi.
writer(Channel, MVar, Count, !IO) :-
channel.take(Channel, LineOrStop, !IO),
(
LineOrStop = line(Line),
io.write_string(Line, !IO),
writer(Channel, MVar, Count + 1, !IO)
;
LineOrStop = stop,
mvar.put(MVar, Count, !IO)
). |
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.
| #Nim | Nim | var msgs: Channel[string]
var count: Channel[int]
const FILE = "input.txt"
proc read() {.thread.} =
for line in FILE.lines:
msgs.send(line)
msgs.send("")
echo count.recv()
count.close()
proc print() {.thread.} =
var n = 0
while true:
var msg = msgs.recv()
if msg.len == 0:
break
echo msg
n += 1
msgs.close()
count.send(n)
var reader_thread = Thread[void]()
var printer_thread = Thread[void]()
msgs.open()
count.open()
createThread(reader_thread, read)
createThread(printer_thread, print)
joinThreads(reader_thread, printer_thread) |
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)
| #AutoIt | AutoIt | MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC) |
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)
| #Avail | Avail | Print: “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.
| #Clojure | Clojure | (defmacro reduce-with
"simplifies form of reduce calls"
[bindings & body]
(assert (and (vector? bindings) (= 4 (count bindings))))
(let [[acc init, item sequence] bindings]
`(reduce (fn [~acc ~item] ~@body) ~init ~sequence)))
(defn digits
"maps e.g. 2345 => [2 3 4 5]"
[n] (->> n str seq (map #(- (int %) (int \0))) vec))
(defn dcount
"handles case (probably impossible in this range) of digit count > 9"
[ds] (let [c (count ds)] (if (< c 10) c (digits c))))
(defn summarize-prev
"produces the summary sequence for a digit sequence"
[ds]
(->> ds (sort >) (partition-by identity) (map (juxt dcount first)) flatten vec)
(defn convergent-sequence
"iterates summarize-prev until a duplicate is found; returns summary step sequence"
[ds]
(reduce-with [cur-seq [], ds (iterate summarize-prev ds)]
(if (some #{ds} cur-seq)
(reduced cur-seq)
(conj cur-seq ds))))
(defn candidate-seq
"only try an already sorted digit sequence, so we only try equivalent seeds once;
e.g. 23 => []; 32 => (convergent-sequence [3 2])"
[n]
(let [ds (digits n)]
(if (apply >= ds) (convergent-sequence ds) [])))
(defn find-longest
"the meat of the task; returns summary step sequence(s) of max length within the range"
[limit]
(reduce-with [max-seqs [[]], new-seq (map candidate-seq (range 1 limit))]
(let [cmp (compare (-> max-seqs first count) (count new-seq))]
(cond
(pos? cmp) max-seqs
(neg? cmp) [new-seq]
(zero? cmp) (conj max-seqs new-seq)))))
(def results (find-longest 1000000)) |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #J | J | primes=: p: i. _1 p: 1000 NB. all prime numbers below 1000
sums=: +/\ primes NB. running sum of those primes
mask=: 1 p: sums NB. array of 0s, 1s where sums are primes
NB. indices of prime sums (incremented for 1-based indexing)
NB. "copy" only the final primes in the prime sums
NB. "copy" only the sums which are prime
results=: (>: I. mask) ,. (mask # primes) ,. (mask # sums)
NB. pretty-printed "boxed" output
output=: 2 1 $ ' n prime sum ' ; < results |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #jq | jq | def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
else {i:23}
| until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
| .i * .i > $n
end;
# primes up to but excluding $n
def primes($n): [range(2;$n) | select(is_prime)];
"Prime sums of primes less than 1000",
(primes(1000)
| range(1; length) as $n
| (.[: $n] | add) as $sum
| select($sum | is_prime)
| "The sum of the \($n) primes from 2 to \(.[$n-1]) is \($sum)." ) |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Julia | Julia | using Primes
p1000 = primes(1000)
for n in 1:length(p1000)
parray = p1000[1:n]
sparray = sum(parray)
if isprime(sparray)
println("The sum of the $n primes from prime 2 to prime $(p1000[n]) is $sparray, which is prime.")
end
end
|
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | p = Prime[Range[PrimePi[1000]]];
TableForm[
Select[Transpose[{Range[Length[p]], p, Accumulate[p]}], Last /* PrimeQ],
TableHeadings -> {None, {"Prime count", "Prime", "Prime sum"}}
] |
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.)
| #JavaScript | JavaScript |
<html>
<head>
<script>
function clip (subjectPolygon, clipPolygon) {
var cp1, cp2, s, e;
var inside = function (p) {
return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]);
};
var intersection = function () {
var 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];
};
var outputList = subjectPolygon;
cp1 = clipPolygon[clipPolygon.length-1];
for (var j in clipPolygon) {
cp2 = clipPolygon[j];
var inputList = outputList;
outputList = [];
s = inputList[inputList.length - 1]; //last on the input list
for (var i in inputList) {
e = inputList[i];
if (inside(e)) {
if (!inside(s)) {
outputList.push(intersection());
}
outputList.push(e);
}
else if (inside(s)) {
outputList.push(intersection());
}
s = e;
}
cp1 = cp2;
}
return outputList
}
function drawPolygon(context, polygon, strokeStyle, fillStyle) {
context.strokeStyle = strokeStyle;
context.fillStyle = fillStyle;
context.beginPath();
context.moveTo(polygon[0][0],polygon[0][1]); //first vertex
for (var i = 1; i < polygon.length ; i++)
context.lineTo(polygon[i][0],polygon[i][1]);
context.lineTo(polygon[0][0],polygon[0][1]); //back to start
context.fill();
context.stroke();
context.closePath();
}
window.onload = function () {
var context = document.getElementById('canvas').getContext('2d');
var subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]],
clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];
var clippedPolygon = clip(subjectPolygon, clipPolygon);
drawPolygon(context, clipPolygon, '#888','#88f');
drawPolygon(context, subjectPolygon, '#888','#8f8');
drawPolygon(context, clippedPolygon, '#000','#0ff');
}
</script>
<body>
<canvas id='canvas' width='400' height='400'></canvas>
</body>
</html>
|
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).
| #D | D | import std.stdio, std.algorithm, std.array;
struct Set(T) {
immutable T[] items;
Set opSub(in Set other) const pure nothrow {
return items.filter!(x => !other.items.canFind(x)).array.Set;
}
Set opAdd(in Set other) const pure nothrow {
return Set(this.items ~ (other - this).items);
}
}
Set!T symmetricDifference(T)(in Set!T left, in Set!T right)
pure nothrow {
return (left - right) + (right - left);
}
void main() {
immutable A = ["John", "Bob", "Mary", "Serena"].Set!string;
immutable B = ["Jim", "Mary", "John", "Bob"].Set!string;
writeln(" A\\B: ", (A - B).items);
writeln(" B\\A: ", (B - A).items);
writeln("A symdiff B: ", symmetricDifference(A, B).items);
} |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #REXX | REXX | /*REXX program computes and displays the first N super─d numbers for D from LO to HI.*/
numeric digits 100 /*ensure enough decimal digs for calc. */
parse arg n LO HI . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 10 /*the number of super─d numbers to calc*/
if LO=='' | LO=="," then LO= 2 /*low end of D for the super─d nums.*/
if HI=='' | HI=="," then HI= 9 /*high " " " " " " " */
/* [↓] process D from LO ──► HI. */
do d=LO to HI; #= 0; $= /*count & list of super─d nums (so far)*/
z= copies(d, d) /*the string that is being searched for*/
do j=2 until #==n /*search for super─d numbers 'til found*/
if pos(z, d * j**d)==0 then iterate /*does product have the required reps? */
#= # + 1; $= $ j /*bump counter; add the number to list*/
end /*j*/
say
say center(' the first ' n " super-"d 'numbers ', digits(), "═")
say $
end /*d*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Ruby | Ruby | (2..8).each do |d|
rep = d.to_s * d
print "#{d}: "
puts (2..).lazy.select{|n| (d * n**d).to_s.include?(rep) }.first(10).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.
| #J | J | require 'files strings'
notes=: monad define
if. #y do.
now=. LF ,~ 6!:0 'hh:mm:ss DD/MM/YYYY'
'notes.txt' fappend~ now, LF ,~ TAB, ' ' joinstring y
elseif. -. _1 -: txt=. fread 'notes.txt' do.
smoutput txt
end.
)
notes 2}.ARGV
exit 0 |
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.
| #Java | Java | import java.io.*;
import java.nio.channels.*;
import java.util.Date;
public class TakeNotes {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
PrintStream ps = new PrintStream(new FileOutputStream("notes.txt", true));
ps.println(new Date());
ps.print("\t" + args[0]);
for (int i = 1; i < args.length; i++)
ps.print(" " + args[i]);
ps.println();
ps.close();
} else {
FileChannel fc = new FileInputStream("notes.txt").getChannel();
fc.transferTo(0, fc.size(), Channels.newChannel(System.out));
fc.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
| #Lua | Lua | local abs,cos,floor,pi,pow,sin = math.abs,math.cos,math.floor,math.pi,math.pow,math.sin
local bitmap = {
init = function(self, w, h, value)
self.w, self.h, self.pixels = w, h, {}
for y=1,h do self.pixels[y]={} end
self:clear(value)
end,
clear = function(self, value)
for y=1,self.h do
for x=1,self.w do
self.pixels[y][x] = value or " "
end
end
end,
set = function(self, x, y, value)
x,y = floor(x+0.5),floor(y+0.5)
if x>0 and y>0 and x<=self.w and y<=self.h then
self.pixels[y][x] = value or "#"
end
end,
superellipse = function(self, ox, oy, n, a, b, c)
local function sgn(n) return n>=0 and 1 or -1 end
for t = 0, 1, 0.002 do
local theta = t * 2 * pi
local x = ox + a * pow(abs(cos(theta)), 2/n) * sgn(cos(theta))
local y = oy + b * pow(abs(sin(theta)), 2/n) * sgn(sin(theta))
self:set(x, y, c)
end
end,
render = function(self)
for y=1,self.h do
print(table.concat(self.pixels[y]))
end
end,
}
bitmap:init(80, 60, "..")
bitmap:superellipse(40, 30, 2.5, 38, 28, "[]")
bitmap:render() |
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).
| #Phix | Phix | -- demo\rosetta\Taxicab_numbers.exw
with javascript_semantics
function cube_sums()
// create cubes and sorted list of cube sums
sequence cubes = {}, sums = {}
for i=1 to 1189 do
atom cube = i * i * i
sums &= sq_add(cubes,cube)
cubes &= cube
end for
sums = sort(sums) -- (706,266 in total)
return {cubes,sums}
end function
sequence {cubes, sums} = cube_sums()
atom nm1 = sums[1],
n = sums[2]
integer idx = 1
printf(1,"First 25 Taxicab Numbers, 2000..2006th, and all interim triples:\n")
for i=3 to length(sums) do
atom np1 = sums[i]
if n=np1 and n!=nm1 then
if idx<=25
or (idx>=2000 and idx<=2006)
or n=sums[i+1] then
sequence s = {}
for j=1 to length(cubes) do
atom x = cubes[j],
y = n-x
if y<x then exit end if
integer ydx = binary_search(y,cubes)
if ydx>0 then
s = append(s,sprintf("(%3d^3=%9d) + (%4d^3=%10d)",{j,x,ydx,y}))
end if
end for
printf(1,"%4d %10d = %s\n",{idx,n,join(s," or ")})
end if
idx += 1
end if
nm1 = n
n = np1
end for
|
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #REXX | REXX | /*REXX program attempts to find better minimizations for computing superpermutations.*/
parse arg cycles . /*obtain optional arguments from the CL*/
if cycles=='' | cycles=="," then cycles= 7 /*Not specified? Then use the default.*/
do n=0 to cycles
#= 0; $.= /*populate the first permutation. */
do pop=1 for n; @.pop= d2x(pop); $.0= $.0 || @.pop
end /*pop*/
do while aPerm(n, 0)
if n\==0 then #= #+1; $.#=
do j=1 for n; $.#= $.# || @.j
end /*j*/
end /*while*/
z= $.0
nm= n-1
do p=1 for #; if $.j=='' then iterate
if pos($.p, z)\==0 then iterate
parse var $.p h 2 R 1 L =(n)
if left(z, nm)==R then do; z= h || z; iterate; end
if right(z, 1)==h then do; z= z || R; iterate; end
z= z || $.p
end /*p*/ /* [↑] more IFs could be added for opt*/
L= commas( length(z) )
say 'length of superpermutation('n") =" right(L, max(length(L), cycles+2) )
end /*cycle*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
aPerm: procedure expose @.; parse arg n,i; nm= n - 1; if n==0 then return 0
do k=nm by -1 for nm; kp=k+1; if @.k<@.kp then do; i=k; leave; end; end /*k*/
do j=i+1 while j<n; parse value @.j @.n with @.n @.j; n= n-1; end /*j*/
if i==0 then return 0
do m=i+1 while @.m<@.i; end /*m*/; parse value @.m @.i with @.i @.m
return 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
| #Common_Lisp | Common Lisp |
(defun to-celsius (k)
(- k 273.15))
(defun to-fahrenheit (k)
(- (* k 1.8) 459.67))
(defun to-rankine (k)
(* k 1.8))
(defun temperature-conversion ()
(let ((k (read)))
(if (numberp k)
(format t "Celsius: ~d~%Fahrenheit: ~d~%Rankine: ~d~%"
(to-celsius k) (to-fahrenheit k) (to-rankine k))
(format t "Error: Non-numeric value entered."))))
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Sidef | Sidef | say { .sigma0 }.map(1..100).join(' ') |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Swift | Swift | import Foundation
// See https://en.wikipedia.org/wiki/Divisor_function
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
// Deal with powers of 2 first
while (n & 1) == 0 {
total += 1
n >>= 1
}
// Odd prime factors up to the square root
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
total *= count
p += 2
}
// If n > 1 then it's prime
if n > 1 {
total *= 2
}
return total
}
let limit = 100
print("Count of divisors for the first \(limit) positive integers:")
for n in 1...limit {
print(String(format: "%3d", divisorCount(number: n)), terminator: "")
if n % 20 == 0 {
print()
}
} |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Tiny_BASIC | Tiny BASIC | LET N = 0
10 LET N = N + 1
IF N < 3 THEN GOTO 100
LET T = 2
LET A = 1
20 LET A = A + 1
IF (N/A)*A = N THEN LET T = T + 1
IF A<(N+1)/2 THEN GOTO 20
30 PRINT "Tau(",N,") = ",T
IF N<100 THEN GOTO 10
END
100 LET T = N
GOTO 30 |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Tcl | Tcl | puts -nonewline "\033\[2J"
flush stdout |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #UNIX_Shell | UNIX Shell | clear
# Alternative method using tput
tput clear |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Visual_Basic_.NET | Visual Basic .NET | System.Console.Clear() |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #PicoLisp | PicoLisp | (de 3not (A)
(or (=0 A) (not A)) )
(de 3and (A B)
(cond
((=T A) B)
((=0 A) (and B 0)) ) )
(de 3or (A B)
(cond
((=T A) T)
((=0 A) (or (=T B) 0))
(T B) ) )
(de 3impl (A B)
(cond
((=T A) B)
((=0 A) (or (=T B) 0))
(T T) ) )
(de 3equiv (A B)
(cond
((=T A) B)
((=0 A) 0)
(T (3not B)) ) ) |
http://rosettacode.org/wiki/Text_processing/1 | Text processing/1 | This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is often used in programming circles for this task.
A request on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
Each row corresponds to 1 day and the field logic is: $1 is the date,
followed by 24 value/flag pairs, representing measurements at 01:00,
02:00 ... 24:00 of the respective day. In short:
<date> <val1> <flag1> <val2> <flag2> ... <val24> <flag24>
Some test data is available at:
... (nolonger available at original location)
I have to sum up the values (per day and only valid data, i.e. with
flag>0) in order to calculate the mean. That's not too difficult.
However, I also need to know what the "maximum data gap" is, i.e. the
longest period with successive invalid measurements (i.e values with
flag<=0)
The data is free to download and use and is of this format:
Data is no longer available at that link. Zipped mirror available here (offsite mirror).
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Only a sample of the data showing its format is given above. The full example file may be downloaded here.
Structure your program to show statistics for each line of the file, (similar to the original Python, Perl, and AWK examples below), followed by summary statistics for the file. When showing example output just show a few line statistics and the full end summary.
| #Ruby | Ruby | filename = "readings.txt"
total = { "num_readings" => 0, "num_good_readings" => 0, "sum_readings" => 0.0 }
invalid_count = 0
max_invalid_count = 0
invalid_run_end = ""
File.new(filename).each do |line|
num_readings = 0
num_good_readings = 0
sum_readings = 0.0
fields = line.split
fields[1..-1].each_slice(2) do |reading, flag|
num_readings += 1
if Integer(flag) > 0
num_good_readings += 1
sum_readings += Float(reading)
invalid_count = 0
else
invalid_count += 1
if invalid_count > max_invalid_count
max_invalid_count = invalid_count
invalid_run_end = fields[0]
end
end
end
printf "Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f\n",
fields[0], num_readings - num_good_readings, num_good_readings, sum_readings,
num_good_readings > 0 ? sum_readings/num_good_readings : 0.0
total["num_readings"] += num_readings
total["num_good_readings"] += num_good_readings
total["sum_readings"] += sum_readings
end
puts ""
puts "File(s) = #{filename}"
printf "Total = %.3f\n", total['sum_readings']
puts "Readings = #{total['num_good_readings']}"
printf "Average = %.3f\n", total['sum_readings']/total['num_good_readings']
puts ""
puts "Maximum run(s) of #{max_invalid_count} consecutive false readings ends at #{invalid_run_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
| #Perl | Perl | use v5.10;
my @days = qw{ first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth };
chomp ( my @gifts = grep { /\S/ } <DATA> );
while ( my $day = shift @days ) {
say "On the $day day of Christmas,\nMy true love gave to me:";
say for map { $day eq 'first' ? s/And a/A/r : $_ } @gifts[@days .. @gifts-1];
say "";
}
__DATA__
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. |
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.
| #OCaml | OCaml | open Event |
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.
| #Oforth | Oforth | import: parallel
: printing(chPrint, chCount)
0 while( chPrint receive dup notNull ) [ println 1+ ] drop
chCount send drop ;
: concurrentPrint(aFileName)
| chPrint chCount line |
Channel new ->chPrint
Channel new ->chCount
#[ printing(chPrint, chCount) ] &
aFileName File new forEach: line [ chPrint send(line) drop ]
chPrint close
chCount receive "Number of lines printed : " print println ; |
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)
| #AWK | AWK | $ awk 'BEGIN{print systime(),strftime()}' |
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)
| #BaCon | BaCon | ' BaCon time
n = NOW
PRINT n, " seconds since January 1st, 1970"
PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%04d/%02d/%02d "
PRINT HOUR(n), MINUTE(n), SECOND(n) FORMAT "%02d:%02d:%02d\n" |
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.
| #CLU | CLU | summarize = proc (s: string) returns (string) signals (bad_format)
digit_count: array[int] := array[int]$fill(0,10,0)
for c: char in string$chars(s) do
d: int := int$parse(string$c2s(c)) resignal bad_format
digit_count[d] := digit_count[d] + 1
end
out: stream := stream$create_output()
for d: int in int$from_to_by(9,0,-1) do
if digit_count[d]>0 then
stream$puts(out, int$unparse(digit_count[d]))
stream$puts(out, int$unparse(d))
end
end
return(stream$get_contents(out))
end summarize
converge = proc (s: string) returns (int) signals (bad_format)
seen: array[string] := array[string]$[]
steps: int := 0
while true do
for str: string in array[string]$elements(seen) do
if str = s then return(steps) end
end
array[string]$addh(seen, s)
s := summarize(s)
steps := steps + 1
end
end converge
start_up = proc ()
po: stream := stream$primary_output()
seeds: array[int]
max: int := 0
for i: int in int$from_to(1, 999999) do
steps: int := converge(int$unparse(i))
if steps > max then
max := steps
seeds := array[int]$[i]
elseif steps = max then
array[int]$addh(seeds,i)
end
end
stream$puts(po, "Seed values: ")
for i: int in array[int]$elements(seeds) do
stream$puts(po, int$unparse(i) || " ")
end
stream$putl(po, "\nIterations: " || int$unparse(max))
stream$putl(po, "\nSequence: ")
s: string := int$unparse(array[int]$bottom(seeds))
for i: int in int$from_to(1, max) do
stream$putl(po, s)
s := summarize(s)
end
end start_up |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Nim | Nim | import math, strformat
const N = 999
func isPrime(n: Positive): bool =
if (n and 1) == 0: return n == 2
if (n mod 3) == 0: return n == 3
var d = 5
var delta = 2
while d <= sqrt(n.toFloat).int:
if n mod d == 0: return false
inc d, delta
delta = 6 - delta
result = true
echo "index prime prime sum"
var s = 0
var idx = 0
for n in 2..N:
if n.isPrime:
inc idx
s += n
if s.isPrime: echo &"{idx:3} {n:5} {s:7}" |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Perl | Perl | use strict;
use warnings;
use ntheory <nth_prime is_prime>;
my($n, $s, $limit, @sums) = (0, 0, 1000);
do {
push @sums, sprintf '%3d %8d', $n, $s if is_prime($s += nth_prime ++$n)
} until $n >= $limit;
print "Of the first $limit primes: @{[scalar @sums]} cumulative prime sums:\n", join "\n", @sums; |
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Phix | Phix | function sp(integer n) return is_prime(sum(get_primes(-n))) end function
sequence res = apply(filter(tagset(length(get_primes_le(1000))),sp),sprint)
printf(1,"Found %d of em: %s\n",{length(res),join(shorten(res,"",5),", ")})
|
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.)
| #Julia | Julia | using Luxor
isinside(p, a, b) = (b.x - a.x) * (p.y - a.y) > (b.y - a.y) * (p.x - a.x)
function intersection(a, b, s, f)
dc = [a.x - b.x, a.y - b.y]
dp = [s.x - f.x, s.y - f.y]
n1 = a.x * b.y - a.y * b.x
n2 = s.x * f.y - s.y * f.x
n3 = 1.0 / (dc[1] * dp[2] - dc[2] * dp[1])
Point((n1 * dp[1] - n2 * dc[1]) * n3, (n1 * dp[2] - n2 * dc[2]) * n3)
end
function clipSH(spoly, cpoly)
outarr = spoly
q = cpoly[end]
for p in cpoly
inarr = outarr
outarr = Point[]
s = inarr[end]
for vtx in inarr
if isinside(vtx, q, p)
if !isinside(s, q, p)
push!(outarr, intersection(q, p, s, vtx))
end
push!(outarr, vtx)
elseif isinside(s, q, p)
push!(outarr, intersection(q, p, s, vtx))
end
s = vtx
end
q = p
end
outarr
end
subjectp = [Point(50, 150), Point(200, 50), Point(350, 150), Point(350, 300),
Point(250, 300), Point(200, 250), Point(150, 350), Point(100, 250), Point(100, 200)]
clipp = [Point(100, 100), Point(300, 100), Point(300, 300), Point(100, 300)]
Drawing(400, 400, "intersecting-polygons.png")
background("white")
sethue("red")
poly(subjectp, :stroke, close=true)
sethue("blue")
poly(clipp, :stroke, close=true)
clipped = clipSH(subjectp, clipp)
sethue("gold")
poly(clipped, :fill, close=true)
finish()
preview()
println(clipped)
|
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.)
| #Kotlin | Kotlin | // version 1.1.2
import java.awt.*
import java.awt.geom.Line2D
import javax.swing.*
class SutherlandHodgman : JPanel() {
private val subject = listOf(
doubleArrayOf( 50.0, 150.0), doubleArrayOf(200.0, 50.0), doubleArrayOf(350.0, 150.0),
doubleArrayOf(350.0, 300.0), doubleArrayOf(250.0, 300.0), doubleArrayOf(200.0, 250.0),
doubleArrayOf(150.0, 350.0), doubleArrayOf(100.0, 250.0), doubleArrayOf(100.0, 200.0)
)
private val clipper = listOf(
doubleArrayOf(100.0, 100.0), doubleArrayOf(300.0, 100.0),
doubleArrayOf(300.0, 300.0), doubleArrayOf(100.0, 300.0)
)
private var result = subject.toMutableList()
init {
preferredSize = Dimension(600, 500)
clipPolygon()
}
private fun clipPolygon() {
val len = clipper.size
for (i in 0 until len) {
val len2 = result.size
val input = result
result = mutableListOf<DoubleArray>()
val a = clipper[(i + len - 1) % len]
val b = clipper[i]
for (j in 0 until len2) {
val p = input[(j + len2 - 1) % len2]
val q = input[j]
if (isInside(a, b, q)) {
if (!isInside(a, b, p)) result.add(intersection(a, b, p, q))
result.add(q)
}
else if (isInside(a, b, p)) result.add(intersection(a, b, p, q))
}
}
}
private fun isInside(a: DoubleArray, b: DoubleArray, c: DoubleArray) =
(a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0])
private fun intersection(a: DoubleArray, b: DoubleArray,
p: DoubleArray, q: DoubleArray): DoubleArray {
val a1 = b[1] - a[1]
val b1 = a[0] - b[0]
val c1 = a1 * a[0] + b1 * a[1]
val a2 = q[1] - p[1]
val b2 = p[0] - q[0]
val c2 = a2 * p[0] + b2 * p[1]
val d = a1 * b2 - a2 * b1
val x = (b2 * c1 - b1 * c2) / d
val y = (a1 * c2 - a2 * c1) / d
return doubleArrayOf(x, y)
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val g2 = g as Graphics2D
g2.translate(80, 60)
g2.stroke = BasicStroke(3.0f)
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
drawPolygon(g2, subject, Color.blue)
drawPolygon(g2, clipper, Color.red)
drawPolygon(g2, result, Color.green)
}
private fun drawPolygon(g2: Graphics2D, points: List<DoubleArray>, color: Color) {
g2.color = color
val len = points.size
val line = Line2D.Double()
for (i in 0 until len) {
val p1 = points[i]
val p2 = points[(i + 1) % len]
line.setLine(p1[0], p1[1], p2[0], p2[1])
g2.draw(line)
}
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with(f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
add(SutherlandHodgman(), BorderLayout.CENTER)
title = "Sutherland-Hodgman"
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
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).
| #Datalog | Datalog | .decl A(text: symbol)
.decl B(text: symbol)
.decl SymmetricDifference(text: symbol)
.output SymmetricDifference
A("this").
A("is").
A("a").
A("test").
B("also").
B("part").
B("of").
B("a").
B("test").
SymmetricDifference(x) :- A(x), !B(x).
SymmetricDifference(x) :- B(x), !A(x). |
http://rosettacode.org/wiki/Symmetric_difference | Symmetric difference | Task
Given two sets A and B, compute
(
A
∖
B
)
∪
(
B
∖
A
)
.
{\displaystyle (A\setminus B)\cup (B\setminus A).}
That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B.
In other words:
(
A
∪
B
)
∖
(
A
∩
B
)
{\displaystyle (A\cup B)\setminus (A\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).
| #Delphi | Delphi |
PROGRAM Symmetric_difference;
uses
System.Typinfo;
TYPE
TName = (Bob, Jim, John, Mary, Serena);
TList = SET OF TName;
TNameHelper = record helper for TName
FUNCTION ToString(): string;
end;
{ TNameHlper }
FUNCTION TNameHelper.ToString: string;
BEGIN
Result := GetEnumName(TypeInfo(TName), Ord(self));
END;
PROCEDURE Put(txt: String; ResSet: TList);
VAR
I: TName;
BEGIN
Write(txt);
FOR I IN ResSet DO
Write(I.ToString, ' ');
WriteLn;
END;
VAR
ListA: TList = [John, Bob, Mary, Serena];
ListB: TList = [Jim, Mary, John, Bob];
BEGIN
Put('ListA -> ', ListA);
Put('ListB -> ', ListB);
Put('ListA >< ListB -> ', (ListA - ListB) + (ListB - ListA));
Put('ListA - ListB -> ', ListA - ListB);
Put('ListB - ListA -> ', ListB - ListA);
ReadLn;
END. |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Rust | Rust | // [dependencies]
// rug = "1.9"
fn print_super_d_numbers(d: u32, limit: u32) {
use rug::Assign;
use rug::Integer;
println!("First {} super-{} numbers:", limit, d);
let digits = d.to_string().repeat(d as usize);
let mut count = 0;
let mut n = 1;
let mut s = Integer::new();
while count < limit {
s.assign(Integer::u_pow_u(n, d));
s *= d;
if s.to_string().contains(&digits) {
print!("{} ", n);
count += 1;
}
n += 1;
}
println!();
}
fn main() {
for d in 2..=9 {
print_super_d_numbers(d, 10);
}
} |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Sidef | Sidef | func super_d(d) {
var D = Str(d)*d
1..Inf -> lazy.grep {|n| Str(d * n**d).contains(D) }
}
for d in (2..8) {
say ("#{d}: ", super_d(d).first(10))
} |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Swift | Swift | import BigInt
import Foundation
let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]
for d in 2...9 {
print("First 10 super-\(d) numbers:")
var count = 0
var n = BigInt(3)
var k = BigInt(0)
while true {
k = n.power(d)
k *= BigInt(d)
if let _ = String(k).range(of: rd[d - 2]) {
count += 1
print(n, terminator: " ")
fflush(stdout)
guard count < 10 else {
break
}
}
n += 1
}
print()
print()
} |
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.
| #JavaScript | JavaScript | var notes = 'NOTES.TXT';
var args = WScript.Arguments;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2, ForAppending = 8;
if (args.length == 0) {
if (fso.FileExists(notes)) {
var f = fso.OpenTextFile(notes, ForReading);
WScript.Echo(f.ReadAll());
f.Close();
}
}
else {
var f = fso.OpenTextFile(notes, ForAppending, true);
var d = new Date();
f.WriteLine(d.toLocaleString());
f.Write("\t");
// note that WScript.Arguments is not an array, it is a "collection"
// it does not have a join() method.
for (var i = 0; i < args.length; i++) {
f.Write(args(i) + " ");
}
f.WriteLine();
f.Close();
} |
http://rosettacode.org/wiki/Take_notes_on_the_command_line | Take notes on the command line | Take notes on the command line is part of Short Circuit's Console Program Basics selection.
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists.
If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline.
Then 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.
| #Julia | Julia | using Dates
const filename = "NOTES.TXT"
if length(ARGS) == 0
fp = open(filename, "r")
println(read(fp, String))
else
fp = open(filename, "a+")
write(fp, string(DateTime(now()), "\n\t", join(ARGS, " "), "\n"))
end
close(fp)
|
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
| #Maple | Maple | plots:-implicitplot(abs((1/200)*x^2.5)+abs((1/200)*y^2.5) = 1, x = -10 .. 10, y = -10 .. 10); |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ContourPlot[Abs[x/200]^2.5 + Abs[y/200]^2.5 == 1, {x, -200, 200}, {y, -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).
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
(off 'B)
(for L (subsets 2 (range 1 1200))
(let K (sum '((N) (** N 3)) L)
(ifn (lup B K)
(idx 'B (list K 1 (list L)) T)
(inc (cdr @))
(push (cddr @) L) ) ) )
(setq R
(filter
'((L) (>= (cadr L) 2))
(idx 'B)) )
(for L (head 25 R)
(println (car L) (caddr L)) )
(for L (head 7 (nth R 2000))
(println (car L) (caddr L)) ) |
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).
| #PureBasic | PureBasic | #MAX=1189
Macro q3(a,b)
a*a*a+b*b*b
EndMacro
Structure Cap
x.i
y.i
s.i
EndStructure
NewList Taxi.Cap()
For i=1 To #MAX
For j=i To #MAX
AddElement(Taxi()) : Taxi()\s=q3(i,j) : Taxi()\x=i : Taxi()\y=j
Next j
Next i
SortStructuredList(Taxi(),#PB_Sort_Ascending,OffsetOf(Cap\s),TypeOf(Cap\s))
If OpenConsole()
ForEach Taxi()
If sum=Taxi()\s
r$+"="+RSet(Str(Taxi()\x),4)+"³ +"+RSet(Str(Taxi()\y),4)+"³ " : Continue
EndIf
If CountString(r$,"=")>=2 : c+1 : EndIf
If CountString(r$,"=")=2
Select c
Case 1 To 25, 2000 To 2006 : PrintN(RSet(Str(c),5)+": "+RSet(Str(sum),10)+r$)
Case Bool(c>2006) : Break
EndSelect
EndIf
r$=""
sum=Taxi()\s : r$="="+RSet(Str(Taxi()\x),4)+"³ +"+RSet(Str(Taxi()\y),4)+"³ "
Next
PrintN("FIN.") : Input()
EndIf |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Ruby | Ruby | #A straight forward implementation of N. Johnston's algorithm. I prefer to look at this as 2n+1 where
#the second n is first n reversed, and the 1 is always the second symbol. This algorithm will generate
#just the left half of the result by setting l to [1,2] and looping from 3 to 6. For the purpose of
#this task I am going to start from an empty array and generate the whole strings using just the
#rules.
#
#Nigel Galloway: December 16th., 2014
#
l = []
(1..6).each{|e|
a, i = [], e-2
(0..l.length-e+1).each{|g|
if not (n = l[g..g+e-2]).uniq!
a.concat(n[(a[0]? i : 0)..-1]).push(e).concat(n)
i = e-2
else
i -= 1
end
}
a.each{|n| print n}; puts "\n\n"
l = a
} |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Scala | Scala | object SuperpermutationMinimisation extends App {
val nMax = 12
@annotation.tailrec
def factorial(number: Int, acc: Long = 1): Long =
if (number == 0) acc else factorial(number - 1, acc * number)
def factSum(n: Int): Long = (1 to n).map(factorial(_)).sum
for (n <- 0 until nMax) println(f"superPerm($n%2d) len = ${factSum(n)}%d")
} |
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
| #D | D | double kelvinToCelsius(in double k) pure nothrow @safe {
return k - 273.15;
}
double kelvinToFahrenheit(in double k) pure nothrow @safe {
return k * 1.8 - 459.67;
}
double kelvinToRankine(in double k) pure nothrow @safe {
return k * 1.8;
}
unittest {
import std.math: approxEqual;
assert(approxEqual(kelvinToCelsius(21.0), -252.15));
assert(approxEqual(kelvinToFahrenheit(21.0), -421.87));
assert(approxEqual(kelvinToRankine(21.0), 37.8));
}
void main(string[] args) {
import std.stdio, std.conv, std.string;
if (args.length == 2 && isNumeric(args[1])) {
immutable kelvin = to!double(args[1]);
if (kelvin >= 0) {
writefln("K %2.2f", kelvin);
writefln("C %2.2f", kelvinToCelsius(kelvin));
writefln("F %2.2f", kelvinToFahrenheit(kelvin));
writefln("R %2.2f", kelvinToRankine(kelvin));
} else
writefln("%2.2f K is below absolute zero", kelvin);
}
} |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Verilog | Verilog | module main;
integer N, T, A;
initial begin
$display("The tau functions for the first 100 positive integers are:\n");
for (N = 1; N <= 100; N=N+1) begin
if (N < 3) T = N;
else begin
T = 2;
for (A = 2; A <= (N+1)/2; A=A+1) begin
if (N % A == 0) T = T + 1;
end
end
$write(T);
if (N % 10 == 0) $display("");
end
$finish ;
end
endmodule |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Wren | Wren | import "/math" for Int
import "/fmt" for Fmt
System.print("The tau functions for the first 100 positive integers are:")
for (i in 1..100) {
Fmt.write("$2d ", Int.divisors(i).count)
if (i % 20 == 0) System.print()
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Wren | Wren | System.print("\e[2J") |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #XPL0 | XPL0 | code Clear=40;
Clear; |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Yabasic | Yabasic | clear screen |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #zkl | zkl | System.cmd(System.isWindows and "cls" or "clear");
// or, for ANSI terminals: print("\e[2J") |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #PureBasic | PureBasic | DataSection
TLogic:
Data.i -1,0,1
TSymb:
Data.s "F","?","T"
EndDataSection
Structure TL
F.i
M.i
T.i
EndStructure
Structure SYM
TS.s{2}[3]
EndStructure
*L.TL=?TLogic
*S.SYM=?TSymb
Procedure.i NOT3(*x.TL)
ProcedureReturn -*x
EndProcedure
Procedure.i AND3(*x.TL,*y.TL)
If *x>*y : ProcedureReturn *y : Else : ProcedureReturn *x : EndIf
EndProcedure
Procedure.i OR3(*x.TL,*y.TL)
If *x<*y : ProcedureReturn *y : Else : ProcedureReturn *x : EndIf
EndProcedure
Procedure.i EQV3(*x.TL,*y.TL)
ProcedureReturn *x * *y
EndProcedure
Procedure.i IMP3(*x.TL,*y.TL)
If -*y>*x : ProcedureReturn -*y : Else : ProcedureReturn *x : EndIf
EndProcedure
If OpenConsole("")
PrintN(" (AND) ( OR) (EQV) (IMP) (NOT)")
PrintN(" F ? T F ? T F ? T F ? T ")
PrintN(" -------------------------------------------------")
For *i.TL=*L\F To *L\T
rs$=" "+*S\TS[*i+1]+" | "
rs$+*S\TS[AND3(*L\F,*i)+1]+" "+*S\TS[AND3(*L\M,*i)+1]+" "+*S\TS[AND3(*L\T,*i)+1]
rs$+" "
rs$+*S\TS[OR3(*L\F,*i)+1] +" "+*S\TS[OR3(*L\M,*i)+1] +" "+*S\TS[OR3(*L\T,*i)+1]
rs$+" "
rs$+*S\TS[EQV3(*L\F,*i)+1]+" "+*S\TS[EQV3(*L\M,*i)+1]+" "+*S\TS[EQV3(*L\T,*i)+1]
rs$+" "
rs$+*S\TS[IMP3(*L\F,*i)+1]+" "+*S\TS[IMP3(*L\M,*i)+1]+" "+*S\TS[IMP3(*L\T,*i)+1]
rs$+" "+*S\TS[NOT3(*i)+1]
PrintN(rs$)
Next
EndIf
Input() |
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.
| #Scala | Scala | object DataMunging {
import scala.io.Source
def spans[A](list: List[A]) = list.tail.foldLeft(List((list.head, 1))) {
case ((a, n) :: tail, b) if a == b => (a, n + 1) :: tail
case (l, b) => (b, 1) :: l
}
type Flag = ((Boolean, Int), String)
type Flags = List[Flag]
type LineIterator = Iterator[Option[(Double, Int, Flags)]]
val pattern = """^(\d+-\d+-\d+)""" + """\s+(\d+\.\d+)\s+(-?\d+)""" * 24 + "$" r;
def linesIterator(file: java.io.File) = Source.fromFile(file).getLines().map(
pattern findFirstMatchIn _ map (
_.subgroups match {
case List(date, rawData @ _*) =>
val dataset = (rawData map (_ toDouble) iterator) grouped 2 toList;
val valid = dataset filter (_.last > 0) map (_.head)
val validSize = valid length;
val validSum = valid sum;
val flags = spans(dataset map (_.last > 0)) map ((_, date))
println("Line: %11s Reject: %2d Accept: %2d Line_tot: %10.3f Line_avg: %10.3f" format
(date, 24 - validSize, validSize, validSum, validSum / validSize))
(validSum, validSize, flags)
}
)
)
def totalizeLines(fileIterator: LineIterator) =
fileIterator.foldLeft(0.0, 0, List[Flag]()) {
case ((totalSum, totalSize, ((flag, size), date) :: tail), Some((validSum, validSize, flags))) =>
val ((firstFlag, firstSize), _) = flags.last
if (firstFlag == flag) {
(totalSum + validSum, totalSize + validSize, flags.init ::: ((flag, size + firstSize), date) :: tail)
} else {
(totalSum + validSum, totalSize + validSize, flags ::: ((flag, size), date) :: tail)
}
case ((_, _, Nil), Some(partials)) => partials
case (totals, None) => totals
}
def main(args: Array[String]) {
val files = args map (new java.io.File(_)) filter (file => file.isFile && file.canRead)
val lines = files.iterator flatMap linesIterator
val (totalSum, totalSize, flags) = totalizeLines(lines)
val ((_, invalidCount), startDate) = flags.filter(!_._1._1).max
val report = """|
|File(s) = %s
|Total = %10.3f
|Readings = %6d
|Average = %10.3f
|
|Maximum run(s) of %d consecutive false readings began at %s""".stripMargin
println(report format (files mkString " ", totalSum, totalSize, totalSum / totalSize, invalidCount, startDate))
}
} |
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
| #Phix | Phix | constant days = {"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"},
gifts = {"A partridge in a pear tree.\n",
"Two turtle doves, and\n",
"Three French hens,\n",
"Four calling birds,\n",
"Five gold rings,\n",
"Six geese a-laying,\n",
"Seven swans a-swimming,\n",
"Eight maids a-milking,\n",
"Nine ladies dancing,\n",
"Ten lords a-leaping,\n",
"Eleven pipers piping,\n",
"Twelve drummers drumming,\n"}
for i=1 to 12 do
printf(1,"On the %s day of Christmas,\nmy true love gave to me:\n",{days[i]})
for j=i to 1 by -1 do
printf(1,gifts[j])
end for
end for
|
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.
| #Ol | Ol |
(import (owl parse))
(coroutine 'reader (lambda ()
; lazy line-by-line file reader
(define (not-a-newline x) (not (eq? x #\newline)))
(define parser (let-parse*
((line (greedy* (byte-if not-a-newline)))
(newline (imm #\newline)))
(bytes->string line)))
(define file (file->bytestream "input.txt"))
(let loop ((in (try-parse parser file #false)))
(cond
((not in) ; file is ended
(define envelope (wait-mail)) ; wait for a request
(mail (ref envelope 1) #eof)) ; send an end-of-file to caller
((pair? in) ; new line is read
(define envelope (wait-mail)) ; wait for a request
(mail (ref envelope 1) (car in)) ; send a line to caller
(loop (try-parse parser (cdr in) #false)))
(else ; just a lazy read, let's repeat
(loop (force in)))))
(print "total lines read: " (await (mail 'writer #t)))
))
(coroutine 'writer (lambda ()
(let loop ((n 0))
(define line (await (mail 'reader #t)))
(if (eof? line)
then
(define envelope (wait-mail)) ; wait for a request
(mail (ref envelope 1) n) ; send a lines count to caller
else
(print "read line: " line)
(loop (+ n 1))))))
|
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)
| #BASIC | BASIC | PRINT TIMER |
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)
| #BASIC256 | BASIC256 | print month+1; "-"; day; "-"; year
# returns system date in format: mm-dd-yyyy
print hour; ":"; minute; ":"; second
# returns system time in format: hh:mm:ss |
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.
| #CoffeeScript | CoffeeScript |
sequence = (n) ->
cnts = {}
for c in n.toString()
d = parseInt(c)
incr cnts, d
seq = []
while true
s = ''
for i in [9..0]
s += "#{cnts[i]}#{i}" if cnts[i]
if s in seq
break
seq.push s
new_cnts = {}
for digit, cnt of cnts
incr new_cnts, cnt
incr new_cnts, digit
cnts = new_cnts
seq
incr = (h, k) ->
h[k] ?= 0
h[k] += 1
descending = (n) ->
return true if n < 10
tens = n / 10
return false if n % 10 > tens % 10
descending(tens)
max_len = 0
for i in [1..1000000]
if descending(i)
seq = sequence(i)
if seq.length > max_len
max_len = seq.length
max_seq = seq
max_i = i
console.log max_i, max_seq
|
http://rosettacode.org/wiki/Summarize_primes | Summarize primes | Task
Considering in order of length, n, all sequences of consecutive
primes, p, from 2 onwards, where p < 1000 and n>0, select those
sequences whose sum is prime, and for these display the length of the
sequence, the last item in the sequence, and the sum.
| #Python | Python | '''Prime sums of primes up to 1000'''
from itertools import accumulate, chain, takewhile
# primeSums :: [(Int, (Int, Int))]
def primeSums():
'''Non finite stream of enumerated tuples,
in which the first value is a prime,
and the second the sum of that prime and all
preceding primes.
'''
return (
x for x in enumerate(
accumulate(
chain([(0, 0)], primes()),
lambda a, p: (p, p + a[1])
)
) if isPrime(x[1][1])
)
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Prime sums of primes below 1000'''
for x in takewhile(
lambda t: 1000 > t[1][0],
primeSums()
):
print(f'{x[0]} -> {x[1][1]}')
# ----------------------- GENERIC ------------------------
# isPrime :: Int -> Bool
def isPrime(n):
'''True if n is prime.'''
if n in (2, 3):
return True
if 2 > n or 0 == n % 2:
return False
if 9 > n:
return True
if 0 == n % 3:
return False
def p(x):
return 0 == n % x or 0 == n % (2 + x)
return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))
# primes :: [Int]
def primes():
''' Non finite sequence of prime numbers.
'''
n = 2
dct = {}
while True:
if n in dct:
for p in dct[n]:
dct.setdefault(n + p, []).append(p)
del dct[n]
else:
yield n
dct[n * n] = [n]
n = 1 + n
# MAIN ---
if __name__ == '__main__':
main()
|
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.)
| #Lua | Lua | subjectPolygon = {
{50, 150}, {200, 50}, {350, 150}, {350, 300},
{250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}
}
clipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}
function inside(p, cp1, cp2)
return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)
end
function intersection(cp1, cp2, s, e)
local dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y
local dpx, dpy = s.x-e.x, s.y-e.y
local n1 = cp1.x*cp2.y - cp1.y*cp2.x
local n2 = s.x*e.y - s.y*e.x
local n3 = 1 / (dcx*dpy - dcy*dpx)
local x = (n1*dpx - n2*dcx) * n3
local y = (n1*dpy - n2*dcy) * n3
return {x=x, y=y}
end
function clip(subjectPolygon, clipPolygon)
local outputList = subjectPolygon
local cp1 = clipPolygon[#clipPolygon]
for _, cp2 in ipairs(clipPolygon) do -- WP clipEdge is cp1,cp2 here
local inputList = outputList
outputList = {}
local s = inputList[#inputList]
for _, e in ipairs(inputList) do
if inside(e, cp1, cp2) then
if not inside(s, cp1, cp2) then
outputList[#outputList+1] = intersection(cp1, cp2, s, e)
end
outputList[#outputList+1] = e
elseif inside(s, cp1, cp2) then
outputList[#outputList+1] = intersection(cp1, cp2, s, e)
end
s = e
end
cp1 = cp2
end
return outputList
end
function main()
local function mkpoints(t)
for i, p in ipairs(t) do
p.x, p.y = p[1], p[2]
end
end
mkpoints(subjectPolygon)
mkpoints(clipPolygon)
local outputList = clip(subjectPolygon, clipPolygon)
for _, p in ipairs(outputList) do
print(('{%f, %f},'):format(p.x, p.y))
end
end
main() |
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).
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | set :setA set{ :John :Bob :Mary :Serena }
set :setB set{ :Jim :Mary :John :Bob }
symmetric-difference A B:
}
for a in keys A:
if not has B a:
a
for b in keys B:
if not has A b:
b
set{
!. symmetric-difference setA setB |
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).
| #E | E | ? def symmDiff(a, b) { return (a &! b) | (b &! a) }
# value: <symmDiff>
? symmDiff(["John", "Bob", "Mary", "Serena"].asSet(), ["Jim", "Mary", "John", "Bob"].asSet())
# value: ["Jim", "Serena"].asSet() |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Module1
Sub Main()
Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
Dim one As BigInteger = 1
Dim nine As BigInteger = 9
For ii = 2 To 9
Console.WriteLine("First 10 super-{0} numbers:", ii)
Dim count = 0
Dim j As BigInteger = 3
While True
Dim k = ii * BigInteger.Pow(j, ii)
Dim ix = k.ToString.IndexOf(rd(ii - 2))
If ix >= 0 Then
count += 1
Console.Write("{0} ", j)
If count = 10 Then
Console.WriteLine()
Console.WriteLine()
Exit While
End If
End If
j += 1
End While
Next
End Sub
End Module |
http://rosettacode.org/wiki/Super-d_numbers | Super-d numbers | A super-d number is a positive, decimal (base ten) integer n such that d × nd has at least d consecutive digits d where
2 ≤ d ≤ 9
For instance, 753 is a super-3 number because 3 × 7533 = 1280873331.
Super-d numbers are also shown on MathWorld™ as super-d or super-d.
Task
Write a function/procedure/routine to find super-d numbers.
For d=2 through d=6, use the routine to show the first 10 super-d numbers.
Extra credit
Show the first 10 super-7, super-8, and/or super-9 numbers (optional).
See also
Wolfram MathWorld - Super-d Number.
OEIS: A014569 - Super-3 Numbers.
| #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
var start = System.clock
var rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888"]
for (i in 2..8) {
Fmt.print("First 10 super-$d numbers:", i)
var count = 0
var j = BigInt.three
while (true) {
var k = j.pow(i) * i
var ix = k.toString.indexOf(rd[i-2])
if (ix >= 0) {
count = count + 1
Fmt.write("$i ", j)
if (count == 10) {
Fmt.print("\nfound in $f seconds\n", System.clock - start)
break
}
}
j = j.inc
}
} |
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.
| #Kotlin | Kotlin | // version 1.2.10
import java.io.File
import java.util.Date
import java.text.SimpleDateFormat
fun main(args: Array<String>) {
val f = File("NOTES.TXT")
// create file if it doesn't exist already
f.createNewFile()
if (args.size == 0) {
println(f.readText())
}
else {
val df = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
val dt = df.format(Date())
val notes = "$dt\n\t${args.joinToString(" ")}\n"
f.appendText(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.
| #Lasso | Lasso | #!/usr/bin/lasso9
local(
arguments = $argv -> asarray,
notesfile = file('notes.txt')
)
#arguments -> removefirst
if(#arguments -> size) => {
#notesfile -> openappend
#notesfile -> dowithclose => {
#notesfile -> writestring(date -> format(`YYYY-MM-dd HH:mm:SS`) + '\n')
#notesfile -> writestring('\t' + #arguments -> join(', ') + '\n')
}
else
#notesfile -> exists ? stdout(#notesfile -> readstring)
} |
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
| #Nim | Nim | import math
import imageman
const
Size = 600
X0 = Size div 2
Y0 = Size div 2
Background = ColorRGBU [byte 0, 0, 0]
Foreground = ColorRGBU [byte 255, 255, 255]
proc drawSuperEllipse(img: var Image; n: float; a, b: int) =
var yList = newSeq[int](a + 1)
for x in 0..a:
let an = pow(a.toFloat, n)
let bn = pow(b.toFloat, n)
let xn = pow(x.toFloat, n)
let t = max(bn - xn * bn / an, 0.0) # Avoid negative values due to rounding errors.
yList[x] = pow(t, 1/n).toInt
var pos: seq[Point]
for x in countdown(a, 0):
pos.add (X0 + x, Y0 - yList[x])
for x in 0..a:
pos.add (X0 - x, Y0 - yList[x])
for x in countdown(a, 0):
pos.add (X0 - x, Y0 + yList[x])
for x in 0..a:
pos.add (X0 + x, Y0 + yList[x])
img.drawPolyline(true, Foreground, pos)
var image = initImage[ColorRGBU](Size, Size)
image.fill(Background)
image.drawSuperEllipse(2.5, 200, 200)
image.savePNG("super_ellipse.png", compression = 9) |
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
| #ooRexx | ooRexx | This program draws 5 super ellipses:
black 120,120,1.5
blue 160,160,2
red 200,200,2.5
green 240,240,3
black 280,280,4 |
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).
| #Python | Python | from collections import defaultdict
from itertools import product
from pprint import pprint as pp
cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
taxied = sorted((k, v) for k,v in sum2cubes.items() if len(v) >= 2)
#pp(len(taxied)) # 2068
for t in enumerate(taxied[:25], 1):
pp(t)
print('...')
for t in enumerate(taxied[2000-1:2000+6], 2000):
pp(t) |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Sidef | Sidef | for len in (1..8) {
var (pre="", post="")
@^len -> permutations {|*p|
var t = p.join
post.append!(t) if !post.contains(t)
pre.prepend!(t) if !pre.contains(t)
}
printf("%2d: %8d %8d\n", len, pre.len, post.len)
} |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #Wren | Wren | import "/fmt" for Fmt
var max = 12
var sp = []
var count = List.filled(max, 0)
var pos = 0
var factSum = Fn.new { |n|
var s = 0
var x = 0
var f = 1
while (x < n) {
x = x + 1
f = f * x
s = s + f
}
return s
}
var r // recursive
r = Fn.new { |n|
if (n == 0) return false
var c = sp[pos - n]
count[n] = count[n] - 1
if (count[n] == 0) {
count[n] = n
if (!r.call(n - 1)) return false
}
sp[pos] = c
pos = pos + 1
return true
}
var superPerm = Fn.new { |n|
pos = n
var len = factSum.call(n)
if (len > 0) sp = List.filled(len, "\0")
for (i in 0..n) count[i] = i
if (n > 0) {
for (i in 1..n) sp[i - 1] = String.fromByte(48 + i)
}
while (r.call(n)) {}
}
for (n in 0...max) {
superPerm.call(n)
Fmt.print("superPerm($2d) len = $d", n, sp.count)
} |
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
| #Delphi | Delphi |
program Temperature;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
TTemp = class
private
fCelsius, fFahrenheit, fRankine: double;
public
constructor Create(aKelvin: double);
property AsCelsius: double read fCelsius;
property AsFahrenheit: double read fFahrenheit;
property AsRankine: double read fRankine;
end;
{ TTemp }
constructor TTemp.Create(aKelvin: double);
begin
fCelsius := aKelvin - 273.15;
fRankine := aKelvin * 9 / 5;
fFahrenheit := fRankine - 459.67;
end;
var
kelvin: double;
temp: TTemp;
begin
write('Kelvin: ');
readln(kelvin);
temp := TTemp.Create(kelvin);
writeln(Format('Celsius: %.2f', [temp.AsCelsius]));
writeln(Format('Fahrenheit: %.2f', [temp.AsFahrenheit]));
writeln(Format('Rankine: %.2f', [temp.AsRankine]));
temp.Free;
readln;
end.
|
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #XPL0 | XPL0 | int N, D, C;
[Format(3, 0);
for N:= 1 to 100 do
[C:= 0;
for D:= 1 to N do
if rem(N/D) = 0 then C:= C+1;
RlOut(0, float(C));
if rem(N/20) = 0 then CrLf(0);
];
] |
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
| #Python | Python | class Trit(int):
def __new__(cls, value):
if value == 'TRUE':
value = 1
elif value == 'FALSE':
value = 0
elif value == 'MAYBE':
value = -1
return super(Trit, cls).__new__(cls, value // (abs(value) or 1))
def __repr__(self):
if self > 0:
return 'TRUE'
elif self == 0:
return 'FALSE'
return 'MAYBE'
def __str__(self):
return repr(self)
def __bool__(self):
if self > 0:
return True
elif self == 0:
return False
else:
raise ValueError("invalid literal for bool(): '%s'" % self)
def __or__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][1]
else:
try:
return _ttable[(self, Trit(bool(other)))][1]
except:
return NotImplemented
def __ror__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][1]
else:
try:
return _ttable[(self, Trit(bool(other)))][1]
except:
return NotImplemented
def __and__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][0]
else:
try:
return _ttable[(self, Trit(bool(other)))][0]
except:
return NotImplemented
def __rand__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][0]
else:
try:
return _ttable[(self, Trit(bool(other)))][0]
except:
return NotImplemented
def __xor__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][2]
else:
try:
return _ttable[(self, Trit(bool(other)))][2]
except:
return NotImplemented
def __rxor__(self, other):
if isinstance(other, Trit):
return _ttable[(self, other)][2]
else:
try:
return _ttable[(self, Trit(bool(other)))][2]
except:
return NotImplemented
def __invert__(self):
return _ttable[self]
def __getattr__(self, name):
if name in ('_n', 'flip'):
# So you can do x._n == x.flip; the inverse of x
# In Python 'not' is strictly boolean so we can't write `not x`
# Same applies to keywords 'and' and 'or'.
return _ttable[self]
else:
raise AttributeError
TRUE, FALSE, MAYBE = Trit(1), Trit(0), Trit(-1)
_ttable = {
# A: -> flip_A
TRUE: FALSE,
FALSE: TRUE,
MAYBE: MAYBE,
# (A, B): -> (A_and_B, A_or_B, A_xor_B)
(MAYBE, MAYBE): (MAYBE, MAYBE, MAYBE),
(MAYBE, FALSE): (FALSE, MAYBE, MAYBE),
(MAYBE, TRUE): (MAYBE, TRUE, MAYBE),
(FALSE, MAYBE): (FALSE, MAYBE, MAYBE),
(FALSE, FALSE): (FALSE, FALSE, FALSE),
(FALSE, TRUE): (FALSE, TRUE, TRUE),
( TRUE, MAYBE): (MAYBE, TRUE, MAYBE),
( TRUE, FALSE): (FALSE, TRUE, TRUE),
( TRUE, TRUE): ( TRUE, TRUE, FALSE),
}
values = ('FALSE', 'TRUE ', 'MAYBE')
print("\nTrit logical inverse, '~'")
for a in values:
expr = '~%s' % a
print(' %s = %s' % (expr, eval(expr)))
for op, ophelp in (('&', 'and'), ('|', 'or'), ('^', 'exclusive-or')):
print("\nTrit logical %s, '%s'" % (ophelp, op))
for a in values:
for b in values:
expr = '%s %s %s' % (a, op, b)
print(' %s = %s' % (expr, eval(expr))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.