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/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
| #Go | Go | package main
import (
"fmt"
)
func main() {
days := []string{"first", "second", "third", "fourth", "fifth", "sixth",
"seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"}
gifts := []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"}
for i := 0; i < 12; i++ {
fmt.Printf("On the %s day of Christmas,\n", days[i])
fmt.Println("My true love sent to me:")
for j := i; j >= 0; j-- {
fmt.Println(gifts[j])
}
fmt.Println()
}
}
|
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Lua | Lua | print("Normal \027[1mBold\027[0m \027[4mUnderline\027[0m \027[7mInverse\027[0m")
colors = { 30,31,32,33,34,35,36,37,90,91,92,93,94,95,96,97 }
for _,bg in ipairs(colors) do
for _,fg in ipairs(colors) do
io.write("\027["..fg..";"..(bg+10).."mX")
end
print("\027[0m") -- be nice, reset
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.
| #Aikido | Aikido |
monitor Queue {
var items = []
public function put (item) {
items.append (item)
notify()
}
public function get() {
while (items.size() == 0) {
wait()
}
var item = items[0]
items <<= 1
return item
}
public function close {
items.append (none)
}
}
thread reader (queue) {
var numlines = 0
for (;;) {
var line = queue.get()
if (typeof(line) == "none") {
break
}
print (line)
numlines++
}
println ("Number of lines: " + numlines)
}
thread writer (queue, lines) {
foreach line lines {
queue.put (line)
}
queue.close()
}
var queue = new Queue()
var lines = readfile ("input.txt")
var r = reader(queue)
var w = writer(queue, lines)
join (r)
join (w) |
http://rosettacode.org/wiki/Synchronous_concurrency | Synchronous concurrency | The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use the term threads, others use the term tasks, while others use co-processes. This task should not be implemented using fork, spawn, or the Linux/UNIX/Win32 pipe command, as communication should be between threads, not processes.
One of the concurrent units will read from a file named "input.txt" and send the contents of that file, one line at a time, to the other concurrent unit, which will print the line it receives to standard output. The printing unit must count the number of lines it prints. After the concurrent unit reading the file sends its last line to the printing unit, the reading unit will request the number of lines printed by the printing unit. The reading unit will then print the number of lines printed by the printing unit.
This task requires two-way communication between the concurrent units. All concurrent units must cleanly terminate at the end of the program.
| #ALGOL_68 | ALGOL 68 | (
STRING line;
INT count := 0, errno;
BOOL input complete := FALSE;
SEMA output throttle = LEVEL 0, input throttle = LEVEL 1;
FILE input txt;
errno := open(input txt, "input.txt", stand in channel);
PROC call back done = (REF FILE f) BOOL: ( input complete := TRUE );
on logical file end(input txt, call back done);
PAR (
WHILE
DOWN input throttle;
get(input txt,(line, new line));
UP output throttle;
NOT input complete
DO
count+:=1
OD
,
WHILE
DOWN output throttle;
NOT input complete
DO
print((line, new line));
UP input throttle
OD
);
print((count))
) |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #FunL | FunL | import db.*
import util.*
Class.forName( 'org.h2.Driver' )
conn = DriverManager.getConnection( 'jdbc:h2:mem:test', 'sa', '' )
statement = conn.createStatement()
statement.execute( '''
CREATE TABLE `user_data` (
`id` identity,
`name` varchar(255) NOT NULL,
`street` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`region` char(2) NOT NULL,
`country` char(2) NOT NULL,
`code` varchar(20) NOT NULL,
`phone` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
)''' )
statement.execute( '''
INSERT INTO `user_data` (`name`, `street`, `city`, `region`, `code`, `country`, `phone`) VALUES
('Jacinthe Steinert', '8540 Fallen Pony Villas', 'Searights', 'IA', '51584-4315', 'US', '(641) 883-4342'),
('Keeley Pinkham', '1363 Easy Downs', 'Mileta', 'TX', '77667-7376', 'US', '(469) 527-4784'),
('Rimon Cleveland', '8052 Blue Pond Dale', 'The Willows', 'UT', '84630-2674', 'US', '(385) 305-7261'),
('Berenice Benda', '2688 Merry Pines', 'Dacono', 'HI', '96766-7398', 'US', '(808) 451-2732'),
('Mehetabel Marcano', '109 Sleepy Goose Crescent', 'Plains', 'UT', '84727-7254', 'US', '(385) 733-8404'),
('Ambria Schiller', '7100 Tawny Robin Highway', 'Barlowes', 'ID', '83792-2043', 'US', '(208) 227-8887'),
('Carne Cancino', '3842 Broad Pioneer Cape', 'Bardstown', 'IA', '51571-6473', 'US', '(563) 060-8352'),
('Ince Leite', '7876 Stony Fawn Boulevard', 'Easton', 'ID', '83651-9235', 'US', '(208) 951-3024'),
('Britney Odell', '3386 Lazy Shadow Thicket', 'Kimberly', 'OK', '73539-6632', 'US', '(539) 848-4448'),
('Suprabha Penton', '9311 Dusty Leaf Alley', 'Niumalu', 'GA', '39927-8332', 'US', '(404) 589-0183')''' )
result = statement.executeQuery( '''SELECT * FROM user_data WHERE region = 'ID' ORDER BY code''' )
print( TextTable.apply(result) )
conn.close() |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Go | Go | package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/mattn/go-sqlite3"
)
func main() {
// task req: show database connection
db, err := sql.Open("sqlite3", "rc.db")
if err != nil {
log.Print(err)
return
}
defer db.Close()
// task req: create table with typed fields, including a unique id
_, err = db.Exec(`create table addr (
id int unique,
street text,
city text,
state text,
zip text
)`)
if err != nil {
log.Print(err)
return
}
// show output: query the created field names and types
rows, err := db.Query(`pragma table_info(addr)`)
if err != nil {
log.Print(err)
return
}
var field, storage string
var ignore sql.RawBytes
for rows.Next() {
err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)
if err != nil {
log.Print(err)
return
}
fmt.Println(field, storage)
}
} |
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.
| #BASIC | BASIC | IF LEN(COMMAND$) THEN
OPEN "notes.txt" FOR APPEND AS 1
PRINT #1, DATE$, TIME$
PRINT #1, CHR$(9); COMMAND$
CLOSE
ELSE
d$ = DIR$("notes.txt")
IF LEN(d$) THEN
OPEN d$ FOR INPUT AS 1
WHILE NOT EOF(1)
LINE INPUT #1, i$
PRINT i$
WEND
CLOSE
END IF
END IF |
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.
| #Batch_File | Batch File | @echo off
if %1@==@ (
if exist notes.txt more notes.txt
goto :eof
)
echo %date% %time%:>>notes.txt
echo %*>>notes.txt |
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).
| #EchoLisp | EchoLisp |
(require '(heap compile))
(define (scube a b) (+ (* a a a) (* b b b)))
(compile 'scube "-f") ; "-f" means : no bigint, no rational used
;; is n - a^3 a cube b^3?
;; if yes return b, else #f
(define (taxi? n a (b 0))
(set! b (cbrt (- n (* a a a)))) ;; cbrt is ∛
(when (and (< b a) (integer? b)) b))
(compile 'taxi? "-f")
#|-------------------
looking for taxis
--------------------|#
;; remove from heap until heap-top >= a
;; when twins are removed, it is a taxicab number : push it
;; at any time (top stack) = last removed
(define (clean-taxi H limit: a min-of-heap: htop)
(when (and htop (> a htop))
(when (!= (stack-top S) htop) (pop S))
(push S htop)
(heap-pop H)
(clean-taxi H a (heap-top H))))
(compile 'clean-taxi "-f")
;; loop on a and b, b <=a , until n taxicabs found
(define (taxicab (n 2100))
(for ((a (in-naturals)))
(clean-taxi H (* a a a) (heap-top H))
#:break (> (stack-length S) n)
(for ((b a))
(heap-push H (scube a b)))))
#|------------------
printing taxis
---------------------|#
;; string of all decompositions
(define (taxi->string i n)
(string-append (format "%d. %d " (1+ i) n)
(for/string ((a (cbrt n)))
#:when (taxi? n a)
(format " = %4d^3 + %4d^3" a (taxi? n a)))))
(define (taxi-print taxis (nfrom 0) (nto 26))
(for ((i (in-naturals nfrom)) (taxi (sublist taxis nfrom nto)))
(writeln (taxi->string i (first taxi)))))
|
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.
| #11l | 11l | -V MAX = 12
[Char] sp
V count = [0] * MAX
V pos = 0
F factSum(n)
V s = 0
V x = 0
V f = 1
L x < n
f *= ++x
s += f
R s
F r(n)
I n == 0
R 0B
V c = :sp[:pos - n]
I --:count[n] == 0
:count[n] = n
I !r(n - 1)
R 0B
:sp[:pos++] = c
R 1B
F superPerm(n)
:pos = n
V len = factSum(n)
I len > 0
:sp = [Char("\0")] * len
L(i) 0 .. n
:count[i] = i
L(i) 1 .. n
:sp[i - 1] = Char(code' ‘0’.code + i)
L r(n) {}
L(n) 0 .< MAX
superPerm(n)
print(‘superPerm(#2) len = #.’.format(n, sp.len)) |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Haskell | Haskell | tau :: Integral a => a -> a
tau n | n <= 0 = error "Not a positive integer"
tau n = go 0 (1, 1)
where
yo i = (i, i * i)
go r (i, ii)
| n < ii = r
| n == ii = r + 1
| 0 == mod n i = go (r + 2) (yo $ i + 1)
| otherwise = go r (yo $ i + 1)
isTau :: Integral a => a -> Bool
isTau n = 0 == mod n (tau n)
main = print . take 100 . filter isTau $ [1..] |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #J | J |
tau_number=: 0 = (|~ tally_factors@>)
tally_factors=: [: */ 1 + _&q:
|
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #Python | Python | from collections import defaultdict
def from_edges(edges):
'''translate list of edges to list of nodes'''
class Node:
def __init__(self):
# root is one of:
# None: not yet visited
# -1: already processed
# non-negative integer: what Wikipedia pseudo code calls 'lowlink'
self.root = None
self.succ = []
nodes = defaultdict(Node)
for v,w in edges:
nodes[v].succ.append(nodes[w])
for i,v in nodes.items(): # name the nodes for final output
v.id = i
return nodes.values()
def trajan(V):
def strongconnect(v, S):
v.root = pos = len(S)
S.append(v)
for w in v.succ:
if w.root is None: # not yet visited
yield from strongconnect(w, S)
if w.root >= 0: # still on stack
v.root = min(v.root, w.root)
if v.root == pos: # v is the root, return everything above
res, S[pos:] = S[pos:], []
for w in res:
w.root = -1
yield [r.id for r in res]
for v in V:
if v.root is None:
yield from strongconnect(v, [])
tables = [ # table 1
[(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2),
(4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)],
# table 2
[('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]]
for table in (tables):
for g in trajan(from_edges(table)):
print(g)
print() |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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 strict;
use warnings;
use feature 'say';
use List::Util qw(uniqstr any);
my(%words,@teacups,%seen);
open my $fh, '<', 'ref/wordlist.10000';
while (<$fh>) {
chomp(my $w = uc $_);
next if length $w < 3;
push @{$words{join '', sort split //, $w}}, $w;}
for my $these (values %words) {
next if @$these < 3;
MAYBE: for (@$these) {
my $maybe = $_;
next if $seen{$_};
my @print;
for my $i (0 .. length $maybe) {
if (any { $maybe eq $_ } @$these) {
push @print, $maybe;
$maybe = substr($maybe,1) . substr($maybe,0,1)
} else {
@print = () and next MAYBE
}
}
if (@print) {
push @teacups, [@print];
$seen{$_}++ for @print;
}
}
}
say join ', ', uniqstr @$_ for sort @teacups; |
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
| #AppleScript | AppleScript | use framework "Foundation" -- Yosemite onwards, for the toLowerCase() function
-- KELVIN TO OTHER SCALE -----------------------------------------------------
-- kelvinAs :: ScaleName -> Num -> Num
on kelvinAs(strOtherScale, n)
heatBabel(n, "Kelvin", strOtherScale)
end kelvinAs
-- MORE GENERAL CONVERSION ---------------------------------------------------
-- heatBabel :: n -> ScaleName -> ScaleName -> Num
on heatBabel(n, strFromScale, strToScale)
set ratio to 9 / 5
set cels to 273.15
set fahr to 459.67
script reading
on |λ|(x, strFrom)
if strFrom = "k" then
x as real
else if strFrom = "c" then
x + cels
else if strFrom = "f" then
(fahr + x) * ratio
else
x / ratio
end if
end |λ|
end script
script writing
on |λ|(x, strTo)
if strTo = "k" then
x
else if strTo = "c" then
x - cels
else if strTo = "f" then
(x * ratio) - fahr
else
x * ratio
end if
end |λ|
end script
writing's |λ|(reading's |λ|(n, ¬
toLower(text 1 of strFromScale)), ¬
toLower(text 1 of strToScale))
end heatBabel
-- TEST ----------------------------------------------------------------------
on kelvinTranslations(n)
script translations
on |λ|(x)
{x, kelvinAs(x, n)}
end |λ|
end script
map(translations, {"K", "C", "F", "R"})
end kelvinTranslations
on run
script tabbed
on |λ|(x)
intercalate(tab, x)
end |λ|
end script
intercalate(linefeed, map(tabbed, kelvinTranslations(21)))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- toLower :: String -> String
on toLower(str)
set ca to current application
((ca's NSString's stringWithString:(str))'s ¬
lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text
end toLower |
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
| #Cowgol | Cowgol | include "cowgol.coh";
typedef N is uint8;
sub tau(n: N): (total: N) is
total := 1;
while n & 1 == 0 loop
total := total + 1;
n := n >> 1;
end loop;
var p: N := 3;
while p*p <= n loop
var count: N := 1;
while n%p == 0 loop
count := count + 1;
n := n / p;
end loop;
total := total * count;
p := p + 2;
end loop;
if n>1 then
total := total << 1;
end if;
end sub;
sub print2(n: uint8) is
print_char(' ');
if n<10
then print_char(' ');
else print_i8(n/10);
end if;
print_i8(n%10);
end sub;
var n: N := 1;
while n <= 100 loop
print2(tau(n));
if n % 20 == 0 then print_nl(); end if;
n := n + 1;
end loop; |
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
| #D | D | import std.stdio;
// See https://en.wikipedia.org/wiki/Divisor_function
uint divisor_count(uint n) {
uint total = 1;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1) {
++total;
}
// Odd prime factors up to the square root
for (uint p = 3; p * p <= n; p += 2) {
uint count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
// If n > 1 then it's prime
if (n > 1) {
total *= 2;
}
return total;
}
void main() {
immutable limit = 100;
writeln("Count of divisors for the first ", limit, " positive integers:");
for (uint n = 1; n <= limit; ++n) {
writef("%3d", divisor_count(n));
if (n % 20 == 0) {
writeln;
}
}
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Fortran | Fortran | program clear
character(len=:), allocatable :: clear_command
clear_command = "clear" !"cls" on Windows, "clear" on Linux and alike
call execute_command_line(clear_command)
end program |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' FreeBASIC has a built in Cls command which clears the console on Windows
' but it may still be possible to scroll the console to view its
' previous contents. The following command prevents this.
Shell("Cls")
Sleep |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Furor | Furor |
cls
|
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
| #J | J | not=: -.
and=: <.
or =: >.
if =: (>. -.)"0~
eq =: (<.&-. >. <.)"0 |
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.
| #Lua | Lua | filename = "readings.txt"
io.input( filename )
file_sum, file_cnt_data, file_lines = 0, 0, 0
max_rejected, n_rejected = 0, 0
max_rejected_date, rejected_date = "", ""
while true do
data = io.read("*line")
if data == nil then break end
date = string.match( data, "%d+%-%d+%-%d+" )
if date == nil then break end
val = {}
for w in string.gmatch( data, "%s%-*%d+[%.%d]*" ) do
val[#val+1] = tonumber(w)
end
sum, cnt = 0, 0
for i = 1, #val, 2 do
if val[i+1] > 0 then
sum = sum + val[i]
cnt = cnt + 1
n_rejected = 0
else
if n_rejected == 0 then
rejected_date = date
end
n_rejected = n_rejected + 1
if n_rejected > max_rejected then
max_rejected = n_rejected
max_rejected_date = rejected_date
end
end
end
file_sum = file_sum + sum
file_cnt_data = file_cnt_data + cnt
file_lines = file_lines + 1
print( string.format( "%s:\tRejected: %d\tAccepted: %d\tLine_total: %f\tLine_average: %f", date, #val/2-cnt, cnt, sum, sum/cnt ) )
end
print( string.format( "\nFile:\t %s", filename ) )
print( string.format( "Total:\t %f", file_sum ) )
print( string.format( "Readings: %d", file_lines ) )
print( string.format( "Average: %f", file_sum/file_cnt_data ) )
print( string.format( "Maximum %d consecutive false readings starting at %s.", max_rejected, max_rejected_date ) ) |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #UNIX_Shell | UNIX Shell | #!/bin/bash
is_palindrome() {
local s1=$1
local s2=$(echo $1 | tr -d "[ ,!:;.'\"]" | tr '[A-Z]' '[a-z]')
if [[ $s2 = $(echo $s2 | rev) ]]
then
echo "[$s1] is a palindrome"
else
echo "[$s1] is NOT a palindrome"
fi
}
|
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #VBA | VBA |
Option Explicit
Sub Test_a_function()
Dim a, i&
a = Array("abba", "mom", "dennis sinned", "Un roc lamina l animal cornu", "palindrome", "ba _ ab", "racecars", "racecar", "wombat", "in girum imus nocte et consumimur igni")
For i = 0 To UBound(a)
Debug.Print a(i) & " is a palidrome ? " & IsPalindrome(CStr(a(i)))
Next
End Sub
Function IsPalindrome(txt As String) As Boolean
Dim tempTxt As String
tempTxt = LCase(Replace(txt, " ", ""))
IsPalindrome = (tempTxt = StrReverse(tempTxt))
End Function
|
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
| #Groovy | Groovy | def presents = ['A partridge in a pear tree.', 'Two turtle doves', 'Three french hens', 'Four calling birds',
'Five golden rings', 'Six geese a-laying', 'Seven swans a-swimming', 'Eight maids a-milking',
'Nine ladies dancing', 'Ten lords a-leaping', 'Eleven pipers piping', 'Twelve drummers drumming']
['first', 'second', 'third', 'forth', 'fifth', 'sixth', 'seventh', 'eight', 'ninth', 'tenth', 'eleventh', 'Twelfth'].eachWithIndex{ day, dayIndex ->
println "On the $day day of Christmas"
println 'My true love gave to me:'
(dayIndex..0).each { p ->
print presents[p]
println p == 1 ? ' and' : ''
}
println()
} |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Run["tput setaf 1"]; Print["Coloured Text"];
Run["tput setaf 2"]; Print["Coloured Text"];
Run["tput setaf 3"]; Print["Coloured Text"] |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Nim | Nim | import Terminal
setForegroundColor(fgRed)
echo "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic"
setBackgroundColor(bgBlue)
setForegroundColor(fgYellow)
stdout.write "This is an "
writeStyled "important"
stdout.write " word"
resetAttributes()
stdout.write "\n"
setForegroundColor(fgYellow)
echo "RosettaCode!"
setForegroundColor(fgCyan)
echo "RosettaCode!"
setForegroundColor(fgGreen)
echo "RosettaCode!"
setForegroundColor(fgMagenta)
echo "RosettaCode!" |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #OCaml | OCaml | $ ocaml unix.cma -I +ANSITerminal ANSITerminal.cma
# open ANSITerminal ;;
# print_string [cyan; on_blue] "Hello\n" ;;
Hello
- : unit = () |
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.
| #BCPL | BCPL | // This is a BCPL implementation of the Rosettacode synchronous
// concurrency test using BCPL coroutines and a coroutine implementation
// of a Occum-style channels.
// BCPL is freely available from www.cl.cam.ac.uk/users/mr10
SECTION "coinout"
GET "libhdr.h"
GLOBAL {
tracing: ug
}
LET start() = VALOF
{ LET argv = VEC 50
LET in_co, out_co = 0, 0
LET channel = 0
LET filename = "input.txt"
UNLESS rdargs("-f,-t/S", argv, 50) DO
{ writef("Bad arguments for coinout*n")
RESULTIS 0
}
IF argv!0 DO filename := argv!0 // -f the source file
tracing := argv!1 // -t/S tracing option
in_co := initco(infn, 500, @channel)
out_co := initco(outfn, 500, @channel)
UNLESS in_co & out_co DO
{ writef("Trouble creating the coroutines*n")
GOTO fin
}
IF tracing DO writef("*nBoth in and out coroutines created*n*n")
callco(in_co, filename)
fin:
IF in_co DO deleteco(in_co)
IF out_co DO deleteco(out_co)
IF tracing DO writef("Both in and out coroutines deleted*n*n")
RESULTIS 0
}
AND readline(line) = VALOF
{ LET ch, i = 0, 0
line%0 := 0
{ ch := rdch()
IF ch=endstreamch RESULTIS FALSE
i := i+1
line%0, line%i := i, ch
IF ch='*n' | i=255 BREAK
} REPEAT
RESULTIS TRUE
}
AND infn(args) BE
{ LET channelptr = args!0
LET name = cowait() // Get the file name
LET instream = findinput(name)
LET line = VEC 256/bytesperword
UNLESS instream DO
{ writef("*nTrouble with file: %s*n", name)
RETURN
}
selectinput(instream)
{ LET ok = readline(line)
UNLESS ok BREAK
IF tracing DO
writef("inco: Sending a line to outco*n")
cowrite(channelptr, line)
} REPEAT
IF tracing DO
writef("inco: Sending zero to outco*n")
writef("*nNumber of lines written was %n*n", cowrite(channelptr, 0))
endstream(instream)
}
AND outfn(args) BE
{ LET channelptr = args!0
LET linecount = 0
{ LET line = coread(channelptr)
UNLESS line BREAK
IF tracing DO writef("outfn: Received a line*n")
writes(line)
linecount := linecount + 1
} REPEAT
IF tracing DO
writef("outfn: Received zero, so sent count=%n back to inco*n",
linecount)
cowait(linecount)
}
// The following functions are a implementation of Occum-style channels
// using coroutines.
// The first coroutine to request a transfer through a channel becomes
// suspended and the second causes the data to be transfers and then allows
// both coroutines to resume (in some order). The channel word is either
// zero or points to a suspended (read or write) cocoutine.
// The use of resumeco in coread is somewhat subtle!
AND coread(ptr) = VALOF
{ LET cptr = !ptr
TEST cptr
THEN { !ptr := 0 // Clear the channel word
RESULTIS resumeco(cptr, currco)
}
ELSE { !ptr := currco // Set channel word to this coroutine
RESULTIS cowait() // Wait for value from cowrite
}
}
AND cowrite(ptr, val) BE
{ LET cptr = !ptr
TEST cptr
THEN { !ptr := 0
callco(cptr, val) // Send val to coread
}
ELSE { !ptr := currco
callco(cowait(), val)
}
}
|
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.
| #C | C | #include <stdlib.h> /* malloc(), realloc(), free() */
#include <stdio.h> /* fopen(), fgetc(), fwrite(), printf() */
#include <libco.h> /* co_create(), co_switch() */
void
fail(const char *message) {
perror(message);
exit(1);
}
/*
* These are global variables of this process. All cothreads of this
* process will share these global variables.
*/
cothread_t reader;
cothread_t printer;
struct {
char *buf; /* Not a C string. No terminating '\0'. */
size_t len; /* Length of line in buffer. */
size_t cap; /* Maximum capacity of buffer. */
} line;
size_t count; /* Number of lines printed. */
/*
* The reader cothread reads every line of an input file, passes each
* line to the printer cothread, and reports the number of lines.
*/
void
reader_entry(void)
{
FILE *input;
size_t newcap;
int c, eof, eol;
char *newbuf;
input = fopen("input.txt", "r");
if (input == NULL)
fail("fopen");
line.buf = malloc(line.cap = 4096); /* New buffer. */
if (line.buf == NULL)
fail("malloc");
line.len = 0; /* Start with an empty line. */
do {
c = fgetc(input); /* Read next character. */
if (ferror(input))
fail("fgetc");
eof = (c == EOF);
if (eof) {
/*
* End of file is also end of line,
` * unless the line would be empty.
*/
eol = (line.len > 0);
} else {
/* Append c to the buffer. */
if (line.len == line.cap) {
/* Need a bigger buffer! */
newcap = line.cap * 2;
newbuf = realloc(line.buf, newcap);
if (newbuf == NULL)
fail("realloc");
line.buf = newbuf;
line.cap = newcap;
}
line.buf[line.len++] = c;
/* '\n' is end of line. */
eol = (c == '\n');
}
if (eol) {
/* Pass our complete line to the printer. */
co_switch(printer);
line.len = 0; /* Destroy our line. */
}
} while (!eof);
free(line.buf);
line.buf = NULL; /* Stops a loop in the printer. */
printf("Printed %zu lines.\n", count);
co_switch(printer);
}
/*
* The printer cothread starts the reader cothread, prints every line
* line from the reader cothread, and counts the number of lines.
*/
int
main()
{
reader = co_create(4096, reader_entry);
printer = co_active();
count = 0;
for (;;) {
co_switch(reader);
if (line.buf == NULL)
break;
/* Print this line. Count it. */
fwrite(line.buf, 1, line.len, stdout);
count++;
}
co_delete(reader);
return 0;
} |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Haskell | Haskell | {-# LANGUAGE OverloadedStrings #-}
import Database.SQLite.Simple
main = do
db <- open "postal.db"
execute_ db "\
\CREATE TABLE address (\
\addrID INTEGER PRIMARY KEY AUTOINCREMENT, \
\addrStreet TEXT NOT NULL, \
\addrCity TEXT NOT NULL, \
\addrState TEXT NOT NULL, \
\addrZIP TEXT NOT NULL \
\)"
close db |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #J | J | Create__hd 'Address';noun define
addrID autoid;
addrStreet varchar
addrCity varchar
addrState char
addrZip char
) |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Julia | Julia | using SQLite
db = SQLite.DB()
SQLite.execute!(db, """\
CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL)
""") |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Kotlin | Kotlin | // Version 1.2.41
import java.io.File
import java.io.RandomAccessFile
fun String.toFixedLength(len: Int) = this.padEnd(len).substring(0, len)
class Address(
var name: String,
var street: String = "",
var city: String = "",
var state: String = "",
var zipCode: String = "",
val autoId: Boolean = true
) {
var id = 0L
private set
init {
if (autoId) id = ++nextId
}
companion object {
private var nextId = 0L
const val RECORD_LENGTH = 127 // including 2 bytes for UTF string length
fun readRecord(file: File, id: Long): Address {
val raf = RandomAccessFile(file, "r")
val seekPoint = (id - 1) * RECORD_LENGTH
raf.use {
it.seek(seekPoint)
val id2 = it.readLong()
if (id != id2) {
println("Database is corrupt")
System.exit(1)
}
val text = it.readUTF()
val name = text.substring(0, 30).trimEnd()
val street = text.substring(30, 80).trimEnd()
val city = text.substring(80, 105).trimEnd()
val state = text.substring(105, 107)
val zipCode = text.substring(107).trimEnd()
val a = Address(name, street, city, state, zipCode, false)
a.id = id
return a
}
}
}
override fun toString() =
"Id : ${this.id}\n" +
"Name : $name\n" +
"Street : $street\n" +
"City : $city\n" +
"State : $state\n" +
"Zip Code : $zipCode\n"
fun writeRecord(file: File) {
val raf = RandomAccessFile(file, "rw")
val text =
name.toFixedLength(30) +
street.toFixedLength(50) +
city.toFixedLength(25) +
state +
zipCode.toFixedLength(10)
val seekPoint = (id - 1) * RECORD_LENGTH
raf.use {
it.seek(seekPoint)
it.writeLong(id)
it.writeUTF(text)
}
}
}
fun main(args: Array<String>) {
val file = File("addresses.dat")
val addresses = listOf(
Address("FSF Inc.", "51 Franklin Street", "Boston", "MA", "02110-1301"),
Address("The White House", "The Oval Office, 1600 Pennsylvania Avenue NW", "Washington", "DC", "20500")
)
// write the address records to the file
addresses.forEach { it.writeRecord(file) }
// now read them back in reverse order and print them out
for (i in 2 downTo 1) {
println(Address.readRecord(file, i.toLong()))
}
} |
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.
| #BBC_BASIC | BBC BASIC | REM!Exefile C:\NOTES.EXE, encrypt, console
REM!Embed
LF = 10
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
SYS "SetConsoleMode", @hfile%(1), 0
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
notes% = OPENUP(@dir$ + "NOTES.TXT")
IF notes% = 0 notes% = OPENOUT(@dir$ + "NOTES.TXT")
IF notes% = 0 PRINT "Cannot open or create NOTES.TXT" : QUIT 1
IF @cmd$ = "" THEN
WHILE NOT EOF#notes%
INPUT #notes%, text$
IF ASC(text$) = LF text$ = MID$(text$,2)
PRINT text$
ENDWHILE
ELSE
PTR#notes% = EXT#notes%
PRINT #notes%,TIME$ : BPUT#notes%,LF
PRINT #notes%,CHR$(9) + @cmd$ : BPUT#notes%,LF
ENDIF
CLOSE #notes%
QUIT |
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.
| #C | C | #include <stdio.h>
#include <time.h>
#define note_file "NOTES.TXT"
int main(int argc, char**argv)
{
FILE *note = 0;
time_t tm;
int i;
char *p;
if (argc < 2) {
if ((note = fopen(note_file, "r")))
while ((i = fgetc(note)) != EOF)
putchar(i);
} else if ((note = fopen(note_file, "a"))) {
tm = time(0);
p = ctime(&tm);
/* skip the newline */
while (*p) fputc(*p != '\n'?*p:'\t', note), p++;
for (i = 1; i < argc; i++)
fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
}
if (note) fclose(note);
return 0;
} |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #Elixir | Elixir | defmodule Taxicab do
def numbers(n \\ 1200) do
(for i <- 1..n, j <- i..n, do: {i,j})
|> Enum.group_by(fn {i,j} -> i*i*i + j*j*j end)
|> Enum.filter(fn {_,v} -> length(v)>1 end)
|> Enum.sort
end
end
nums = Taxicab.numbers |> Enum.with_index
Enum.each(nums, fn {x,i} ->
if i in 0..24 or i in 1999..2005 do
IO.puts "#{i+1} : #{inspect x}"
end
end) |
http://rosettacode.org/wiki/Taxicab_numbers | Taxicab numbers |
A taxicab number (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
The first taxicab number is 1729, which is:
13 + 123 and also
93 + 103.
Taxicab numbers are also known as:
taxi numbers
taxi-cab numbers
taxi cab numbers
Hardy-Ramanujan numbers
Task
Compute and display the lowest 25 taxicab numbers (in numeric order, and in a human-readable format).
For each of the taxicab numbers, show the number as well as it's constituent cubes.
Extra credit
Show the 2,000th taxicab number, and a half dozen more
See also
A001235: taxicab numbers on The On-Line Encyclopedia of Integer Sequences.
Hardy-Ramanujan Number on MathWorld.
taxicab number on MathWorld.
taxicab number on Wikipedia (includes the story on how taxi-cab numbers came to be called).
| #Forth | Forth | variable taxicablist
variable searched-cubessum
73 constant max-constituent \ uses magic numbers
: cube dup dup * * ;
: cubessum cube swap cube + ;
: ?taxicab ( a b -- c d true | false )
\ does exist an (c, d) such that c^3+d^3 = a^3+b^3 ?
2dup cubessum searched-cubessum !
dup 1- rot 1+ do \ c is possibly in [a+1 b-2]
dup i 1+ do \ d is possibly in [c+1 b-1]
j i cubessum searched-cubessum @ = if drop j i true unloop unloop exit then
loop
loop drop false ;
: swap-taxi ( n -- )
dup 5 cells + swap do
i @ i 5 cells - @ i ! i 5 cells - !
cell +loop ;
: bubble-taxicablist
here 5 cells - taxicablist @ = if exit then \ not for the first one
taxicablist @ here 5 cells - do
i @ i 5 cells - @ > if unloop exit then \ no (more) need to reorder
i swap-taxi
5 cells -loop ;
: store-taxicab ( a b c d -- )
2dup cubessum , swap , , swap , ,
bubble-taxicablist ;
: build-taxicablist
here taxicablist !
max-constituent 3 - 1 do \ a in [ 1 ; max-3 ]
i 3 + max-constituent swap do \ b in [ a+3 ; max ]
j i ?taxicab if j i store-taxicab then
loop
loop ;
: .nextcube cell + dup @ . ." ^3 " ;
: .taxi
dup @ .
." = " .nextcube ." + " .nextcube ." = " .nextcube ." + " .nextcube
drop ;
: taxicab 5 cells * taxicablist @ + ;
: list-taxicabs ( n -- )
0 do
cr I 1+ . ." : "
I taxicab .taxi
loop ;
build-taxicablist
25 list-taxicabs |
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.
| #AWK | AWK |
# syntax: GAWK -f SUPERPERMUTATION_MINIMISATION.AWK
# converted from C
BEGIN {
arr[0] # prevents fatal: attempt to use scalar 'arr' as an array
limit = 11
for (n=0; n<=limit; n++) {
leng = super_perm(n)
printf("%2d %d ",n,leng)
# for (i=0; i<length(arr); i++) { printf(arr[i]) } # un-comment to see the string
printf("\n")
}
exit(0)
}
function fact_sum(n, f,s,x) {
f = 1
s = x = 0
for (;x<n;) {
f *= ++x
s += f
}
return(s)
}
function super_perm(n, i,leng) {
delete arr
pos = n
leng = fact_sum(n)
for (i=0; i<leng; i++) {
arr[i] = ""
}
for (i=0; i<=n; i++) {
cnt[i] = i
}
for (i=1; i<=n; i++) {
arr[i-1] = i + "0"
}
while (r(n)) { }
return(leng)
}
function r(n, c) {
if (!n) { return(0) }
c = arr[pos-n]
if (!--cnt[n]) {
cnt[n] = n
if (!r(n-1)) { return(0) }
}
arr[pos++] = c
return(1)
}
|
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Java | Java | public class Tau {
private static long divisorCount(long n) {
long total = 1;
// Deal with powers of 2 first
for (; (n & 1) == 0; n >>= 1) {
++total;
}
// Odd prime factors up to the square root
for (long p = 3; p * p <= n; p += 2) {
long count = 1;
for (; n % p == 0; n /= p) {
++count;
}
total *= count;
}
// If n > 1 then it's prime
if (n > 1) {
total *= 2;
}
return total;
}
public static void main(String[] args) {
final long limit = 100;
System.out.printf("The first %d tau numbers are:%n", limit);
long count = 0;
for (long n = 1; count < limit; ++n) {
if (n % divisorCount(n) == 0) {
System.out.printf("%6d", n);
++count;
if (count % 10 == 0) {
System.out.println();
}
}
}
}
} |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #Racket | Racket | #lang racket
(require syntax/parse/define
fancy-app
(for-syntax racket/syntax))
(struct node (name index low-link on?) #:transparent #:mutable
#:methods gen:custom-write
[(define (write-proc v port mode) (fprintf port "~a" (node-name v)))])
(define-syntax-parser change!
[(_ x:id f) #'(set! x (f x))]
[(_ accessor:id v f)
#:with mutator! (format-id this-syntax "set-~a!" #'accessor)
#'(mutator! v (f (accessor v)))])
(define (tarjan g)
(define sccs '())
(define index 0)
(define s '())
(define (dfs v)
(set-node-index! v index)
(set-node-low-link! v index)
(set-node-on?! v #t)
(change! s (cons v _))
(change! index add1)
(for ([w (in-list (hash-ref g v '()))])
(match-define (node _ index low-link on?) w)
(cond
[(not index) (dfs w)
(change! node-low-link v (min (node-low-link w) _))]
[on? (change! node-low-link v (min index _))]))
(when (= (node-low-link v) (node-index v))
(define-values (scc* s*) (splitf-at s (λ (w) (not (eq? w v)))))
(set! s (rest s*))
(define scc (cons (first s*) scc*))
(for ([w (in-list scc)]) (set-node-on?! w #f))
(change! sccs (cons scc _))))
(for* ([(u _) (in-hash g)] #:when (not (node-index u))) (dfs u))
sccs)
(define (make-graph xs)
(define store (make-hash))
(define (make-node v) (hash-ref! store v (thunk (node v #f #f #f))))
;; it's important that we use hasheq instead of hash so that we compare
;; reference instead of actual value. Had we use the actual value,
;; the key would be a mutable value, which causes undefined behavior
(for/hasheq ([vs (in-list xs)]) (values (make-node (first vs)) (map make-node (rest vs)))))
(tarjan (make-graph '([0 1]
[2 0]
[5 2 6]
[6 5]
[1 2]
[3 1 2 4]
[4 5 3]
[7 4 7 6]))) |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #Raku | Raku | sub tarjan (%k) {
my %onstack;
my %index;
my %lowlink;
my @stack;
my @connected;
sub strong-connect ($vertex) {
state $index = 0;
%index{$vertex} = $index;
%lowlink{$vertex} = $index++;
%onstack{$vertex} = True;
@stack.push: $vertex;
for |%k{$vertex} -> $connection {
if not %index{$connection}.defined {
strong-connect($connection);
%lowlink{$vertex} min= %lowlink{$connection};
}
elsif %onstack{$connection} {
%lowlink{$vertex} min= %index{$connection};
}
}
if %lowlink{$vertex} eq %index{$vertex} {
my @node;
repeat {
@node.push: @stack.pop;
%onstack{@node.tail} = False;
} while @node.tail ne $vertex;
@connected.push: @node;
}
}
.&strong-connect unless %index{$_} for %k.keys;
@connected
}
# TESTING
-> $test { say "\nStrongly connected components: ", |tarjan($test).sort».sort } for
# hash of vertex, edge list pairs
(((1),(2),(0),(1,2,4),(3,5),(2,6),(5),(4,6,7)).pairs.hash),
# Same layout test data with named vertices instead of numbered.
%(:Andy<Bart>,
:Bart<Carl>,
:Carl<Andy>,
:Dave<Bart Carl Earl>,
:Earl<Dave Fred>,
:Fred<Carl Gary>,
:Gary<Fred>,
:Hank<Earl Gary Hank>
) |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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 | procedure filter_set(sequence anagrams)
-- anagrams is a (small) set of words that are all anagrams of each other
-- for example: {"angel","angle","galen","glean","lange"}
-- print any set(s) for which every rotation is also present (marking as
-- you go to prevent the same set appearing with each word being first)
sequence used = repeat(false,length(anagrams))
for i=1 to length(anagrams) do
if not used[i] then
used[i] = true
string word = anagrams[i]
sequence res = {word}
for r=2 to length(word) do
word = word[2..$]&word[1]
integer k = find(word,anagrams)
if k=0 then res = {} exit end if
if not find(word,res) then
res = append(res,word)
end if
used[k] = true
end for
if length(res) then ?res end if
end if
end for
end procedure
procedure teacup(string filename, integer minlen=3, bool allow_mono=false)
sequence letters, -- a sorted word, eg "ate" -> "aet".
words = {}, -- in eg {{"aet","ate"},...} form
anagrams = {}, -- a set with same letters
last = "" -- (for building such sets)
object word
printf(1,"using %s",filename)
integer fn = open(filename,"r")
if fn=-1 then crash(filename&" not found") end if
while 1 do
word = lower(trim(gets(fn)))
if atom(word) then exit end if
if length(word)>=minlen then
letters = sort(word)
words = append(words, {letters, word})
end if
end while
close(fn)
printf(1,", %d words read\n",length(words))
if length(words)!=0 then
words = sort(words) -- group by anagram
for i=1 to length(words) do
{letters,word} = words[i]
if letters=last then
anagrams = append(anagrams,word)
else
if allow_mono or length(anagrams)>=length(last) then
filter_set(anagrams)
end if
last = letters
anagrams = {word}
end if
end for
if allow_mono or length(anagrams)>=length(last) then
filter_set(anagrams)
end if
end if
end procedure
teacup(join_path({"demo","unixdict.txt"}))
-- These match output from other entries:
--teacup(join_path({"demo","unixdict.txt"}),allow_mono:=true)
--teacup(join_path({"demo","rosetta","mit.wordlist.10000.txt"}))
--teacup(join_path({"demo","rosetta","words.txt"}),4,true)
-- Note that allow_mono is needed to display eg {"agag","gaga"}
|
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
| #Arturo | Arturo | convertKelvins: function [k][
#[
celcius: k - 273.15
fahrenheit: (k * 9/5.0)-459.67
rankine: k * 9/5.0
]
]
print convertKelvins 100 |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #Delphi | Delphi |
program Tau_function;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function CountDivisors(n: Integer): Integer;
begin
Result := 0;
var i := 1;
var k := 2;
if (n mod 2) = 0 then
k := 1;
while i * i <= n do
begin
if (n mod i) = 0 then
begin
inc(Result);
var j := n div i;
if j <> i then
inc(Result);
end;
inc(i, k);
end;
end;
begin
writeln('The tau functions for the first 100 positive integers are:');
for var i := 1 to 100 do
begin
write(CountDivisors(i): 2, ' ');
if (i mod 20) = 0 then
writeln;
end;
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
| #Draco | Draco | proc nonrec tau(word n) word:
word count, total, p;
total := 1;
while n & 1 = 0 do
total := total + 1;
n := n >> 1
od;
p := 3;
while p*p <= n do
count := 1;
while n % p = 0 do
count := count + 1;
n := n / p
od;
total := total * count;
p := p + 2
od;
if n>1
then total << 1
else total
fi
corp
proc nonrec main() void:
byte n;
for n from 1 upto 100 do
write(tau(n):3);
if n%20=0 then writeln() fi
od
corp |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Go | Go | package main
import (
"os"
"os/exec"
)
func main() {
c := exec.Command("clear")
c.Stdout = os.Stdout
c.Run()
} |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #GUISS | GUISS | Window:Terminal,Type:clear[enter] |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Haskell | Haskell |
import System.Console.ANSI
main = clearScreen
|
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
| #Java | Java | public class Logic{
public static enum Trit{
TRUE, MAYBE, FALSE;
public Trit and(Trit other){
if(this == TRUE){
return other;
}else if(this == MAYBE){
return (other == FALSE) ? FALSE : MAYBE;
}else{
return FALSE;
}
}
public Trit or(Trit other){
if(this == TRUE){
return TRUE;
}else if(this == MAYBE){
return (other == TRUE) ? TRUE : MAYBE;
}else{
return other;
}
}
public Trit tIf(Trit other){
if(this == TRUE){
return other;
}else if(this == MAYBE){
return (other == TRUE) ? TRUE : MAYBE;
}else{
return TRUE;
}
}
public Trit not(){
if(this == TRUE){
return FALSE;
}else if(this == MAYBE){
return MAYBE;
}else{
return TRUE;
}
}
public Trit equals(Trit other){
if(this == TRUE){
return other;
}else if(this == MAYBE){
return MAYBE;
}else{
return other.not();
}
}
}
public static void main(String[] args){
for(Trit a:Trit.values()){
System.out.println("not " + a + ": " + a.not());
}
for(Trit a:Trit.values()){
for(Trit b:Trit.values()){
System.out.println(a+" and "+b+": "+a.and(b)+
"\t "+a+" or "+b+": "+a.or(b)+
"\t "+a+" implies "+b+": "+a.tIf(b)+
"\t "+a+" = "+b+": "+a.equals(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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FileName = "Readings.txt"; data = Import[FileName,"TSV"];
Scan[(a=Position[#[[3;;All;;2]],1];
Print["Line:",#[[1]] ,"\tReject:", 24 - Length[a], "\t Accept:", Length[a], "\tLine_tot:",
Total@Part[#, Flatten[2*a]] , "\tLine_avg:", Total@Part[#, Flatten[2*a]]/Length[a]])&, data]
GlobalSum = Nb = Running = MaxRunRecorded = 0; MaxRunTime = {};
Scan[ For[i = 3, i < 50, i = i + 2,
If[#[[i]] == 1,
Running=0; GlobalSum += #[[i-1]]; Nb++;,
Running ++; If[MaxRunRecorded < Running, MaxRunRecorded = Running;MaxRunTime={ #[[1]]}; ];
]] &, data ]
Print["\nFile(s) : ",FileName,"\nTotal : ",AccountingForm@GlobalSum,"\nReadings : ",Nb,
"\nAverage : ",GlobalSum/Nb,"\n\nMaximum run(s) of ",MaxRunRecorded,
" consecutive false readings ends at line starting with date(s):",MaxRunTime] |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #Wren | Wren | import "/module" for Expect, Suite, ConsoleReporter
var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }
var words = ["rotor", "rosetta", "step on no pets", "été", "wren", "🦊😀🦊"]
var expected = [true, false, true, true, false, true]
var TestPal = Suite.new("Pal") { |it|
it.suite("'isPal' function:") { |it|
for (i in 0...words.count) {
it.should("return '%(expected[i])' for '%(words[i])' is palindrome") {
Expect.call(isPal.call(words[i])).toEqual(expected[i])
}
}
}
}
var reporter = ConsoleReporter.new()
TestPal.run(reporter)
reporter.epilogue() |
http://rosettacode.org/wiki/Test_a_function | Test a function |
Task
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome.
If your language does not have a testing specific library well known to the language's community then state this or omit the language.
| #zkl | zkl | fcn pali(text){
if (text.len()<2) return(False);
text==text.reverse();
} |
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
| #Haskell | Haskell | gifts :: [String]
gifts =
[ "And a partridge in a pear tree!",
"Two turtle doves,",
"Three french hens,",
"Four calling birds,",
"FIVE GOLDEN RINGS,",
"Six geese a-laying,",
"Seven swans a-swimming,",
"Eight maids a-milking,",
"Nine ladies dancing,",
"Ten lords a-leaping,",
"Eleven pipers piping,",
"Twelve drummers drumming,"
]
days :: [String]
days =
[ "first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth"
]
verseOfTheDay :: Int -> IO ()
verseOfTheDay day = do
putStrLn $
"On the " <> days !! day
<> " day of Christmas my true love gave to me... "
mapM_ putStrLn [dayGift day d | d <- [day, day -1 .. 0]]
putStrLn ""
where
dayGift 0 _ = "A partridge in a pear tree!"
dayGift _ gift = gifts !! gift
main :: IO ()
main = mapM_ verseOfTheDay [0 .. 11] |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #ooRexx | ooRexx |
#!/usr/bin/rexx
/*.----------------------------------------------------------------------.*/
/*|bashcolours: Display a table showing all of the possible colours that |*/
/*| can be generated using ANSI escapes in bash in an xterm |*/
/*| terminal session. |*/
/*| |*/
/*|Usage: |*/
/*| |*/
/*|>>-bashcolours-.----------.-----------------------------------------><|*/
/*| |-- -? ----| |*/
/*| |-- -h ----| |*/
/*| '- --help -' |*/
/*| |*/
/*|where |*/
/*| -?, -h or --help |*/
/*| display this documentation. |*/
/*| |*/
/*|This program is based on the shell script in the Bash Prompt HowTo at |*/
/*|http://www.tldp.org/, by Giles Orr. |*/
/*| |*/
/*|This program writes the various colour codes to the terminal to |*/
/*|demonstrate what's available. Each line showshe colour code of one |*/
/*|forground colour, out of 17 (default + 16 escapes), followed by a test|*/
/*|use of that colour on all nine background colours (default + 8 |*/
/*|escapes). Additional highlighting escapes are also demonstrated. |*/
/*| |*/
/*|This program uses object-oriented features of Open Object Rexx. |*/
/*|The lineout method is used instead of say for consistency with use of |*/
/*|the charout method. |*/
/*'----------------------------------------------------------------------'*/
call usage arg(1)
trace normal
/* See if escapes work on the kind of terminal in use. */
if value('TERM',,'ENVIRONMENT') = 'LINUX' then
do
say 'The Linux console does not support ANSI escape sequences for',
'changing text colours or highlighting.'
exit 4
end
/* Set up the escape sequences. */
! = '1B'x -- ASCII escape
bg = .array~of('[40m','[41m','[42m','[43m','[44m','[45m','[46m','[47m')
fg = .array~of('[0m', '[1m', '[0;30m','[1;30m','[0;31m','[1;31m',,
'[0;32m','[1;32m','[0;33m','[1;33m','[0;34m','[1;34m',,
'[0;35m','[1;35m','[0;36m','[1;36m','[0;37m','[1;37m')
hi = .array~of('[4m','[5m','[7m','[8m')
text = 'gYw' -- The test text
.OUTPUT~lineout(' ')
.OUTPUT~lineout('Foreground | Background Codes')
.OUTPUT~lineout(!'[4mCodes '!'[0m|'||,
!'[4m~[40m ~[41m ~[42m ~[43m ~[44m ~[45m ~[46m ~[47m'!'[0m')
do f = 1 to fg~size -- write the foreground info.
prefix = '~'fg[f]~left(6)' '!||fg[f]~strip' 'text
.OUTPUT~charout(prefix)
do b = 1 to bg~size -- write the background info.
segment = !||fg[f]~strip !||bg[b]' 'text' '!||fg[1]
.OUTPUT~charout(segment)
end
.OUTPUT~lineout(' ')
end
/* Write the various highlighting escape sequences. */
prefix = '~[4m'~left(6)' '!||hi[1]'Underlined'!||fg[1]
.OUTPUT~lineout(prefix)
prefix = '~[5m'~left(6)' '!||hi[2]'Blinking'!||fg[1]
.OUTPUT~lineout(prefix)
prefix = '~[7m'~left(6)' '!||hi[3]'Inverted'!||fg[1]
.OUTPUT~lineout(prefix)
prefix = '~[8m'~left(6)' '!||hi[4]'Concealed'!||fg[1],
"(Doesn't seem to work in my xterm; might in Windows?)"
.OUTPUT~lineout(prefix)
.OUTPUT~lineout(' ')
.OUTPUT~lineout("Where ~ denotes the ASCII escape character ('1B'x).")
.OUTPUT~lineout(' ')
exit
/*.--------------------------------------------------------.*/
/*|One might expect to be able to use directory collections|*/
/*|as below instead of array collections, but there is no |*/
/*|way to guarantee that a directory's indices will be |*/
/*|iterated over in a consistent sequence, since directory |*/
/*|objects are not ordered. Oh, well... |*/
/*'--------------------------------------------------------'*/
fg = .directory~new
fg[Default] = '[0m'; fg[DefaultBold] = '[1m'
fg[Black] = '[0;30m'; fg[DarkGray] = '[1;30m'
fg[Blue] = '[0;34m'; fg[LightBlue] = '[1;34m'
fg[Green] = '[0;32m'; fg[LightGreen] = '[1;32m'
fg[Cyan] = '[0;36m'; fg[LightCyan] = '[1;36m'
fg[Red] = '[0;31m'; fg[LightRed] = '[1;31m'
fg[Purple] = '[0;35m'; fg[LightPurple] = '[1;35m'
fg[Brown] = '[0;33m'; fg[Yellow] = '[1;33m'
fg[LightGray] = '[0;37m'; fg[White] = '[1;37m'
bg = .directory~new; hi = .directory~new
bg[Black] = '[0;40m'; hi[Underlined] = '[4m'
bg[Blue] = '[0;44m'; hi[Blinking] = '[5m'
bg[Green] = '[0;42m'; hi[Inverted] = '[7m'
bg[Cyan] = '[0;46m'; hi[Concealed] = '[8m'
bg[Red] = '[0;41m'
bg[Purple] = '[0;45m'
bg[Brown] = '[0;43m'
bg[LightGray] = '[0;47m'
usage: procedure
trace normal
if arg(1) = '-h',
| arg(1) = '-?',
| arg(1) = '--help'
then
do
line = '/*|'
say
do l = 3 by 1 while line~left(3) = '/*|'
line = sourceline(l)
parse var line . '/*|' text '|*/' .
.OUTPUT~lineout(text)
end
say
exit 0
end
return
|
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.
| #C.23 | C# | using System;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.IO;
namespace SynchronousConcurrency
{
class Program
{
static void Main(string[] args)
{
BlockingCollection<string> toWriterTask = new BlockingCollection<string>();
BlockingCollection<int> fromWriterTask = new BlockingCollection<int>();
Task writer = Task.Factory.StartNew(() => ConsoleWriter(toWriterTask, fromWriterTask));
Task reader = Task.Factory.StartNew(() => FileReader(fromWriterTask, toWriterTask));
Task.WaitAll(writer, reader);
}
static void ConsoleWriter(BlockingCollection<string> input, BlockingCollection<int> output)
{
int nLines = 0;
string line;
while ((line = input.Take()) != null)
{
Console.WriteLine(line);
++nLines;
}
output.Add(nLines);
}
static void FileReader(BlockingCollection<int> input, BlockingCollection<string> output)
{
StreamReader file = new StreamReader("input.txt"); // TODO: check exceptions
string line;
while ((line = file.ReadLine()) != null)
{
output.Add(line);
}
output.Add(null); // EOF
Console.WriteLine("line count: " + input.Take());
}
}
} |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Lasso | Lasso | // connect to a Mysql database
inline(-database = 'rosettatest', -sql = "CREATE TABLE `address` (
`id` int(11) NOT NULL auto_increment,
`street` varchar(50) NOT NULL default '',
`city` varchar(25) NOT NULL default '',
`state` char(2) NOT NULL default '',
`zip` char(10) NOT NULL default '',
PRIMARY KEY (`id`)
);
") => {^
error_msg
^} |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Lua | Lua | -- Import module
local sql = require("ljsqlite3")
-- Open connection to database file
local conn = sql.open("address.sqlite")
-- Create address table unless it already exists
conn:exec[[
CREATE TABLE IF NOT EXISTS address(
id INTEGER PRIMARY KEY AUTOINCREMENT,
street TEXT NOT NULL,
city TEXT NOT NULL,
state TEXT NOT NULL,
zip TEXT NOT NULL)
]]
-- Explicitly close connection
conn:close() |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | TableCreation="CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL, addrCity TEXT NOT NULL,
addrState TEXT NOT NULL, addrZIP TEXT NOT NULL )";
Needs["DatabaseLink`"]
conn=OpenSQLConnection[ JDBC[ "mysql","databases:1234/conn_test"], "Username" -> "test"]
SQLExecute[ conn, TableCreation] |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #MySQL | MySQL | CREATE TABLE `Address` (
`addrID` int(11) NOT NULL auto_increment,
`addrStreet` varchar(50) NOT NULL default '',
`addrCity` varchar(25) NOT NULL default '',
`addrState` char(2) NOT NULL default '',
`addrZIP` char(10) NOT NULL default '',
PRIMARY KEY (`addrID`)
); |
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.
| #C.23 | C# | using System;
using System.IO;
using System.Text;
namespace RosettaCode
{
internal class Program
{
private const string FileName = "NOTES.TXT";
private static void Main(string[] args)
{
if (args.Length==0)
{
string txt = File.ReadAllText(FileName);
Console.WriteLine(txt);
}
else
{
var sb = new StringBuilder();
sb.Append(DateTime.Now).Append("\n\t");
foreach (string s in args)
sb.Append(s).Append(" ");
sb.Append("\n");
if (File.Exists(FileName))
File.AppendAllText(FileName, sb.ToString());
else
File.WriteAllText(FileName, sb.ToString());
}
}
}
} |
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.
| #C.2B.2B | C++ | #include <fstream>
#include <iostream>
#include <ctime>
using namespace std;
#define note_file "NOTES.TXT"
int main(int argc, char **argv)
{
if(argc>1)
{
ofstream Notes(note_file, ios::app);
time_t timer = time(NULL);
if(Notes.is_open())
{
Notes << asctime(localtime(&timer)) << '\t';
for(int i=1;i<argc;i++)
Notes << argv[i] << ' ';
Notes << endl;
Notes.close();
}
}
else
{
ifstream Notes(note_file, ios::in);
string line;
if(Notes.is_open())
{
while(!Notes.eof())
{
getline(Notes, line);
cout << line << endl;
}
Notes.close();
}
}
} |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #11l | 11l | F sylverster(lim)
V result = [BigInt(2)]
L 2..lim
result.append(product(result) + 1)
R result
V l = sylverster(10)
print(‘First 10 terms of the Sylvester sequence:’)
L(item) l
print(item)
V s = 0.0
L(item) l
s += 1 / Float(item)
print("\nSum of the reciprocals of the first 10 terms: #.17".format(s)) |
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).
| #Fortran | Fortran |
! A non-bruteforce approach
PROGRAM POOKA
IMPLICIT NONE
!
! PARAMETER definitions
!
INTEGER , PARAMETER :: NVARS = 25
!
! Local variables
!
REAL :: f1
REAL :: f2
INTEGER :: hits
INTEGER :: s
INTEGER :: TAXICAB
hits = 0
s = 0
f1 = SECOND()
DO WHILE ( hits<NVARS )
s = s + 1
hits = hits + TAXICAB(s)
END DO
f2 = SECOND()
PRINT * , 'elapsed time = ' , f2 - f1 , 'For ' , NVARS , ' Variables'
STOP
END PROGRAM POOKA
FUNCTION TAXICAB(N)
IMPLICIT NONE
!
! Dummy arguments
!
INTEGER :: N
INTEGER :: TAXICAB
INTENT (IN) N
!
! Local variables
!
INTEGER :: holder
INTEGER :: oldx
INTEGER :: oldy
INTEGER :: s
INTEGER :: x
INTEGER :: y
real*8,parameter :: xpon=(1.0D0/3.0D0)
!
x = 0
holder = 0
oldx = 0
oldy = 0
TAXICAB = 0
y = INT(N**xpon)
DO WHILE ( x<=y )
s = x**3 + y**3
IF( s<N )THEN
x = x + 1
ELSE IF( s>N )THEN
y = y - 1
ELSE
IF( holder==s )THEN ! Print the last value and this one that correspond
WRITE(6 , 34)s , '(' , x**3 , y**3 , ')' , '(' , oldx**3 , oldy**3 , ')'
34 FORMAT(1x , i12 , 10x , 1A1 , i12 , 2x , i12 , 1A1 , 10x , 1A1 , i12 , 2x ,&
& i12 , 1A1)
TAXICAB = 1 ! Indicate that we found a Taxi Number
END IF
holder = s ! Set to the number that appears a potential cab number
oldx = x ! Retain the values for the 2 cubes
oldy = y
x = x + 1 ! Keep looking
y = y - 1
END IF
END DO
RETURN
END FUNCTION TAXICAB
|
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 12
char *super = 0;
int pos, cnt[MAX];
// 1! + 2! + ... + n!
int fact_sum(int n)
{
int s, x, f;
for (s = 0, x = 0, f = 1; x < n; f *= ++x, s += f);
return s;
}
int r(int n)
{
if (!n) return 0;
char c = super[pos - n];
if (!--cnt[n]) {
cnt[n] = n;
if (!r(n-1)) return 0;
}
super[pos++] = c;
return 1;
}
void superperm(int n)
{
int i, len;
pos = n;
len = fact_sum(n);
super = realloc(super, len + 1);
super[len] = '\0';
for (i = 0; i <= n; i++) cnt[i] = i;
for (i = 1; i <= n; i++) super[i - 1] = i + '0';
while (r(n));
}
int main(void)
{
int n;
for (n = 0; n < MAX; n++) {
printf("superperm(%2d) ", n);
superperm(n);
printf("len = %d", (int)strlen(super));
// uncomment next line to see the string itself
// printf(": %s", super);
putchar('\n');
}
return 0;
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #jq | jq | def count(s): reduce s as $x (0; .+1);
# For pretty-printing
def nwise($n):
def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end;
n;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Julia | Julia | using Primes
function numfactors(n)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init = f)
end
length(f)
end
function taunumbers(toget = 100)
n = 0
for i in 1:100000000
if i % numfactors(i) == 0
n += 1
print(rpad(i, 5), n % 20 == 0 ? " \n" : "")
n == toget && break
end
end
end
taunumbers()
|
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Lua | Lua | function divisor_count(n)
local total = 1
-- Deal with powers of 2 first
while (n & 1) == 0 do
total = total + 1
n = n >> 1
end
-- Odd prime factors up to the square root
local p = 3
while p * p <= n do
local count = 1
while n % p == 0 do
count = count + 1
n = math.floor(n / p)
end
total = total * count
p = p + 2
end
-- If n > 1 then it's prime
if n > 1 then
total = total * 2
end
return total
end
local limit = 100
local count = 0
print("The first " .. limit .. " tau numbers are:")
local n = 1
while count < limit do
if n % divisor_count(n) == 0 then
io.write(string.format("%6d", n))
count = count + 1
if count % 10 == 0 then
print()
end
end
n = n + 1
end |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #REXX | REXX | /* REXX - Tarjan's Algorithm */
/* Vertices are numbered 1 to 8 (instead of 0 to 7) */
g='[2] [3] [1] [2 3 5] [4 6] [3 7] [6] [5 7 8]'
gg=g
Do i=1 By 1 While gg>''
Parse Var gg '[' g.i ']' gg
name.i=i-1
End
g.0=i-1
index.=0
lowlink.=0
stacked.=0
stack.=0
x=1
Do n=1 To g.0
If index.n=0 Then
If strong_connect(n)=0 Then
Return
End
Exit
strong_connect: Procedure Expose x g. index. lowlink. stacked. stack. name.
Parse Arg n
index.n = x
lowlink.n = x
stacked.n = 1
Call stack n
x=x+1
Do b=1 To words(g.n)
Call show_all
nb=word(g.n,b)
If index.nb=0 Then Do
If strong_connect(nb)=0 Then
Return 0
If lowlink.nb < lowlink.n Then
lowlink.n = lowlink.nb
End
Else Do
If stacked.nb = 1 Then
If index.nb < lowlink.n Then
lowlink.n = index.nb
end
end
if lowlink.n=index.n then Do
c=''
Do z=stack.0 By -1
w=stack.z
stacked.w=0
stack.0=stack.0-1
c=name.w c
If w=n Then Do
Say '['space(c)']'
Return 1
End
End
End
Return 1
stack: Procedure Expose stack.
Parse Arg m
z=stack.0+1
stack.z=m
stack.0=z
Return
/* The following were used for debugging (and understanding) */
show_all: Return
ind='Index '
low='Lowlink'
sta='Stacked'
Do z=1 To g.0
ind=ind index.z
low=low lowlink.z
sta=sta stacked.z
End
Say ind
Say low
Say sta
Return
show_stack:
ol='Stack'
Do z=1 To stack.0
ol=ol stack.z
End
Say ol
Return |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #PicoLisp | PicoLisp | (de rotw (W)
(let W (chop W)
(unless (or (apply = W) (not (cddr W)))
(make
(do (length W)
(link (pack (copy W)))
(rot W) ) ) ) ) )
(off D)
(put 'D 'v (cons))
(mapc
'((W)
(idx 'D (cons (hash W) W) T) )
(setq Words
(make (in "wordlist.10000" (while (line T) (link @)))) ) )
(mapc
println
(extract
'((W)
(let? Lst (rotw W)
(when
(and
(fully
'((L) (idx 'D (cons (hash L) L)))
Lst )
(not
(member (car Lst) (car (get 'D 'v))) ) )
(mapc
'((L) (push (get 'D 'v) L))
Lst )
Lst ) ) )
Words ) ) |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #PureBasic | PureBasic | DataSection
dname:
Data.s "./Data/unixdict.txt"
Data.s "./Data/wordlist.10000.txt"
Data.s ""
EndDataSection
EnableExplicit
Dim c.s{1}(2)
Define.s txt, bset, res, dn
Define.i i,q, cw
Restore dname : Read.s dn
While OpenConsole() And ReadFile(0,dn)
While Not Eof(0)
cw+1
txt=ReadString(0)
If Len(txt)=3 : bset+txt+";" : EndIf
Wend
CloseFile(0)
For i=1 To CountString(bset,";")
PokeS(c(),StringField(bset,i,";"))
If FindString(res,c(0)+c(1)+c(2)) : Continue : EndIf
If c(0)=c(1) Or c(1)=c(2) Or c(0)=c(2) : Continue : EndIf
If FindString(bset,c(1)+c(2)+c(0)) And FindString(bset,c(2)+c(0)+c(1))
res+c(0)+c(1)+c(2)+~"\t"+c(1)+c(2)+c(0)+~"\t"+c(2)+c(0)+c(1)+~"\n"
EndIf
Next
PrintN(res+Str(cw)+" words, "+Str(CountString(res,~"\n"))+" circular") : Input()
bset="" : res="" : cw=0
Read.s dn
Wend |
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
| #AutoHotkey | AutoHotkey | MsgBox, % "Kelvin:`t`t 21.00 K`n"
. "Celsius:`t`t" kelvinToCelsius(21) " C`n"
. "Fahrenheit:`t" kelvinToFahrenheit(21) " F`n"
. "Rankine:`t`t" kelvinToRankine(21) " R`n"
kelvinToCelsius(k)
{
return, round(k - 273.15, 2)
}
kelvinToFahrenheit(k)
{
return, round(k * 1.8 - 459.67, 2)
}
kelvinToRankine(k)
{
return, round(k * 1.8, 2)
} |
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
| #Dyalect | Dyalect | func divisorCount(number) {
var n = number
var total = 1
while (n &&& 1) == 0 {
total += 1
n >>>= 1
}
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 {
total *= 2
}
total
}
let limit = 100
print("Count of divisors for the first \(limit) positive integers:")
for n in 1..limit {
print(divisorCount(number: n).ToString().PadLeft(2, ' ') + " ", terminator: "")
print() when n % 20 == 0
} |
http://rosettacode.org/wiki/Tau_function | Tau function | Given a positive integer, count the number of its positive divisors.
Task
Show the result for the first 100 positive integers.
Related task
Tau number
| #F.23 | F# |
// Tau function. Nigel Galloway: March 10th., 2021
let tau u=let P=primes32()
let rec fN g=match u%g with 0->g |_->fN(Seq.head P)
let rec fG n i g e l=match n=u,u%l with (true,_)->e |(_,0)->fG (n*i) i g (e+g)(l*i) |_->let q=fN(Seq.head P) in fG (n*q) q e (e+e) (q*q)
let n=Seq.head P in fG 1 n 1 1 n
[1..100]|>Seq.iter(tau>>printf "%d "); printfn ""
|
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Icon_and_Unicon | Icon and Unicon | procedure main ()
if &features == "MS Windows" then system("cls") # Windows
else if &features == "UNIX" then system("clear") # Unix
end |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #J | J | smwrite_jijs_ '' |
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen | Terminal control/Clear the screen | Task
Clear the terminal window.
| #Java | Java | public class Clear
{
public static void main (String[] args)
{
System.out.print("\033[2J");
}
} |
http://rosettacode.org/wiki/Ternary_logic | Ternary logic |
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In logic, a three-valued logic (also trivalent, ternary, or trinary logic, sometimes abbreviated 3VL) is any of several many-valued logic systems in which there are three truth values indicating true, false and some indeterminate third value.
This is contrasted with the more commonly known bivalent logics (such as classical sentential or boolean logic) which provide only for true and false.
Conceptual form and basic ideas were initially created by Łukasiewicz, Lewis and Sulski.
These were then re-formulated by Grigore Moisil in an axiomatic algebraic form, and also extended to n-valued logics in 1945.
Example Ternary Logic Operators in Truth Tables:
not a
¬
True
False
Maybe
Maybe
False
True
a and b
∧
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
False
False
False
False
False
a or b
∨
True
Maybe
False
True
True
True
True
Maybe
True
Maybe
Maybe
False
True
Maybe
False
if a then b
⊃
True
Maybe
False
True
True
Maybe
False
Maybe
True
Maybe
Maybe
False
True
True
True
a is equivalent to b
≡
True
Maybe
False
True
True
Maybe
False
Maybe
Maybe
Maybe
Maybe
False
False
Maybe
True
Task
Define a new type that emulates ternary logic by storing data trits.
Given all the binary logic operators of the original programming language, reimplement these operators for the new Ternary logic type trit.
Generate a sampling of results using trit variables.
Kudos for actually thinking up a test case algorithm where ternary logic is intrinsically useful, optimises the test case algorithm and is preferable to binary logic.
Note: Setun (Сетунь) was a balanced ternary computer developed in 1958 at Moscow State University. The device was built under the lead of Sergei Sobolev and Nikolay Brusentsov. It was the only modern ternary computer, using three-valued ternary logic
| #JavaScript | JavaScript | var L3 = new Object();
L3.not = function(a) {
if (typeof a == "boolean") return !a;
if (a == undefined) return undefined;
throw("Invalid Ternary Expression.");
}
L3.and = function(a, b) {
if (typeof a == "boolean" && typeof b == "boolean") return a && b;
if ((a == true && b == undefined) || (a == undefined && b == true)) return undefined;
if ((a == false && b == undefined) || (a == undefined && b == false)) return false;
if (a == undefined && b == undefined) return undefined;
throw("Invalid Ternary Expression.");
}
L3.or = function(a, b) {
if (typeof a == "boolean" && typeof b == "boolean") return a || b;
if ((a == true && b == undefined) || (a == undefined && b == true)) return true;
if ((a == false && b == undefined) || (a == undefined && b == false)) return undefined;
if (a == undefined && b == undefined) return undefined;
throw("Invalid Ternary Expression.");
}
// A -> B is equivalent to -A or B
L3.ifThen = function(a, b) {
return L3.or(L3.not(a), b);
}
// A <=> B is equivalent to (A -> B) and (B -> A)
L3.iff = function(a, b) {
return L3.and(L3.ifThen(a, b), L3.ifThen(b, a));
}
|
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.
| #Nim | Nim | import os, sequtils, strutils, strformat
var
nodata = 0
nodataMax = -1
nodataMaxLine: seq[string]
totFile = 0.0
numFile = 0
for filename in commandLineParams():
for line in filename.lines:
var
totLine = 0.0
numLine = 0
data: seq[float]
flags: seq[int]
let fields = line.split()
let date = fields[0]
for i, field in fields[1..^1]:
if i mod 2 == 0: data.add parseFloat(field)
else: flags.add parseInt(field)
for datum, flag in zip(data, flags).items:
if flag < 1:
inc nodata
else:
if nodataMax == nodata and nodata > 0:
nodataMaxLine.add date
if nodataMax < nodata and nodata > 0:
nodataMax = nodata
nodataMaxLine = @[date]
nodata = 0
totLine += datum
inc numLine
totFile += totLine
numFile += numLine
let average = if numLine > 0: totLine / float(numLine) else: 0.0
echo &"Line: {date} Reject: {data.len - numLine:2} Accept: {numLine:2} ",
&"LineTot: {totLine:6.2f} LineAvg: {average:4.2f}"
echo()
echo &"""File(s) = {commandLineParams().join(" ")}"""
echo &"Total = {totFile:.2f}"
echo &"Readings = {numFile}"
echo &"Average = {totFile / float(numFile):.2f}"
echo ""
echo &"Maximum run(s) of {nodataMax} consecutive false readings ",
&"""ends at line starting with date(s): {nodataMaxLine.join(" ")}.""" |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
days := ["first","second","third","fourth","fifth","sixth","seventh",
"eighth","ninth","tenth","eleventh","twelveth"]
gifts := ["A partridge in a pear tree.", "Two turtle doves and",
"Three french hens,", "Four calling birds,",
"Five golden rings,", "Six geese a-laying,",
"Seven swans a-swimming,", "Eight maids a-milking,",
"Nine ladies dancing,", "Ten lords a-leaping,",
"Eleven pipers piping,", "Twelve drummers drumming,"]
every write("\nOn the ",days[day := 1 to 12]," day of Christmas my true love gave to me:") do
every write(" ",gifts[day to 1 by -1])
end |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #PARI.2FGP | PARI/GP | for(b=40, 47, for(c=30, 37, printf("\e[%d;%d;1mRosetta Code\e[0m\n", c, b))) |
http://rosettacode.org/wiki/Terminal_control/Coloured_text | Terminal control/Coloured text | Task
Display a word in various colours on the terminal.
The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used.
Optionally demonstrate:
How the system should determine if the terminal supports colour
Setting of the background colour
How to cause blinking or flashing (if supported by the terminal)
| #Pascal | Pascal | program Colorizer;
uses CRT;
const SampleText = 'Lorem ipsum dolor sit amet';
var fg, bg: 0..15;
begin
ClrScr;
for fg := 0 to 7 do begin
bg := 15 - fg;
TextBackground(bg);
TextColor(fg);
writeln(SampleText)
end;
TextBackground(White);
TextColor(Black);
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.
| #C.2B.2B | C++ | #include <future>
#include <iostream>
#include <fstream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
struct lock_queue
{
std::queue<std::string> q;
std::mutex mutex;
};
void reader(std::string filename, std::future<size_t> lines, lock_queue& out)
{
std::string line;
std::ifstream in(filename);
while(std::getline(in, line)) {
line += '\n';
std::lock_guard<std::mutex> lock(out.mutex);
out.q.push(line);
} {
std::lock_guard<std::mutex> lock(out.mutex);
out.q.push("");
}
lines.wait();
std::cout << "\nPrinted " << lines.get() << " lines\n";
}
void printer(std::promise<size_t> lines, lock_queue& in)
{
std::string s;
size_t line_n = 0;
bool print = false;
while(true) {
{
std::lock_guard<std::mutex> lock(in.mutex);
if(( print = not in.q.empty() )) { //Assignment intended
s = in.q.front();
in.q.pop();
}
}
if(print) {
if(s == "") break;
std::cout << s;
++line_n;
print = false;
}
}
lines.set_value(line_n);
}
int main()
{
lock_queue queue;
std::promise<size_t> promise;
std::thread t1(reader, "input.txt", promise.get_future(), std::ref(queue));
std::thread t2(printer, std::move(promise), std::ref(queue));
t1.join(); t2.join();
} |
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import java.sql.Connection
import java.sql.Statement
import java.sql.SQLException
import java.sql.DriverManager
class RTableCreate01 public
properties private constant
addressDDL = String '' -
' create table Address' -
' (' -
' addrID integer primary key generated by default as identity,' -
' addrStreet varchar(50) not null,' -
' addrCity varchar(50) not null,' -
' addrState char(2) not null,' -
' addrZip char(10) not null' -
' )'
driver = String 'org.apache.derby.jdbc.EmbeddedDriver'
dbName = String 'db/rosetta_code'
method createTable() public static
connectionURL = String
conn = java.sql.Connection
sqlStatement = java.sql.Statement
do
Class.forName(driver)
connectionURL = 'jdbc:derby:' || dbName || ';' || 'create=true'
conn = DriverManager.getConnection(connectionURL)
sqlStatement = conn.createStatement()
say 'Creating table'
sqlStatement.execute(addressDDL)
say 'Table creation complete'
sqlStatement.close()
conn.close()
do
-- In embedded mode, an application should shut down Derby.
-- Shutdown throws the XJ015 exception to confirm success.
connectionURL = 'jdbc:derby:' || ';' || 'shutdown=true'
DriverManager.getConnection(connectionURL)
catch sex = SQLException
if sex.getSQLState().equals("XJ015") then do
say 'Database shut down normally'
end
else do
say 'Database did not shut down normally'
signal sex
end
end
catch sex = SQLException
sex.printStackTrace()
catch ex = ClassNotFoundException
ex.printStackTrace()
end
return
method main(args = String[]) public static
createTable()
return
|
http://rosettacode.org/wiki/Table_creation/Postal_addresses | Table creation/Postal addresses | Task
Create a table to store addresses.
You may assume that all the addresses to be stored will be located in the USA. As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zipcode. Choose appropriate types for each field.
For non-database languages, show how you would open a connection to a database (your choice of which) and create an address table in it. You should follow the existing models here for how you would structure the table.
| #Nim | Nim | import db_sqlite as db
#import db_mysql as db
#import db_postgres as db
const
connection = ":memory:"
user = "foo"
pass = "bar"
database = "db"
var c = open(connection, user, pass, database)
c.exec sql"""CREATE TABLE address (
addrID INTEGER PRIMARY KEY AUTOINCREMENT,
addrStreet TEXT NOT NULL,
addrCity TEXT NOT NULL,
addrState TEXT NOT NULL,
addrZIP TEXT NOT NULL)"""
c.close() |
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.)
| #11l | 11l | F clip(subjectPolygon, clipPolygon)
F inside(p, cp1, cp2)
R (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)
F computeIntersection(s, e, cp1, cp2)
V dc = cp1 - cp2
V dp = s - e
V n1 = cp1.x * cp2.y - cp1.y * cp2.x
V n2 = s.x * e.y - s.y * e.x
V n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x)
R ((n1 * dp.x - n2 * dc.x) * n3, (n1 * dp.y - n2 * dc.y) * n3)
V outputList = subjectPolygon
V cp1 = clipPolygon.last
L(clipVertex) clipPolygon
V cp2 = clipVertex
V inputList = outputList
outputList.clear()
V s = inputList.last
L(subjectVertex) inputList
V e = subjectVertex
I inside(e, cp1, cp2)
I !inside(s, cp1, cp2)
outputList.append(computeIntersection(s, e, cp1, cp2))
outputList.append(e)
E I inside(s, cp1, cp2)
outputList.append(computeIntersection(s, e, cp1, cp2))
s = e
cp1 = cp2
R (outputList)
V subjectp = [(50.0, 150.0), (200.0, 50.0), (350.0, 150.0), (350.0, 300.0), (250.0, 300.0), (200.0, 250.0), (150.0, 350.0), (100.0, 250.0), (100.0, 200.0)]
V clipp = [(100.0, 100.0), (300.0, 100.0), (300.0, 300.0), (100.0, 300.0)]
print_elements(clip(subjectp, clipp), sep' "\n") |
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).
| #11l | 11l | V setA = Set([‘John’, ‘Bob’, ‘Mary’, ‘Serena’])
V setB = Set([‘Jim’, ‘Mary’, ‘John’, ‘Bob’])
print(setA.symmetric_difference(setB))
print(setA - setB)
print(setB - setA) |
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.
| #11l | 11l | V rd = [‘22’, ‘333’, ‘4444’, ‘55555’, ‘666666’, ‘7777777’, ‘88888888’, ‘999999999’]
L(ii) 2..7
print(‘First 10 super-#. numbers:’.format(ii))
V count = 0
BigInt j = 3
L
V k = ii * j^ii
I rd[ii - 2] C String(k)
count++
print(j, end' ‘ ’)
I count == 10
print("\n")
L.break
j++ |
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.
| #Clojure | Clojure | (ns rosettacode.notes
(:use [clojure.string :only [join]]))
(defn notes [notes]
(if (seq notes)
(spit
"NOTES.txt"
(str (java.util.Date.) "\n" "\t"
(join " " notes) "\n")
:append true)
(println (slurp "NOTES.txt"))))
(notes *command-line-args*) |
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.
| #CLU | CLU | % This program uses the "get_argv" function that is supplied iwth
% PCLU in "useful.lib".
NOTEFILE = "notes.txt"
% Format the date and time as MM/DD/YYYY HH:MM:SS [AM|PM]
format_date = proc (d: date) returns (string)
ds: stream := stream$create_output()
stream$putzero(ds, int$unparse(d.month), 2)
stream$putc(ds, '/')
stream$putzero(ds, int$unparse(d.day), 2)
stream$putc(ds, '/')
stream$putzero(ds, int$unparse(d.year), 4)
stream$putc(ds, ' ')
hour: int := d.hour // 12
if hour=0 then hour:=12 end
ampm: string := "AM"
if d.hour>=12 then ampm := "PM" end
stream$putzero(ds, int$unparse(hour), 2)
stream$putc(ds, ':')
stream$putzero(ds, int$unparse(d.minute), 2)
stream$putc(ds, ':')
stream$putzero(ds, int$unparse(d.second), 2)
stream$putc(ds, ' ')
stream$puts(ds, ampm)
return(stream$get_contents(ds))
end format_date
% Add a note to the file
add_note = proc (note: sequence[string])
fn: file_name := file_name$parse(NOTEFILE)
out: stream := stream$open(fn, "append")
stream$putl(out, format_date(now()))
c: char := '\t'
for part: string in sequence[string]$elements(note) do
stream$putc(out, c)
stream$puts(out, part)
c := ' '
end
stream$putc(out, '\n')
stream$close(out)
end add_note
% Show the notes file, if it exists
show_notes = proc ()
po: stream := stream$primary_output()
fn: file_name := file_name$parse(NOTEFILE)
begin
inp: stream := stream$open(fn, "read")
while true do
stream$putl(po, stream$getl(inp))
except when end_of_file: break end
end
stream$close(inp)
end except when not_possible(s: string): end
end show_notes
% Add a note if one is given, show the notes otherwise
start_up = proc ()
note: sequence[string] := get_argv()
if sequence[string]$empty(note)
then show_notes()
else add_note(note)
end
end start_up |
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #ALGOL_68 | ALGOL 68 | BEGIN # calculate elements of Sylvestor's Sequence #
PR precision 200 PR # set the number of digits for LONG LONG modes #
# returns an array set to the forst n elements of Sylvestor's Sequence #
# starting from 2, the elements are the product of the previous #
# elements plus 1 #
OP SYLVESTOR = ( INT n )[]LONG LONG INT:
BEGIN
[ 1 : n ]LONG LONG INT result;
LONG LONG INT product := 2;
result[ 1 ] := 2;
FOR i FROM 2 TO n DO
result[ i ] := product + 1;
product *:= result[ i ]
OD;
result
END;
# find the first 10 elements of Sylvestor's Seuence #
[]LONG LONG INT seq = SYLVESTOR 10;
# show the sequence and sum the reciprocals #
LONG LONG REAL reciprocal sum := 0;
FOR i FROM LWB seq TO UPB seq DO
print( ( whole( seq[ i ], 0 ), newline ) );
reciprocal sum +:= 1 / seq[ i ]
OD;
print( ( "Sum of reciprocals: ", reciprocal sum, newline ) )
END
|
http://rosettacode.org/wiki/Sylvester%27s_sequence | Sylvester's sequence |
This page uses content from Wikipedia. The original article was at Sylvester's sequence. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In number theory, Sylvester's sequence is an integer sequence in which each term of the sequence is the product of the previous terms, plus one.
Its values grow doubly exponentially, and the sum of its reciprocals forms a series of unit fractions that converges to 1 more rapidly than any other series of unit fractions with the same number of terms.
Further, the sum of the first k terms of the infinite series of reciprocals provides the closest possible underestimate of 1 by any k-term Egyptian fraction.
Task
Write a routine (function, procedure, generator, whatever) to calculate Sylvester's sequence.
Use that routine to show the values of the first 10 elements in the sequence.
Show the sum of the reciprocals of the first 10 elements on the sequence, ideally as an exact fraction.
Related tasks
Egyptian fractions
Harmonic series
See also
OEIS A000058 - Sylvester's sequence
| #Arturo | Arturo | sylvester: function [lim][
result: new [2]
loop 2..lim 'x [
'result ++ inc fold result .seed:1 [a b][a * b]
]
return result
]
lst: sylvester 10
print "First 10 terms of the Sylvester sequence:"
print lst
print ""
sumRep: round sum map lst => [1 // &]
print "Sum of the reciprocals of the first 10 items:"
print sumRep |
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).
| #FreeBASIC | FreeBASIC | ' version 11-10-2016
' compile with: fbc -s console
' Brute force
' adopted from "Sorting algorithms/Shell" sort Task
Sub shellsort(s() As String)
' sort from lower bound to the highter bound
Dim As UInteger lb = LBound(s)
Dim As UInteger ub = UBound(s)
Dim As Integer done, i, inc = ub - lb
Do
inc = inc / 2.2
If inc < 1 Then inc = 1
Do
done = 0
For i = lb To ub - inc
If s(i) > s(i + inc) Then
Swap s(i), s(i + inc)
done = 1
End If
Next
Loop Until done = 0
Loop Until inc = 1
End Sub
' ------=< MAIN >=------
Dim As UInteger x, y, count, c, sum
Dim As UInteger cube(1290)
Dim As String result(), str1, str2, str3
Dim As String buf11 = Space(11), buf5 = Space(5)
ReDim result(900000) ' ~1291*1291\2
' set up the cubes
Print : Print " Calculate cubes"
For x = 1 To 1290
cube(x) = x*x*x
Next
' combine and store
Print : Print " Combine cubes"
For x = 1 To 1290
For y = x To 1290
sum = cube(x)+cube(y)
RSet buf11, Str(sum) : str1 = buf11
RSet buf5, Str(x) : str2 = buf5
RSet buf5, Str(y) : Str3 = buf5
result(count)=buf11 + " = " + str2 + " ^ 3 + " + str3 + " ^ 3"
count = count +1
Next
Next
count= count -1
ReDim Preserve result(count) ' trim the array
Print : Print " Sort (takes some time)"
shellsort(result()) ' sort
Print : Print " Find the Taxicab numbers"
c = 1 ' start at index 1
For x = 0 To count -1
' find sums that match
If Left(result(x), 11) = Left(result(x + 1), 11) Then
result(c) = result(x)
y = x +1
Do ' merge the other solution(s)
result(c) = result(c) + Mid(result(y), 12)
y = y +1
Loop Until Left(result(x), 11) <> Left(result(y), 11)
x = y -1 ' let x point to last match result
c = c +1
End If
Next
c = c -1
Print : Print " "; c; " Taxicab numbers found"
ReDim Preserve result(c) ' trim the array again
cls
Print : Print " Print first 25 numbers" : Print
For x = 1 To 25
Print result(x)
Next
Print : Print " The 2000th to the 2006th" : Print
For x = 2000 To 2006
Print result(x)
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Superpermutation_minimisation | Superpermutation minimisation | A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.
For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'.
The permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.
A too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.
A little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.
The "too obvious" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.
Show descriptions and comparisons of algorithms used here, and select the "Best" algorithm as being the one generating shorter superpermutations.
The problem of generating the shortest superpermutation for each N might be NP complete, although the minimal strings for small values of N have been found by brute -force searches.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
Reference
The Minimal Superpermutation Problem. by Nathaniel Johnston.
oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.
Superpermutations - Numberphile. A video
Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.
New Superpermutations Discovered! Standupmaths & Numberphile.
| #C.2B.2B | C++ | #include <array>
#include <iostream>
#include <vector>
constexpr int MAX = 12;
static std::vector<char> sp;
static std::array<int, MAX> count;
static int pos = 0;
int factSum(int n) {
int s = 0;
int x = 0;
int f = 1;
while (x < n) {
f *= ++x;
s += f;
}
return s;
}
bool r(int n) {
if (n == 0) {
return false;
}
char c = sp[pos - n];
if (--count[n] == 0) {
count[n] = n;
if (!r(n - 1)) {
return false;
}
}
sp[pos++] = c;
return true;
}
void superPerm(int n) {
pos = n;
int len = factSum(n);
if (len > 0) {
sp.resize(len);
}
for (size_t i = 0; i <= n; i++) {
count[i] = i;
}
for (size_t i = 1; i <= n; i++) {
sp[i - 1] = '0' + i;
}
while (r(n)) {}
}
int main() {
for (size_t n = 0; n < MAX; n++) {
superPerm(n);
std::cout << "superPerm(" << n << ") len = " << sp.size() << '\n';
}
return 0;
} |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #MAD | MAD | NORMAL MODE IS INTEGER
INTERNAL FUNCTION(N)
ENTRY TO POSDIV.
COUNT = 1
THROUGH DIV, FOR I=2, 1, I.G.N
DIV WHENEVER N/I*I.E.N, COUNT = COUNT+1
FUNCTION RETURN COUNT
END OF FUNCTION
SEEN=0
THROUGH TAU, FOR X=1, 1, SEEN.GE.100
DIVS=POSDIV.(X)
WHENEVER X/DIVS*DIVS.E.X
PRINT FORMAT NUM,X
SEEN = SEEN+1
TAU END OF CONDITIONAL
VECTOR VALUES NUM = $I4*$
END OF PROGRAM |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Take[Select[Range[10000], Divisible[#, Length[Divisors[#]]] &], 100] |
http://rosettacode.org/wiki/Tau_number | Tau number | A Tau number is a positive integer divisible by the count of its positive divisors.
Task
Show the first 100 Tau numbers.
The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike).
Related task
Tau function
| #Modula-2 | Modula-2 | MODULE TauNumbers;
FROM InOut IMPORT WriteCard, WriteLn;
CONST
MaxNum = 1100; (* enough to generate 100 Tau numbers *)
NumTau = 100; (* how many Tau numbers to generate *)
VAR DivCount: ARRAY [1..MaxNum] OF CARDINAL;
seen, n: CARDINAL;
(* Find the amount of divisors for each number beforehand *)
PROCEDURE CountDivisors;
VAR i, j: CARDINAL;
BEGIN
FOR i := 1 TO MaxNum DO
DivCount[i] := 1; (* every number is divisible by 1 *)
END;
FOR i := 2 TO MaxNum DO
j := i;
WHILE j <= MaxNum DO (* J is divisible by I *)
DivCount[j] := DivCount[j] + 1;
j := j + i; (* next multiple of i *)
END;
END;
END CountDivisors;
BEGIN
CountDivisors();
n := 1;
seen := 0;
WHILE seen < NumTau DO
IF n MOD DivCount[n] = 0 THEN
WriteCard(n, 5);
INC(seen);
IF seen MOD 10 = 0 THEN
WriteLn();
END;
END;
INC(n);
END;
END TauNumbers. |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #Rust | Rust | use std::collections::{BTreeMap, BTreeSet};
// Using a naked BTreeMap would not be very nice, so let's make a simple graph representation
#[derive(Clone, Debug)]
pub struct Graph {
neighbors: BTreeMap<usize, BTreeSet<usize>>,
}
impl Graph {
pub fn new(size: usize) -> Self {
Self {
neighbors: (0..size).fold(BTreeMap::new(), |mut acc, x| {
acc.insert(x, BTreeSet::new());
acc
}),
}
}
pub fn edges<'a>(&'a self, vertex: usize) -> impl Iterator<Item = usize> + 'a {
self.neighbors[&vertex].iter().cloned()
}
pub fn add_edge(&mut self, from: usize, to: usize) {
assert!(to < self.len());
self.neighbors.get_mut(&from).unwrap().insert(to);
}
pub fn add_edges(&mut self, from: usize, to: impl IntoIterator<Item = usize>) {
let limit = self.len();
self.neighbors
.get_mut(&from)
.unwrap()
.extend(to.into_iter().filter(|x| {
assert!(*x < limit);
true
}));
}
pub fn is_empty(&self) -> bool {
self.neighbors.is_empty()
}
pub fn len(&self) -> usize {
self.neighbors.len()
}
}
#[derive(Clone)]
struct VertexState {
index: usize,
low_link: usize,
on_stack: bool,
}
// The easy way not to fight with Rust's borrow checker is moving the state in
// a structure and simply invoke methods on that structure.
pub struct Tarjan<'a> {
graph: &'a Graph,
index: usize,
stack: Vec<usize>,
state: Vec<VertexState>,
components: Vec<BTreeSet<usize>>,
}
impl<'a> Tarjan<'a> {
// Having index: Option<usize> would look nicer, but requires just
// some unwraps and Vec has actual len limit isize::MAX anyway, so
// we can reserve this large value as the invalid one.
const INVALID_INDEX: usize = usize::MAX;
pub fn walk(graph: &'a Graph) -> Vec<BTreeSet<usize>> {
Self {
graph,
index: 0,
stack: Vec::new(),
state: vec![
VertexState {
index: Self::INVALID_INDEX,
low_link: Self::INVALID_INDEX,
on_stack: false
};
graph.len()
],
components: Vec::new(),
}
.visit_all()
}
fn visit_all(mut self) -> Vec<BTreeSet<usize>> {
for vertex in 0..self.graph.len() {
if self.state[vertex].index == Self::INVALID_INDEX {
self.visit(vertex);
}
}
self.components
}
fn visit(&mut self, v: usize) {
let v_ref = &mut self.state[v];
v_ref.index = self.index;
v_ref.low_link = self.index;
self.index += 1;
self.stack.push(v);
v_ref.on_stack = true;
for w in self.graph.edges(v) {
let w_ref = &self.state[w];
if w_ref.index == Self::INVALID_INDEX {
self.visit(w);
let w_low_link = self.state[w].low_link;
let v_ref = &mut self.state[v];
v_ref.low_link = v_ref.low_link.min(w_low_link);
} else if w_ref.on_stack {
let w_index = self.state[w].index;
let v_ref = &mut self.state[v];
v_ref.low_link = v_ref.low_link.min(w_index);
}
}
let v_ref = &self.state[v];
if v_ref.low_link == v_ref.index {
let mut component = BTreeSet::new();
loop {
let w = self.stack.pop().unwrap();
self.state[w].on_stack = false;
component.insert(w);
if w == v {
break;
}
}
self.components.push(component);
}
}
}
fn main() {
let graph = {
let mut g = Graph::new(8);
g.add_edge(0, 1);
g.add_edge(2, 0);
g.add_edges(5, vec![2, 6]);
g.add_edge(6, 5);
g.add_edge(1, 2);
g.add_edges(3, vec![1, 2, 4]);
g.add_edges(4, vec![5, 3]);
g.add_edges(7, vec![4, 7, 6]);
g
};
for component in Tarjan::walk(&graph) {
println!("{:?}", component);
}
} |
http://rosettacode.org/wiki/Tarjan | Tarjan |
This page uses content from Wikipedia. The original article was at Graph. 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)
Tarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph.
It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
Tarjan's Algorithm is named for its discoverer, Robert Tarjan.
References
The article on Wikipedia.
| #Sidef | Sidef | func tarjan (k) {
var(:onstack, :index, :lowlink, *stack, *connected)
func strong_connect (vertex, i=0) {
index{vertex} = i
lowlink{vertex} = i+1
onstack{vertex} = true
stack << vertex
for connection in (k{vertex}) {
if (index{connection} == nil) {
strong_connect(connection, i+1)
lowlink{vertex} `min!` lowlink{connection}
}
elsif (onstack{connection}) {
lowlink{vertex} `min!` index{connection}
}
}
if (lowlink{vertex} == index{vertex}) {
var *node
do {
node << stack.pop
onstack{node.tail} = false
} while (node.tail != vertex)
connected << node
}
}
{ strong_connect(_) if !index{_} } << k.keys
return connected
}
var tests = [
Hash(
0 => <1>,
1 => <2>,
2 => <0>,
3 => <1 2 4>,
4 => <3 5>,
5 => <2 6>,
6 => <5>,
7 => <4 6 7>,
),
Hash(
:Andy => <Bart>,
:Bart => <Carl>,
:Carl => <Andy>,
:Dave => <Bart Carl Earl>,
:Earl => <Dave Fred>,
:Fred => <Carl Gary>,
:Gary => <Fred>,
:Hank => <Earl Gary Hank>,
)
]
tests.each {|t|
say ("Strongly connected components: ", tarjan(t).map{.sort}.sort)
} |
http://rosettacode.org/wiki/Teacup_rim_text | Teacup rim text | On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word TEA appears a number of times separated by bullet characters (•).
It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word.
So start at the T and read TEA. Start at the E and read EAT, or start at the A and read ATE.
That got me thinking that maybe there are other words that could be used rather that TEA. And that's just English. What about Italian or Greek or ... um ... Telugu.
For English, we will use the unixdict (now) located at: unixdict.txt.
(This will maintain continuity with other Rosetta Code tasks that also use it.)
Task
Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding AH and HA, for example.)
Having listed a set, for example [ate tea eat], refrain from displaying permutations of that set, e.g.: [eat tea ate] etc.
The words should also be made of more than one letter (thus precluding III and OOO etc.)
The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So ATE becomes TEA and TEA becomes EAT.
All of the possible permutations, using this particular permutation technique, must be words in the list.
The set you generate for ATE will never included the word ETA as that cannot be reached via the first-to-last movement method.
Display one line for each set of teacup rim words.
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
| #Python | Python | '''Teacup rim text'''
from itertools import chain, groupby
from os.path import expanduser
from functools import reduce
# main :: IO ()
def main():
'''Circular anagram groups, of more than one word,
and containing words of length > 2, found in:
https://www.mit.edu/~ecprice/wordlist.10000
'''
print('\n'.join(
concatMap(circularGroup)(
anagrams(3)(
# Reading from a local copy.
lines(readFile('~/mitWords.txt'))
)
)
))
# anagrams :: Int -> [String] -> [[String]]
def anagrams(n):
'''Groups of anagrams, of minimum group size n,
found in the given word list.
'''
def go(ws):
def f(xs):
return [
[snd(x) for x in xs]
] if n <= len(xs) >= len(xs[0][0]) else []
return concatMap(f)(groupBy(fst)(sorted(
[(''.join(sorted(w)), w) for w in ws],
key=fst
)))
return go
# circularGroup :: [String] -> [String]
def circularGroup(ws):
'''Either an empty list, or a list containing
a string showing any circular subset found in ws.
'''
lex = set(ws)
iLast = len(ws) - 1
# If the set contains one word that is circular,
# then it must contain all of them.
(i, blnCircular) = until(
lambda tpl: tpl[1] or (tpl[0] > iLast)
)(
lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
)(
(0, False)
)
return [' -> '.join(allRotations(ws[i]))] if blnCircular else []
# isCircular :: Set String -> String -> Bool
def isCircular(lexicon):
'''True if all of a word's rotations
are found in the given lexicon.
'''
def go(w):
def f(tpl):
(i, _, x) = tpl
return (1 + i, x in lexicon, rotated(x))
iLast = len(w) - 1
return until(
lambda tpl: iLast < tpl[0] or (not tpl[1])
)(f)(
(0, True, rotated(w))
)[1]
return go
# allRotations :: String -> [String]
def allRotations(w):
'''All rotations of the string w.'''
return takeIterate(len(w) - 1)(
rotated
)(w)
# GENERIC -------------------------------------------------
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list over which a function has been mapped.
The list monad can be derived by using a function f which
wraps its output in a list,
(using an empty list to represent computational failure).
'''
def go(xs):
return chain.from_iterable(map(f, xs))
return go
# fst :: (a, b) -> a
def fst(tpl):
'''First member of a pair.'''
return tpl[0]
# groupBy :: (a -> b) -> [a] -> [[a]]
def groupBy(f):
'''The elements of xs grouped,
preserving order, by equality
in terms of the key function f.
'''
def go(xs):
return [
list(x[1]) for x in groupby(xs, key=f)
]
return go
# lines :: String -> [String]
def lines(s):
'''A list of strings,
(containing no newline characters)
derived from a single new-line delimited string.
'''
return s.splitlines()
# mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
def mapAccumL(f):
'''A tuple of an accumulation and a list derived by a
combined map and fold,
with accumulation from left to right.
'''
def go(a, x):
tpl = f(a[0], x)
return (tpl[0], a[1] + [tpl[1]])
return lambda acc: lambda xs: (
reduce(go, xs, (acc, []))
)
# readFile :: FilePath -> IO String
def readFile(fp):
'''The contents of any file at the path
derived by expanding any ~ in fp.
'''
with open(expanduser(fp), 'r', encoding='utf-8') as f:
return f.read()
# rotated :: String -> String
def rotated(s):
'''A string rotated 1 character to the right.'''
return s[1:] + s[0]
# snd :: (a, b) -> b
def snd(tpl):
'''Second member of a pair.'''
return tpl[1]
# takeIterate :: Int -> (a -> a) -> a -> [a]
def takeIterate(n):
'''Each value of n iterations of f
over a start value of x.
'''
def go(f):
def g(x):
def h(a, i):
v = f(a) if i else x
return (v, v)
return mapAccumL(h)(x)(
range(0, 1 + n)
)[1]
return g
return go
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f):
def g(x):
v = x
while not p(v):
v = f(v)
return v
return g
return go
# MAIN ---
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.