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/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Perl | Perl | use ntheory qw/is_square_free moebius/;
sub square_free_count {
my ($n) = @_;
my $count = 0;
foreach my $k (1 .. sqrt($n)) {
$count += moebius($k) * int($n / $k**2);
}
return $count;
}
print "Square─free numbers between 1 and 145:\n";
print join(' ', grep { is_square_free($_) } 1 .. 145), "\n";
print "\nSquare-free numbers between 10^12 and 10^12 + 145:\n";
print join(' ', grep { is_square_free($_) } 1e12 .. 1e12 + 145), "\n";
print "\n";
foreach my $n (2 .. 6) {
my $c = square_free_count(10**$n);
print "The number of square-free numbers between 1 and 10^$n (inclusive) is: $c\n";
} |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #PicoLisp | PicoLisp | (de *Data
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36
29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119
58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127
29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43
117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106
33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27
27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 )
(let L
(group
(mapcar
'((N)
(cons
(or (format (head -1 (setq N (chop N)))) 0)
(last N) ) )
(sort *Data) ) )
(for I (range (caar L) (car (last L)))
(prinl (align 3 I) " | " (glue " " (cdr (assoc I L)))) ) ) |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #AppleScript | AppleScript | intercalate(", ", ¬
map(curry(intercalate)'s |λ|(""), ¬
group("gHHH5YY++///\\")))
--> "g, HHH, 5, YY, ++, ///, \\"
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- curry :: (Script|Handler) -> Script
on curry(f)
script
on |λ|(a)
script
on |λ|(b)
|λ|(a, b) of mReturn(f)
end |λ|
end script
end |λ|
end script
end curry
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- group :: Eq a => [a] -> [[a]]
on group(xs)
script eq
on |λ|(a, b)
a = b
end |λ|
end script
groupBy(eq, xs)
end group
-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
on groupBy(f, xs)
set mf to mReturn(f)
script enGroup
on |λ|(a, x)
if length of (active of a) > 0 then
set h to item 1 of active of a
else
set h to missing value
end if
if h is not missing value and mf's |λ|(h, x) then
{active:(active of a) & x, sofar:sofar of a}
else
{active:{x}, sofar:(sofar of a) & {active of a}}
end if
end |λ|
end script
if length of xs > 0 then
tell foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs))
if length of (its active) > 0 then
its sofar & its active
else
{}
end if
end tell
else
{}
end if
end groupBy
-- 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
-- tail :: [a] -> [a]
on tail(xs)
if length of xs > 1 then
items 2 thru -1 of xs
else
{}
end if
end tail |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Nim | Nim | import math, strformat, strutils
iterator sternBrocot(): (int, int) =
## Yield index and value of the terms of the sequence.
var sequence: seq[int]
sequence.add 1
sequence.add 1
var index = 1
yield (1, 1)
yield (2, 1)
while true:
sequence.add sequence[index] + sequence[index - 1]
yield (sequence.len, sequence[^1])
sequence.add sequence[index]
yield (sequence.len, sequence[^1])
inc index
# Fiind first 15 terms.
var res: seq[int]
for i, n in sternBrocot():
res.add n
if i == 15: break
echo "First 15 terms: ", res.join(" ")
echo()
# Find indexes for 1..10.
var indexes: array[1..10, int]
var toFind = 10
for i, n in sternBrocot():
if n in 1..10 and indexes[n] == 0:
indexes[n] = i
dec toFind
if toFind == 0: break
for n in 1..10:
echo &"Index of first occurrence of number {n:3}: {indexes[n]:4}"
# Find index for 100.
var index: int
for i, n in sternBrocot():
if n == 100:
index = i
break
echo &"Index of first occurrence of number 100: {index:4}"
echo()
# Check GCD.
var prev = 1
index = 1
for i, n in sternBrocot():
if gcd(prev, n) != 1: break
prev = n
inc index
if index > 1000: break
if index <= 1000:
echo "Found two successive terms at index: ", index
else:
echo "All consecutive terms up to the 1000th member have a GCD equal to one." |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Tcl | Tcl | set level 41
set prob 0.5001
proc step {} {
global level prob steps
incr steps
if {rand() < $prob} {
incr level 1
return 1
} else {
incr level -1
return 0
}
} |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #TI-83_BASIC | TI-83 BASIC | If rand>.5:Then
0→C
Disp "FALL"
If A=1:Then
D-1→D
Disp D
End
Else
1→C
Disp "CLIMB"
If A=1:Then
D+1→D
Disp D
End
End
If B=1
Pause |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Wren | Wren | import "random" for Random
import "/fmt" for Conv
var rand = Random.new(1268) // generates short repeatable sequence
var position = 0
var step = Fn.new {
var r = Conv.itob(rand.int(2))
if (r) {
position = position + 1
System.print("Climbed up to %(position)")
} else {
position = position - 1
System.print("Fell down to %(position)")
}
return r
}
var stepUp // recursive
stepUp = Fn.new {
while (!step.call()) stepUp.call()
}
stepUp.call() |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Arturo | Arturo | Stack: $[]-> []
pushTo: function [st val]-> 'st ++ val
popStack: function [st] [
result: last st
remove 'st .index (size st)-1
return result
]
emptyStack: function [st]-> empty 'st
printStack: function [st]-> print st
st: new Stack
pushTo st "one"
pushTo st "two"
pushTo st "three"
printStack st
print popStack st
printStack st
emptyStack st
print ["finally:" st] |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Racket | Racket | #lang racket
(require db file/md5)
(define-logger authentication)
(current-logger authentication-logger)
(define DB-HOST "localhost")
(define DB-USER "devel")
(define DB-PASS "devel")
(define DB-NAME "test")
(define (connect-db)
(mysql-connect
#:user DB-USER
#:database DB-NAME
#:password DB-PASS))
(define (salt+password->hash salt password #:hex-encode? (hex-encode? #f))
(md5 (bytes-append salt password) hex-encode?))
(define (report-sql-error e)
(log-authentication-error "Failed to create user:~s" (exn-message e))
#f)
(define (create-user db username passwd)
; if user was successfully created, returns its ID else #f
(define salt (list->bytes (for/list ((i (in-range 16))) (random 256))))
(define hash (salt+password->hash salt passwd))
(with-handlers ((exn:fail:sql? report-sql-error))
(query db "INSERT INTO users (username, pass_salt, pass_md5) VALUES (?, ?, ?)"
username salt hash)))
(define (authenticate-user db username password)
(or
(match (query-maybe-row db "SELECT pass_salt, pass_md5 FROM users WHERE username = ?" username)
[#f #f]
[(vector salt hash) (bytes=? hash (salt+password->hash salt password))])
; don't let the deviants know whether it's the username or password that's dodgy
(error "the username, password combination does not exist in system")))
(module+ test
(require rackunit)
(define test-DB (connect-db))
; typically, you only do this the once (or risk upsetting your users bigtime!)
; call this just the once!
(define (create-users-table db)
(query-exec db "DROP TABLE IF EXISTS users")
(query-exec db #<<EOS
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
EOS
))
(create-users-table test-DB)
(create-user test-DB #"tim" #"shh! it's a secret!")
; ensure the user exists (for testing purposes)
(check-match (query-list test-DB "SELECT userid FROM users WHERE username = 'tim'") (list _))
; (ah... but tim exists!!!)
(check-false (create-user test-DB #"tim" #"tim's password"))
(check-exn exn:fail? (λ () (authenticate-user test-DB #"tim" #"password")))
(check-true (authenticate-user test-DB #"tim" #"shh! it's a secret!"))) |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Raku | Raku |
use v6;
use DBIish;
multi connect_db(:$dbname, :$host, :$user, :$pass) {
my $db = DBIish.connect("mysql",host => $host, database =>$dbname, user =>$user, password =>$pass, :RaiseError)
or die "ERROR: {DBIish.errstr}.";
$db;
}
multi create_user(:$db, :$user, :$pass) {
#https://stackoverflow.com/questions/53365101/converting-pack-to-perl6
my $salt = Buf.new((^256).roll(16));
my $sth = $db.prepare(q:to/STATEMENT/);
INSERT IGNORE INTO users (username, pass_salt, pass_md5)
VALUES (?, ?, unhex(md5(concat(pass_salt, ?))))
STATEMENT
$sth.execute($user,$salt,$pass);
$sth.insert-id or Any;
}
multi authenticate_user (:$db, :$user, :$pass) {
my $sth = $db.prepare(q:to/STATEMENT/);
SELECT userid FROM users WHERE
username=? AND pass_md5=unhex(md5(concat(pass_salt, ?)))
STATEMENT
$sth.execute($user,$pass);
my $userid = $sth.fetch;
$userid[0] or Any;
} |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #BASIC256 | BASIC256 | say "Goodbye, World for the " + 123456 + "th time."
say "This is an example of speech synthesis." |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Batch_File | Batch File | @set @dummy=0 /*
::Batch File section
@echo off
cscript //e:jscript //nologo "%~f0" "%~1"
exit /b
::*/
//The JScript section
var objVoice = new ActiveXObject("SAPI.SpVoice");
objVoice.speak(WScript.Arguments(0)); |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #BBC_BASIC | BBC BASIC | SPF_ASYNC = 1
ON ERROR SYS `CoUninitialize` : PRINT 'REPORT$ : END
ON CLOSE SYS `CoUninitialize` : QUIT
SYS "LoadLibrary","OLE32.DLL" TO O%
SYS "GetProcAddress",O%,"CoInitialize" TO `CoInitialize`
SYS "GetProcAddress",O%,"CoUninitialize" TO `CoUninitialize`
SYS "GetProcAddress",O%,"CoCreateInstance" TO `CoCreateInstance`
SYS `CoInitialize`,0
voice% = FN_voice_create
PROC_voice_speak(voice%, "This is an example of speech synthesis")
PROC_voice_wait(voice%)
PROC_voice_free(voice%)
SYS `CoUninitialize`
END
DEF FN_voice_create
LOCAL C%, D%, F%, I%, M%, P%, V%
DIM C% LOCAL 15, I% LOCAL 15
C%!0 = &96749377 : C%!4 = &11D23391 : C%!8 = &C000E39E : C%!12 = &9673794F
I%!0 = &6C44DF74 : I%!4 = &499272B9 : I%!8 = &99EFECA1 : I%!12 = &D422046E
SYS `CoCreateInstance`, C%, 0, 5, I%, ^V%
IF V%=0 ERROR 100, "SAPI5 not available"
= V%
DEF PROC_voice_speak(V%, M$)
DIM M% LOCAL 2*LENM$+1
SYS "MultiByteToWideChar", 0, 0, M$, -1, M%, LENM$+1
SYS !(!V%+80), V%, M%, SPF_ASYNC, 0
ENDPROC
DEF PROC_voice_wait(V%)
SYS !(!V%+128), V%
ENDPROC
DEF PROC_voice_free(V%)
SYS !(!V%+8), V%
ENDPROC |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #C | C | #include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void talk(const char *s)
{
pid_t pid;
int status;
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
execlp("espeak", "espeak", s, (void*)0);
perror("espeak");
_exit(1);
}
waitpid(pid, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
exit(1);
}
int main()
{
talk("This is an example of speech synthesis.");
return 0;
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. SQUARE-NOT-CUBE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 COMPUTATION.
02 SQ-ROOT PIC 9999 COMP VALUE 1.
02 CUBE-ROOT PIC 9999 COMP VALUE 1.
02 SQUARE PIC 9999 COMP VALUE 1.
02 CUBE PIC 9999 COMP VALUE 1.
02 SEEN PIC 99 COMP VALUE 0.
01 OUTPUT-FORMAT.
02 OUT-NUM PIC ZZZ9.
PROCEDURE DIVISION.
SQUARE-STEP.
COMPUTE SQUARE = SQ-ROOT ** 2.
CUBE-STEP.
IF SQUARE IS GREATER THAN CUBE
ADD 1 TO CUBE-ROOT
COMPUTE CUBE = CUBE-ROOT ** 3
GO TO CUBE-STEP.
IF SQUARE IS NOT EQUAL TO CUBE
ADD 1 TO SEEN
MOVE SQUARE TO OUT-NUM
DISPLAY OUT-NUM.
ADD 1 TO SQ-ROOT.
IF SEEN IS LESS THAN 30 GO TO SQUARE-STEP.
STOP RUN. |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Julia | Julia | using Printf
function hist(numbers)
maxwidth = 50
h = fill(0, 10)
for n in numbers
h[ceil(Int, 10n)] += 1
end
mx = maximum(h)
for (n, i) in enumerate(h)
@printf("%3.1f: %s\n", n / 10, "+" ^ floor(Int, i / mx * maxwidth))
end
end
for i in 1:6
n = rand(10 ^ i)
println("\n##\n## $(10 ^ i) numbers")
@printf("μ: %8.6f; σ: %8.6f\n", mean(n), std(n))
hist(n)
end |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Klong | Klong |
.l("nstat.kg")
bar::{x{x;.d("*")}:*0;.p("")}
hist10::{[s];#'=s@<s::_x*10}
plot::{[s];.p("");.p("n = ",$x);
(!10){.d(x%10);.d(" ");bar(y)}'_(100%x)*(hist10(s::{x;.rn()}'!x));
.p("mean = ",$mu(s));.p("sd = ",$sd(s))}
plot(100)
plot(1000)
plot(10000)
|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Phix | Phix | with javascript_semantics
function square_frees(atom start, finish)
sequence res = {}
integer maxprime = get_maxprime(finish)
while start<=finish do
if square_free(start,maxprime) then
res &= start
end if
start += 1
end while
return res
end function
procedure show_range(atom start, finish, integer jb, string fmt)
sequence res = square_frees(start, finish)
printf(1,"There are %d square-free integers from %,d to %,d:\n%s\n",
{length(res),start,finish,join_by(res,1,jb,"","\n",fmt)})
end procedure
show_range(1,145,20,"%4d")
show_range(1e12,1e12+145,5,"%14d")
printf(1,"\nNumber of square-free integers:\n");
for i=2 to 6 do
integer lim = power(10,i),
len = length(square_frees(1,lim))
printf(1," from %,d to %,d = %,d\n", {1,lim,len})
end for
|
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #PowerShell | PowerShell |
$Set = -split '12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146'
$Data = $Set | Select @{ Label = 'Stem'; Expression = { [string][int]$_.Substring( 0, $_.Length - 1 ) } }, @{ Label = 'Leaf'; Expression = { [string]$_[-1] } }
$StemStats = $Data | Measure-Object -Property Stem -Minimum -Maximum
ForEach ( $Stem in $StemStats.Minimum..$StemStats.Maximum )
{
@( $Stem.ToString().PadLeft( 2, " " ), '|' ) + ( ( $Data | Where Stem -eq $Stem ).Leaf | Sort ) -join " "
}
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program splitcar.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szCarriageReturn: .asciz "\n"
szString1: .asciz "gHHH5YY++///\\"
/* IMPORTANT REMARK for compiler as
The way to get special characters into a string is to escape these characters: precede them
with a backslash ‘\’ character. For example ‘\\’ represents one backslash: the first \ is
an escape which tells as to interpret the second character literally as a backslash (which
prevents as from recognizing the second \ as an escape character).
*/
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sBuffer: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszString1 @ input string address
ldr r1,iAdrsBuffer @ output buffer address
bl split
ldr r0,iAdrsBuffer
bl affichageMess @ display message
ldr r0,iAdrszCarriageReturn
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszString1: .int szString1
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsBuffer: .int sBuffer
/******************************************************************/
/* generate value */
/******************************************************************/
/* r0 contains the address of input string */
/* r1 contains the address of output buffer */
split:
push {r1-r5,lr} @ save registers
mov r4,#0 @ indice loop input string
mov r5,#0 @ indice buffer
ldrb r2,[r0,r4] @ read first char in reg r2
cmp r2,#0 @ if null -> end
beq 3f
strb r2,[r1,r5] @ store char in buffer
add r5,#1 @ increment location buffer
1:
ldrb r3,[r0,r4] @read char[r4] in reg r3
cmp r3,#0 @ if null end
beq 3f
cmp r2,r3 @ compare two characters
streqb r3,[r1,r5] @ = -> store char in buffer
beq 2f @ loop
mov r2,#',' @ else store comma in buffer
strb r2,[r1,r5] @ store char in buffer
add r5,#1
mov r2,#' ' @ and store space in buffer
strb r2,[r1,r5]
add r5,#1
strb r3,[r1,r5] @ and store input char in buffer
mov r2,r3 @ and maj r2 with new char
2:
add r5,#1 @ increment indices
add r4,#1
b 1b @ and loop
3:
strb r3,[r1,r5] @ store zero final in buffer
100:
pop {r1-r5,lr}
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
output : gg, HHH, 5, YY, ++, ///, \
|
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Oforth | Oforth | : stern(n)
| l i |
ListBuffer new dup add(1) dup add(1) dup ->l
n 1- 2 / loop: i [ l at(i) l at(i 1+) tuck + l add l add ]
n 2 mod ifFalse: [ dup removeLast drop ] dup freeze ;
stern(10000) Constant new: Sterns |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #XPL0 | XPL0 | proc Step_up; \Iterative version
int I;
[I:= 0;
while I<1 do
if Step then I:= I+1
else I:= I-1;
];
proc Step_up; \Recursive version
while not Step do Step_up; |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #zkl | zkl | fcn step{ } // add code to return Bool
fcn stepUp{ while(not step()){ self.fcn() } } |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #11l | 11l | L
L(rod) ‘\|/-’
print(rod, end' "\r")
sleep(0.25) |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ATS | ATS | (* Stacks implemented as linked lists. *)
(* A nonlinear stack type of size n, which is good for when you are
using a garbage collector or can let the memory leak. *)
typedef stack_t (t : t@ype+, n : int) = list (t, n)
typedef stack_t (t : t@ype+) = [n : int] stack_t (t, n)
(* A linear stack type of size n, which requires (and will enforce)
explicit freeing. (Note that a "peek" function for a linear stack
is a complicated topic. But the task avoids this issue.) *)
viewtypedef stack_vt (vt : vt@ype+, n : int) = list_vt (vt, n)
viewtypedef stack_vt (vt : vt@ype+) = [n : int] stack_vt (vt, n)
(* Proof that a given nonlinear stack does not have a nonnegative
size. *)
prfn
lemma_stack_t_param {n : int} {t : t@ype}
(stack : stack_t (t, n)) :<prf>
[0 <= n] void =
lemma_list_param stack
(* Proof that a given linear stack does not have a nonnegative
size. *)
prfn
lemma_stack_vt_param {n : int} {vt : vt@ype}
(stack : !stack_vt (vt, n)) :<prf>
[0 <= n] void =
lemma_list_vt_param stack
(* Create an empty nonlinear stack. *)
fn {}
stack_t_nil {t : t@ype} () :<> stack_t (t, 0) =
list_nil ()
(* Create an empty linear stack. *)
fn {}
stack_vt_nil {vt : vt@ype} () :<> stack_vt (vt, 0) =
list_vt_nil ()
(* Is a nonlinear stack empty? *)
fn {}
stack_t_is_empty {n : int} {t : t@ype}
(stack : stack_t (t, n)) :<>
[empty : bool | empty == (n == 0)]
bool empty =
case+ stack of
| list_nil _ => true
| list_cons _ => false
(* Is a linear stack empty? *)
fn {}
stack_vt_is_empty {n : int} {vt : vt@ype}
(* ! = pass by value; stack is preserved. *)
(stack : !stack_vt (vt, n)) :<>
[empty : bool | empty == (n == 0)]
bool empty =
case+ stack of
| list_vt_nil _ => true
| list_vt_cons _ => false
(* Push to a nonlinear stack that is stored in a variable. *)
fn {t : t@ype}
stack_t_push {n : int}
(stack : &stack_t (t, n) >> stack_t (t, m),
x : t) :<!wrt>
(* It is proved that the stack is raised one higher. *)
#[m : int | 1 <= m; m == n + 1]
void =
let
prval _ = lemma_stack_t_param stack
prval _ = prop_verify {0 <= n} ()
in
stack := list_cons (x, stack)
end
(* Push to a linear stack that is stored in a variable. Beware: if x
is linear, it is consumed. *)
fn {vt : vt@ype}
stack_vt_push {n : int}
(stack : &stack_vt (vt, n) >> stack_vt (vt, m),
x : vt) :<!wrt>
(* It is proved that the stack is raised one higher. *)
#[m : int | 1 <= m; m == n + 1]
void =
let
prval _ = lemma_stack_vt_param stack
prval _ = prop_verify {0 <= n} ()
in
stack := list_vt_cons (x, stack)
end
(* Pop from a nonlinear stack that is stored in a variable. It is
impossible (unless you cheat the typechecker) to pop from an empty
stack. *)
fn {t : t@ype}
stack_t_pop {n : int | 1 <= n}
(stack : &stack_t (t, n) >> stack_t (t, m)) :<!wrt>
(* It is proved that the stack is lowered by one. *)
#[m : int | m == n - 1]
t =
case+ stack of
| list_cons (x, tail) =>
begin
stack := tail;
x
end
(* Pop from a linear stack that is stored in a variable. It is
impossible (unless you cheat the typechecker) to pop from an empty
stack. *)
fn {vt : vt@ype}
stack_vt_pop {n : int | 1 <= n}
(stack : &stack_vt (vt, n) >> stack_vt (vt, m)) :<!wrt>
(* It is proved that the stack is lowered by one. *)
#[m : int | m == n - 1]
vt =
case+ stack of
| ~ list_vt_cons (x, tail) => (* ~ = the top node is consumed. *)
begin
stack := tail;
x
end
(* A linear stack has to be consumed. *)
extern fun {vt : vt@ype}
stack_vt_free$element_free (x : vt) :<> void
fn {vt : vt@ype}
stack_vt_free {n : int}
(stack : stack_vt (vt, n)) :<> void =
let
fun
loop {m : int | 0 <= m}
.<m>. (* <-- proof of loop termination *)
(stk : stack_vt (vt, m)) :<> void =
case+ stk of
| ~ list_vt_nil () => begin end
| ~ list_vt_cons (x, tail) =>
begin
stack_vt_free$element_free x;
loop tail
end
prval _ = lemma_stack_vt_param stack
in
loop stack
end
implement
main0 () =
let
var nonlinear_stack : stack_t (int) = stack_t_nil ()
var linear_stack : stack_vt (int) = stack_vt_nil ()
implement stack_vt_free$element_free<int> x = begin end
overload is_empty with stack_t_is_empty
overload is_empty with stack_vt_is_empty
overload push with stack_t_push
overload push with stack_vt_push
overload pop with stack_t_pop
overload pop with stack_vt_pop
in
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
println! ("pushing 3, 2, 1...");
push (nonlinear_stack, 3);
push (nonlinear_stack, 2);
push (nonlinear_stack, 1);
push (linear_stack, 3);
push (linear_stack, 2);
push (linear_stack, 1);
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
stack_vt_free<int> linear_stack
end |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Raven | Raven | 'mysql://root@localhost/test' open as mysql
'abcdefghijklmnopqrstuvwxyz0123456789' as $salt_chars
# return userid for success and FALSE for failure.
define create_user use $user, $pass
group 16 each as i
$salt_chars choose chr
join as $pass_salt
"%($pass_salt)s%($pass)s" md5 as $pass_md5
$user copy mysql escape as $user_name
group 'INSERT IGNORE into users (username, pass_md5, pass_salt)'
" VALUES ('%($user_name)s', unhex('%($pass_md5)s'), '%($pass_salt)s')"
join mysql query inserted
# return userid for success and FALSE for failure.
define authenticate_user use $user, $pass
FALSE as $userid
$user copy mysql escape as $user_name
group 'SELECT userid, pass_salt, hex(pass_md5)'
" FROM users WHERE username = '%($user_name)s'"
join mysql query as rs
rs selected
if rs fetch values into $possible_userid, $pass_salt, $pass_md5
"%($pass_salt)s%($pass)s" md5 $pass_md5 lower =
if $possible_userid as $userid
$userid
'foo' 'bar' create_user !if "could not create user\n" print bye
'foo' 'bar' authenticate_user !if "could not authenticate user\n" print bye
"user successfully created and authenticated!\n" print |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Ruby | Ruby | require 'mysql2'
require 'securerandom'
require 'digest'
def connect_db(host, port = nil, username, password, db)
Mysql2::Client.new(
host: host,
port: port,
username: username,
password: password,
database: db
)
end
def create_user(client, username, password)
salt = SecureRandom.random_bytes(16)
password_md5 = Digest::MD5.hexdigest(salt + password)
statement = client.prepare('INSERT INTO users (username, pass_salt, pass_md5) VALUES (?, ?, ?)')
statement.execute(username, salt, password_md5)
statement.last_id
end
def authenticate_user(client, username, password)
user_record = client.prepare("SELECT SELECT pass_salt, pass_md5 FROM users WHERE username = '#{client.escape(username)}'").first
return false unless user_record
password_md5 = Digest::MD5.hexdigest(user_record['pass_salt'] + password)
password_md5 == user_record['pass_md5']
end |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #C.23 | C# | using SpeechLib;
namespace Speaking_Computer
{
public class Program
{
private static void Main()
{
var voice = new SpVoice();
voice.Speak("This is an example of speech synthesis.");
}
}
} |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Clojure | Clojure | (use 'speech-synthesis.say)
(say "This is an example of speech synthesis.") |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #FreeBASIC | FreeBASIC | ''This works on Windows. Does anyone know how it would be done in Linux?
Sub speak(texto As String)
Dim As String frase
frase ="mshta vbscript:Execute(""CreateObject(""""SAPI.SpVoice"""").Speak("""""+texto+""""")(window.close)"")"
Print texto
Shell frase
End Sub
speak "Vamos a contar " + str(123456)
speak "This is an example of speech synthesis."
Sleep |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Comal | Comal | 0010 ZONE 5
0020 cube_n#:=0;square_n#:=0;seen#:=0
0030 WHILE seen#<30 DO
0040 WHILE cube_n#^3<square_n#^2 DO cube_n#:+1
0050 IF cube_n#^3<>square_n#^2 THEN
0060 PRINT square_n#^2,
0070 seen#:+1
0080 IF seen# MOD 5=0 THEN PRINT
0090 ENDIF
0100 square_n#:+1
0110 ENDWHILE
0120 END |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Commodore_BASIC | Commodore BASIC | 100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES
110 PRINT "SQUARES BUT NOT CUBES:"
120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND
130 SR = 1: REM CURRENT SQUARE ROOT
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE
150 REM BEGIN LOOP
160 : IF N >= 30 THEN 230
170 : SQ = SR * SR
180 : IF SQ > CU THEN CR = CR + 1: CU = CR*CR*CR: GOTO 180
190 : IF SQ = CU THEN SC(SC) = SQ: SC = SC + 1
200 : IF SQ < CU THEN N = N + 1:PRINT SQ,
210 : SR = SR + 1
220 GOTO 160: REM END LOOP
230 PRINT: PRINT
240 PRINT "BOTH SQUARES AND CUBES:"
250 FOR I=0 TO SC-1: PRINT SC(I),: NEXT I
260 PRINT |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Kotlin | Kotlin | // version 1.1.2
val rand = java.util.Random()
fun basicStats(sampleSize: Int) {
if (sampleSize < 1) return
val r = DoubleArray(sampleSize)
val h = IntArray(10) // all zero by default
/*
Generate 'sampleSize' random numbers in the interval [0, 1)
and calculate in which box they will fall when drawing the histogram
*/
for (i in 0 until sampleSize) {
r[i] = rand.nextDouble()
h[(r[i] * 10).toInt()]++
}
// adjust one of the h[] values if necessary to ensure they sum to sampleSize
val adj = sampleSize - h.sum()
if (adj != 0) {
for (i in 0..9) {
h[i] += adj
if (h[i] >= 0) break
h[i] -= adj
}
}
val mean = r.average()
val sd = Math.sqrt(r.map { (it - mean) * (it - mean) }.average())
// Draw a histogram of the data with interval 0.1
var numStars: Int
// If sample size > 500 then normalize histogram to 500
val scale = if (sampleSize <= 500) 1.0 else 500.0 / sampleSize
println("Sample size $sampleSize\n")
println(" Mean ${"%1.6f".format(mean)} SD ${"%1.6f".format(sd)}\n")
for (i in 0..9) {
print(" %1.2f : ".format(i / 10.0))
print("%5d ".format(h[i]))
numStars = (h[i] * scale + 0.5).toInt()
println("*".repeat(numStars))
}
println()
}
fun main(args: Array<String>) {
val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000)
for (sampleSize in sampleSizes) basicStats(sampleSize)
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Python | Python |
import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ): # Create a custom prime sieve
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".format(i), end="" )
count += 1
print ( "\n\nTotal count of square-free numbers between {} and {}: {}".format(_start, _end, count))
ListSquareFrees( 1, 100 )
ListSquareFrees( 1000000000000, 1000000000145 )
|
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #PureBasic | PureBasic | If OpenConsole()
Dim MyList(120)
Define i, j, StemMax, StemMin
Restore MyData ; Get the address of MyData, e.g. the data to print as a Stem-and-leaf plot
For a=0 To 120
Read.i MyList(a) ; Read the data into the used Array
If MyList(a)>StemMax
StemMax=MyList(a) ; Find the largest Stem layer at the same time
EndIf
If MyList(a)<StemMin
StemMin=MyList(a) ; Find the smallest Stem layer at the same time
EndIf
Next
StemMax/10: StemMin/10 ; Remove the leafs from the Stem limits
SortArray(MyList(),#PB_Sort_Ascending) ; Sort the data
For i=StemMin To StemMax
Print(RSet(Str(i),3)+" | ") ; Print the Stem
For j=0 To 120
If MyList(j)<10*i ; Skip all smaller then current
Continue
ElseIf MyList(j)>=10*(i+1) ; Break current print if a new Stem layer is reached
Break
Else
Print(Str(MyList(j)%10)+" ") ; Print all Leafs on this current Stem layer
EndIf
Next j
PrintN("")
Next i
Print(#CRLF$+#CRLF$+"Press ENTER to exit")
Input()
CloseConsole()
EndIf
DataSection
MyData:
Data.i 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115
Data.i 105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125
Data.i 32, 61, 37,127, 29,113,121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116
Data.i 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117,116,111, 40,119, 47,105
Data.i 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146
EndDataSection |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Arturo | Arturo | parts: [] current: ""
loop split {gHHH5YY++///\} 'ch [
if? or? empty? current
contains? current ch -> 'current ++ ch
else [
'parts ++ current
current: new ch
]
]
'parts ++ current
print parts |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #AutoHotkey | AutoHotkey | Split_Change(str){
for i, v in StrSplit(str)
res .= (v=prev) ? v : (res?", " :"") v , prev := v
return res
} |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #PARI.2FGP | PARI/GP |
\\ Stern-Brocot sequence
\\ 5/27/16 aev
SternBrocot(n)={
my(L=List([1,1]),k=2); if(n<3,return(L));
for(i=2,n, listput(L,L[i]+L[i-1]); if(k++>=n, break); listput(L,L[i]);if(k++>=n, break));
return(Vec(L));
}
\\ Find the first item in any list starting with sind index (return 0 or index).
\\ 9/11/2015 aev
findinlist(list, item, sind=1)={
my(idx=0, ln=#list); if(ln==0 || sind<1 || sind>ln, return(0));
for(i=sind, ln, if(list[i]==item, idx=i; break;)); return(idx);
}
{
\\ Required tests:
my(v,j);
v=SternBrocot(15);
print1("The first 15: "); print(v);
v=SternBrocot(1200);
print1("The first i@n: "); \\print(v);
for(i=1,10, if(j=findinlist(v,i), print1(i,"@",j,", ")));
if(j=findinlist(v,100), print(100,"@",j));
v=SternBrocot(10000);
print1("All GCDs=1?: ");
j=1; for(i=2,10000, j*=gcd(v[i-1],v[i]));
if(j==1, print("Yes"), print("No"));
}
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
CHAR ARRAY spin="|/-\"
BYTE i,
CH=$02FC, ;Internal hardware value for last key pressed
CRSINH=$02F0 ;Controls visibility of cursor
Print("Press any key to exit...")
CRSINH=1 ;hide cursor
i=1
WHILE CH=$FF
DO
Put(spin(i))
Put(30) ;move cursor left
i==+1
IF i>spin(0) THEN
i=1
FI
Wait(5)
OD
CH=$FF
CRSINH=0 ;show cursor
RETURN |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Ada | Ada | with Ada.Text_IO;
procedure Spinning_Rod is
use Ada.Text_IO;
type Index_Type is mod 4;
Rod : constant array (Index_Type) of Character := ('|', '/', '-', '\');
Index : Index_Type := 0;
Char : Character;
Avail : Boolean;
begin
Put (ASCII.ESC & "[?25l"); -- Hide the cursor
loop
Put (ASCII.ESC & "[2J"); -- Clear Terminal
Put (ASCII.ESC & "[0;0H"); -- Place Cursor at Top Left Corner
Get_Immediate (Char, Avail);
exit when Avail;
Put (Rod (Index));
Index := Index_Type'Succ (Index);
delay 0.250;
end loop;
Put (ASCII.ESC & "[?25h"); -- Restore the cursor
end Spinning_Rod; |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #AutoHotkey | AutoHotkey | msgbox % stack("push", 4)
msgbox % stack("push", 5)
msgbox % stack("peek")
msgbox % stack("pop")
msgbox % stack("peek")
msgbox % stack("empty")
msgbox % stack("pop")
msgbox % stack("empty")
return
stack(command, value = 0)
{
static
if !pointer
pointer = 10000
if (command = "push")
{
_p%pointer% := value
pointer -= 1
return value
}
if (command = "pop")
{
pointer += 1
return _p%pointer%
}
if (command = "peek")
{
next := pointer + 1
return _p%next%
}
if (command = "empty")
{
if (pointer == 10000)
return "empty"
else
return 0
}
} |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Sidef | Sidef | require('DBI')
# returns a database handle configured to throw an exception on query errors
func connect_db(dbname, host, user, pass) {
var db = %s<DBI>.connect("dbi:mysql:#{dbname}:#{host}", user, pass)
db || die (global DBI::errstr)
db{:RaiseError} = 1
db
}
# if the user was successfully created, returns its user id.
# if the name was already in use, returns nil.
func create_user(db, user, pass) {
var salt = "C*".pack(16.of { 256.irand }...)
db.do(
"INSERT IGNORE INTO users (username, pass_salt, pass_md5)
VALUES (?, ?, unhex(md5(concat(pass_salt, ?))))", nil, user, salt, pass
) ? db{:mysql_insertid} : nil
}
# if the user is authentic, returns its user id. otherwise returns nil.
func authenticate_user(db, user, pass) {
db.selectrow_array("SELECT userid FROM users WHERE
username=? AND pass_md5=unhex(md5(concat(pass_salt, ?)))",
nil, user, pass
)
} |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Tcl | Tcl | package require tdbc
proc connect_db {handleName dbname host user pass} {
package require tdbc::mysql
tdbc::mysql::connection create $handleName -user $user -passwd $pass \
-host $host -database $dbname
return $handleName
}
# A simple helper to keep code shorter
proc r64k {} {
expr int(65536*rand())
}
proc create_user {handle user pass} {
set salt [binary format ssssssss \
[r64k] [r64k] [r64k] [r64k] [r64k] [r64k] [r64k] [r64k]]
# Note that we are using named parameters below, :user :salt :pass
# They are bound automatically to local variables with the same name
$handle allrows {
INSERT IGNORE INTO users (username, pass_salt, pass_md5)
VALUES (:user, :salt, unhex(md5(concat(:salt, :pass))))
}
return ;# Ignore the result of the allrows method
}
proc authenticate_user {handle user pass} {
$handle foreach row {
SELECT userid FROM users WHERE
username=:user AND pass_md5=unhex(md5(concat(pass_salt, :pass)))
} {
return [dict get $row userid]
}
# Only get here if no rows selected
error "authentication failed for user \"$user\""
} |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #GlovePIE | GlovePIE | if var.number=0 then
var.number=1
say("This is an example of speech synthesis.")
endif |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Go | Go | package main
import (
"go/build"
"log"
"path/filepath"
"github.com/unixpickle/gospeech"
"github.com/unixpickle/wav"
)
const pkgPath = "github.com/unixpickle/gospeech"
const input = "This is an example of speech synthesis."
func main() {
p, err := build.Import(pkgPath, ".", build.FindOnly)
if err != nil {
log.Fatal(err)
}
d := filepath.Join(p.Dir, "dict/cmudict-IPA.txt")
dict, err := gospeech.LoadDictionary(d)
if err != nil {
log.Fatal(err)
}
phonetics := dict.TranslateToIPA(input)
synthesized := gospeech.DefaultVoice.Synthesize(phonetics)
wav.WriteFile(synthesized, "output.wav")
} |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Groovy | Groovy | 'say "This is an example of speech synthesis."'.execute() |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Common_Lisp | Common Lisp | (defun cubep (n)
(loop for i from 1
for c = (* i i i)
while (<= c n)
when (= c n) do (return t)
finally (return nil)))
(defparameter squares (let ((n 0)) (lambda () (incf n) (* n n))))
(destructuring-bind (noncubes cubes)
(loop for s = (funcall squares) then (funcall squares)
while (< (length noncubes) 30)
if (cubep s) collect s into cubes
if (not (cubep s)) collect s into noncubes
finally (return (list noncubes cubes)))
(format t "Squares but not cubes:~%~A~%~%" noncubes)
(format t "Both squares and cubes:~%~A~%~%" cubes)) |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Lasso | Lasso | define stat1(a) => {
if(#a->size) => {
local(mean = (with n in #a sum #n) / #a->size)
local(sdev = math_pow(((with n in #a sum Math_Pow((#n - #mean),2)) / #a->size),0.5))
return (:#sdev, #mean)
else
return (:0,0)
}
}
define stat2(a) => {
if(#a->size) => {
local(sx = 0, sxx = 0)
with x in #a do => {
#sx += #x
#sxx += #x*#x
}
local(sdev = math_pow((#a->size * #sxx - #sx * #sx),0.5) / #a->size)
return (:#sdev, #sx / #a->size)
else
return (:0,0)
}
}
define histogram(a) => {
local(
out = '\r',
h = array(0,0,0,0,0,0,0,0,0,0,0),
maxwidth = 50,
sc = 0
)
with n in #a do => {
#h->get(integer(#n*10)+1) += 1
}
local(mx = decimal(with n in #h max #n))
with i in #h do => {
#out->append((#sc/10.0)->asString(-precision=1)+': '+('+' * integer(#i / #mx * #maxwidth))+'\r')
#sc++
}
return #out
}
with scale in array(100,1000,10000,100000) do => {^
local(n = array)
loop(#scale) => { #n->insert(decimal_random) }
local(sdev1,mean1) = stat1(#n)
local(sdev2,mean2) = stat2(#n)
#scale' numbers:\r'
'Naive method: sd: '+#sdev1+', mean: '+#mean1+'\r'
'Second method: sd: '+#sdev2+', mean: '+#mean2+'\r'
histogram(#n)
'\r\r'
^} |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Liberty_BASIC | Liberty BASIC |
call sample 100
call sample 1000
call sample 10000
end
sub sample n
dim dat( n)
for i =1 to n
dat( i) =rnd( 1)
next i
'// show mean, standard deviation
sum =0
sSq =0
for i =1 to n
sum =sum +dat( i)
sSq =sSq +dat( i)^2
next i
print n; " data terms used."
mean =sum / n
print "Mean ="; mean
print "Stddev ="; ( sSq /n -mean^2)^0.5
'// show histogram
nBins =10
dim bins( nBins)
for i =1 to n
z =int( nBins *dat( i))
bins( z) =bins( z) +1
next i
for b =0 to nBins -1
for j =1 to int( nBins *bins( b)) /n *70)
print "#";
next j
print
next b
print
end sub
|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Racket | Racket | #lang racket
(define (not-square-free-set-for-range range-min (range-max (add1 range-min)))
(for*/set ((i2 (sequence-map sqr (in-range 2 (add1 (integer-sqrt range-max)))))
(i2.x (in-range (* i2 (quotient range-min i2))
(* i2 (add1 (quotient range-max i2)))
i2))
#:when (and (<= range-min i2.x)
(< i2.x range-max)))
i2.x))
(define (square-free? n #:table (table (not-square-free-set-for-range n)))
(not (set-member? table n)))
(define (count-square-free-numbers #:range-min (range-min 1) range-max)
(- range-max range-min (set-count (not-square-free-set-for-range range-min range-max))))
(define ((print-list-to-width w) l)
(let loop ((l l) (x 0))
(if (null? l)
(unless (zero? x) (newline))
(let* ((str (~a (car l))) (len (string-length str)))
(cond [(<= (+ len x) w) (display str) (write-char #\space) (loop (cdr l) (+ x len 1))]
[(zero? x) (displayln str) (loop (cdr l) 0)]
[else (newline) (loop l 0)])))))
(define print-list-to-80 (print-list-to-width 80))
(module+ main
(print-list-to-80 (for/list ((n (in-range 1 (add1 145))) #:when (square-free? n)) n))
(print-list-to-80 (time (let ((table (not-square-free-set-for-range #e1e12 (add1 (+ #e1e12 145)))))
(for/list ((n (in-range #e1e12 (add1 (+ #e1e12 145))))
#:when (square-free? n #:table table)) n))))
(displayln "Compare time taken without the table (rather with table on the fly):")
(void (time (for/list ((n (in-range #e1e12 (add1 (+ #e1e12 145)))) #:when (square-free? n)) n)))
(count-square-free-numbers 100)
(count-square-free-numbers 1000)
(count-square-free-numbers 10000)
(count-square-free-numbers 100000)
(count-square-free-numbers 1000000)) |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Raku | Raku | # Prime factorization routines
sub prime-factors ( Int $n where * > 0 ) {
return $n if $n.is-prime;
return [] if $n == 1;
my $factor = find-factor( $n );
flat prime-factors( $factor ), prime-factors( $n div $factor );
}
sub find-factor ( Int $n, $constant = 1 ) {
return 2 unless $n +& 1;
if (my $gcd = $n gcd 6541380665835015) > 1 {
return $gcd if $gcd != $n
}
my $x = 2;
my $rho = 1;
my $factor = 1;
while $factor == 1 {
$rho *= 2;
my $fixed = $x;
for ^$rho {
$x = ( $x * $x + $constant ) % $n;
$factor = ( $x - $fixed ) gcd $n;
last if 1 < $factor;
}
}
$factor = find-factor( $n, $constant + 1 ) if $n == $factor;
$factor;
}
# Task routine
sub is-square-free (Int $n) { my @v = $n.&prime-factors.Bag.values; @v.sum/@v <= 1 }
# The Task
# Parts 1 & 2
for 1, 145, 1e12.Int, 145+1e12.Int -> $start, $end {
say "\nSquare─free numbers between $start and $end:\n",
($start .. $end).hyper(:4batch).grep( &is-square-free ).list.fmt("%3d").comb(84).join("\n");
}
# Part 3
for 1e2, 1e3, 1e4, 1e5, 1e6 {
say "\nThe number of square─free numbers between 1 and {$_} (inclusive) is: ",
+(1 .. .Int).race.grep: &is-square-free;
} |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #Python | Python | from collections import namedtuple
from pprint import pprint as pp
from math import floor
Stem = namedtuple('Stem', 'data, leafdigits')
data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37,
48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35,
113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99,
41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114,
126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116,
27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27,
106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115,
43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120,
30, 127, 31, 116, 146),
1.0)
def stemplot(stem):
d = []
interval = int(10**int(stem.leafdigits))
for data in sorted(stem.data):
data = int(floor(data))
stm, lf = divmod(data,interval)
d.append( (int(stm), int(lf)) )
stems, leafs = list(zip(*d))
stemwidth = max(len(str(x)) for x in stems)
leafwidth = max(len(str(x)) for x in leafs)
laststem, out = min(stems) - 1, []
for s,l in d:
while laststem < s:
laststem += 1
out.append('\n%*i |' % ( stemwidth, laststem))
out.append(' %0*i' % (leafwidth, l))
out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n'
% (interval, interval))
return ''.join(out)
if __name__ == '__main__':
print( stemplot(data0) ) |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #AWK | AWK |
# syntax: GAWK -f SPLIT_A_CHARACTER_STRING_BASED_ON_CHANGE_OF_CHARACTER.AWK
BEGIN {
str = "gHHH5YY++///\\"
printf("old: %s\n",str)
printf("new: %s\n",split_on_change(str))
exit(0)
}
function split_on_change(str, c,i,new_str) {
new_str = substr(str,1,1)
for (i=2; i<=length(str); i++) {
c = substr(str,i,1)
if (substr(str,i-1,1) != c) {
new_str = new_str ", "
}
new_str = new_str c
}
return(new_str)
}
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #BaCon | BaCon | txt$ = "gHHH5YY++///\\"
c$ = LEFT$(txt$, 1)
FOR x = 1 TO LEN(txt$)
d$ = MID$(txt$, x, 1)
IF d$ <> c$ THEN
PRINT ", ";
c$ = d$
END IF
PRINT d$;
NEXT |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Pascal | Pascal | program StrnBrCt;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
const
MaxCnt = 10835282;{ seq[i] < 65536 = high(Word) }
//MaxCnt = 500*1000*1000;{ 2Gbyte -> real 0.85 s user 0.31 }
type
tSeqdata = word;//cardinal LongWord
pSeqdata = pWord;//pcardinal pLongWord
tseq = array of tSeqdata;
function SternBrocotCreate(size:NativeInt):tseq;
var
pSeq,pIns : pSeqdata;
PosIns : NativeInt;
sum : tSeqdata;
Begin
setlength(result,Size+1);
dec(Size); //== High(result)
pIns := @result[size];// set at end
PosIns := -size+2; // negative index campare to 0
pSeq := @result[0];
sum := 1;
pSeq[0]:= sum;pSeq[1]:= sum;
repeat
pIns[PosIns+1] := sum;//append copy of considered
inc(sum,pSeq[0]);
pIns[PosIns ] := sum;
inc(pSeq);
inc(PosIns,2);sum := pSeq[1];//aka considered
until PosIns>= 0;
setlength(result,length(result)-1);
end;
function FindIndex(const s:tSeq;value:tSeqdata):NativeInt;
Begin
result := 0;
while result <= High(s) do
Begin
if s[result] = value then
EXIT(result+1);
inc(result);
end;
end;
function gcd_iterative(u, v: NativeInt): NativeInt;
//http://rosettacode.org/wiki/Greatest_common_divisor#Pascal_.2F_Delphi_.2F_Free_Pascal
var
t: NativeInt;
begin
while v <> 0 do begin
t := u;u := v;v := t mod v;
end;
gcd_iterative := abs(u);
end;
var
seq : tSeq;
i : nativeInt;
Begin
seq:= SternBrocotCreate(MaxCnt);
// Show the first fifteen members of the sequence.
For i := 0 to 13 do write(seq[i],',');writeln(seq[14]);
//Show the (1-based) index of where the numbers 1-to-10 first appears in the
For i := 1 to 10 do
write(i,' @ ',FindIndex(seq,i),',');
writeln(#8#32);
//Show the (1-based) index of where the number 100 first appears in the sequence.
writeln(100,' @ ',FindIndex(seq,100));
//Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
i := 999;
if i > High(seq) then
i := High(seq);
Repeat
IF gcd_iterative(seq[i],seq[i+1]) <>1 then
Begin
writeln(' failure at ',i+1,' ',seq[i],' ',seq[i+1]);
BREAK;
end;
dec(i);
until i <0;
IF i< 0 then
writeln('GCD-test is O.K.');
setlength(seq,0);
end. |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #ALGOL_68 | ALGOL 68 | FOR i TO 1 000 DO # increase/decrease the TO value for a longer/shorter animation #
FOR d TO 2 000 000 DO SKIP OD; # adjust to change the spin rate #
print( ( CASE 1 + i MOD 4 IN "/", "-", "\", "|" ESAC, REPR 8 ) )
OD |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #AWK | AWK | function deque(arr) {
arr["start"] = 0
arr["end"] = 0
}
function dequelen(arr) {
return arr["end"] - arr["start"]
}
function empty(arr) {
return dequelen(arr) == 0
}
function push(arr, elem) {
arr[++arr["end"]] = elem
}
function pop(arr) {
if (empty(arr)) {
return
}
return arr[arr["end"]--]
}
function unshift(arr, elem) {
arr[arr["start"]--] = elem
}
function shift(arr) {
if (empty(arr)) {
return
}
return arr[++arr["start"]]
}
function peek(arr) {
if (empty(arr)) {
return
}
return arr[arr["end"]]
}
function printdeque(arr, i, sep) {
printf("[")
for (i = arr["start"] + 1; i <= arr["end"]; i++) {
printf("%s%s", sep, arr[i])
sep = ", "
}
printf("]\n")
}
BEGIN {
deque(q)
for (i = 1; i <= 10; i++) {
push(q, i)
}
printdeque(q)
for (i = 1; i <= 10; i++) {
print pop(q)
}
printdeque(q)
} |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Wren | Wren | import "./sql" for Sql, Connection
import "./crypto" for Md5
var addUser = Fn.new { |db, name, pw|
var sql = "INSERT OR IGNORE INTO users (username,pass_salt,pass_md5) VALUES(?, ?, ?)"
var stmt = db.prepare(sql)
var salt = Sql.randomness(16)
var md5s = Md5.digest(salt + pw)
stmt.bindText(1, name)
stmt.bindText(2, salt)
stmt.bindText(3, md5s)
stmt.step()
}
var authenticateUser = Fn.new { |db, name, pw|
var sql = "SELECT pass_salt, pass_md5 FROM users WHERE username = ?"
var stmt = db.prepare(sql)
stmt.bindText(1, name)
var res = stmt.step()
if (res != Sql.row) {
res = false // no such user
} else {
var salt = stmt.columnText(0)
var passMd5 = stmt.columnText(1)
res = passMd5 == Md5.digest(salt + pw)
}
return res
}
var createSql = """
DROP TABLE IF EXISTS users;
CREATE TABLE users(
userid INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
pass_salt tinyblob NOT NULL,
pass_md5 tinyblob NOT NULL);
"""
var db = Connection.open("users.db")
var res = db.exec(createSql)
if (res != Sql.ok) Fiber.abort("Error creating users table.")
addUser.call(db, "user", "password")
System.print("User with correct password: %(authenticateUser.call(db, "user", "password"))")
System.print("User with incorrect password: %(authenticateUser.call(db, "user", "wrong"))") |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Haskell | Haskell |
import System.Process (callProcess) -- From “process” library
say text = callProcess "espeak" ["--", text]
main = say "This is an example of speech synthesis."
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #JavaScript | JavaScript |
var utterance = new SpeechSynthesisUtterance("This is an example of speech synthesis.");
window.speechSynthesis.speak(utterance);
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Julia | Julia |
julia> a = "hello world"
"hello world"
julia> run(`espeak $a`)
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Cowgol | Cowgol | include "cowgol.coh";
var cube: uint16 := 1;
var ncube: uint16 := 1;
var sqr: uint16 := 1;
var nsqr: uint16 := 1;
var seen: uint8 := 0;
while seen < 30 loop
sqr := nsqr * nsqr;
while sqr > cube loop
ncube := ncube + 1;
cube := ncube * ncube * ncube;
end loop;
if sqr != cube then
seen := seen + 1;
print_i16(sqr);
print_char(' ');
end if;
nsqr := nsqr + 1;
end loop;
print_nl(); |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #D | D | import std.algorithm;
import std.range;
import std.stdio;
auto squareGen() {
struct Gen {
private int add = 3;
private int curr = 1;
bool empty() {
return curr < 0;
}
auto front() {
return curr;
}
void popFront() {
curr += add;
add += 2;
}
}
return Gen();
}
auto cubeGen() {
struct Gen {
private int add1 = 7;
private int add2 = 12;
private int curr = 1;
bool empty() {
return curr < 0;
}
auto front() {
return curr;
}
void popFront() {
curr += add1;
add1 += add2;
add2 += 6;
}
}
return Gen();
}
auto merge() {
struct Gen {
private auto sg = squareGen();
private auto cg = cubeGen();
bool empty() {
return sg.empty || cg.empty;
}
auto front() {
import std.typecons;
if (sg.front == cg.front) {
return tuple!("num", "isCube")(sg.front, true);
} else {
return tuple!("num", "isCube")(sg.front, false);
}
}
void popFront() {
while (true) {
if (sg.front < cg.front) {
sg.popFront();
return;
} else if (sg.front == cg.front) {
sg.popFront();
cg.popFront();
return;
} else {
cg.popFront();
}
}
}
}
return Gen();
}
void main() {
foreach (p; merge.take(33)) {
if (p.isCube) {
writeln(p.num, " (also cube)");
} else {
writeln(p.num);
}
}
} |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Lua | Lua |
math.randomseed(os.time())
function randList (n) -- Build table of size n
local numbers = {}
for i = 1, n do
table.insert(numbers, math.random()) -- range correct by default
end
return numbers
end
function mean (t) -- Find mean average of values in table t
local sum = 0
for k, v in pairs(t) do
sum = sum + v
end
return sum / #t
end
function stdDev (t) -- Find population standard deviation of table t
local squares, avg = 0, mean(t)
for k, v in pairs(t) do
squares = squares + ((avg - v) ^ 2)
end
local variance = squares / #t
return math.sqrt(variance)
end
function showHistogram (t) -- Draw histogram of given table to stdout
local histBars, compVal = {}
for range = 0, 9 do
histBars[range] = 0
for k, v in pairs(t) do
compVal = tonumber(string.format("%0.1f", v - 0.05))
if compVal == range / 10 then
histBars[range] = histBars[range] + 1
end
end
end
for k, v in pairs(histBars) do
io.write("0." .. k .. " " .. string.rep('=', v / #t * 200))
print(" " .. v)
end
print()
end
function showStats (tabSize) -- Create and display statistics info
local numList = randList(tabSize)
print("Table of size " .. #numList)
print("Mean average: " .. mean(numList))
print("Standard dev: " .. stdDev(numList))
showHistogram(numList)
end
for power = 2, 5 do -- Start of main procedure
showStats(10 ^ power)
end
|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #REXX | REXX | /*REXX program displays square─free numbers (integers > 1) up to a specified limit. */
numeric digits 20 /*be able to handle larger numbers. */
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/
if HI=='' | HI=="," then HI= 145 /* " " " " " " */
sw= linesize() - 1 /*use one less than a full line. */
# = 0 /*count of square─free numbers found. */
$= /*variable that holds a line of numbers*/
do j=LO to abs(HI) /*process all integers between LO & HI.*/
if \isSquareFree(j) then iterate /*Not square─free? Then skip this #. */
#= # + 1 /*bump the count of square─free numbers*/
if HI<0 then iterate /*Only counting 'em? Then look for more*/
if length($ || j)<sw then $= strip($ j) /*append the number to the output list.*/
else do; say $; $=j; end /*display a line of numbers.*/
end /*j*/
if $\=='' then say $ /*are there any residuals to display ? */
@theNum= 'The number of square─free numbers between '
if HI<0 then say @theNum LO " and " abs(HI) ' (inclusive) is: ' #
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isSquareFree: procedure; parse arg x; if x<1 then return 0 /*is the number too small?*/
odd= x//2 /*ODD=1 if X is odd, ODD=0 if even.*/
do k=2+odd to iSqrt(x) by 1+odd /*use all numbers, or just odds*/
if x // k**2 == 0 then return 0 /*Is X divisible by a square?*/
end /*k*/ /* [↑] Yes? Then ¬ square─free*/
return 1 /* [↑] // is REXX's ÷ remainder.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
iSqrt: procedure; parse arg x; q= 1; do while q<=x; q= q * 4
end /*while q<=x*/
r= 0
do while q>1; q= q % 4; _= x - r - q; r= r % 2
if _>=0 then do; x= _; r= r + q; end
end /*while q>1*/
return r /*R is the integer square root of X. */ |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #R | R |
x <- c(12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36,
29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109,
23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113,
121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116,
27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117,
116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28,
48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146)
stem(x)
|
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #Racket | Racket |
#lang racket
(define (show-stem+leaf data)
(define xs (sort data <))
(for ([stem (add1 (floor (/ (last xs) 10)))])
(printf "~a|" (~a #:width 2 #:align 'right stem))
(for ([i xs])
(define-values [q r] (quotient/remainder i 10))
(when (= q stem) (printf " ~a" r)))
(newline)))
(show-stem+leaf (sequence->list (in-producer read eof)))
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #BASIC256 | BASIC256 | function split$(instring$)
if length(instring$) < 2 then return instring$
ret$ = left(instring$,1)
for i = 2 to length(instring$)
if mid(instring$,i,1) <> mid(instring$, i-1, 1) then ret$ += ", "
ret$ += mid(instring$, i, 1)
next i
return ret$
end function
print split$("gHHH5YY++///\") |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #BBC_BASIC | BBC BASIC | REM >split
PRINT FN_split( "gHHH5YY++///\" )
END
DEF FN_split( s$ )
LOCAL c$, split$, d$, i%
c$ = LEFT$( s$, 1 )
split$ = ""
FOR i% = 1 TO LEN s$
LET d$ = MID$( s$, i%, 1 )
IF d$ <> c$ THEN
split$ += ", "
c$ = d$
ENDIF
split$ += d$
NEXT
= split$ |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Perl | Perl | use strict;
use warnings;
sub stern_brocot {
my @list = (1, 1);
sub {
push @list, $list[0] + $list[1], $list[1];
shift @list;
}
}
{
my $generator = stern_brocot;
print join ' ', map &$generator, 1 .. 15;
print "\n";
}
for (1 .. 10, 100) {
my $index = 1;
my $generator = stern_brocot;
$index++ until $generator->() == $_;
print "first occurrence of $_ is at index $index\n";
}
{
sub gcd {
my ($u, $v) = @_;
$v ? gcd($v, $u % $v) : abs($u);
}
my $generator = stern_brocot;
my ($a, $b) = ($generator->(), $generator->());
for (1 .. 1000) {
die "unexpected GCD for $a and $b" unless gcd($a, $b) == 1;
($a, $b) = ($b, $generator->());
}
} |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #AWK | AWK |
# syntax: GAWK -f SPINNING_ROD_ANIMATION_TEXT.AWK
@load "time"
BEGIN {
while (1) {
printf(" %s\r",substr("|/-\\",x++%4+1,1))
sleep(.25)
}
exit(0)
}
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #BaCon | BaCon | WHILE TRUE
PRINT CR$, TOKEN$("🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘", x);
x = IIF(x>7, 1, x+1)
SLEEP 250
WEND |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Axe | Axe | 0→S
Lbl PUSH
r₁→{L₁+S}ʳ
S+2→S
Return
Lbl POP
S-2→S
{L₁+S}ʳ
Return
Lbl EMPTY
S≤≤0
Return |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Kotlin | Kotlin | // Kotlin Native v0.6.2
import kotlinx.cinterop.*
import platform.posix.*
fun talk(s: String) {
val pid = fork()
if (pid < 0) {
perror("fork")
exit(1)
}
if (pid == 0) {
execlp("espeak", "espeak", s, null)
perror("espeak")
_exit(1)
}
memScoped {
val status = alloc<IntVar>()
waitpid(pid, status.ptr, 0)
if (status.value > 0) println("Exit status was ${status.value}")
}
}
fun main(args: Array<String>) {
talk("This is an example of speech synthesis.")
} |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Liberty_BASIC | Liberty BASIC |
nomainwin
run "C:\Program Files\eSpeak\command_line\espeak "; chr$( 34); "This is an example of speech synthesis."; chr$( 34)
end
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Locomotive_Basic | Locomotive Basic | |say,"This is an example of speech synthesis." |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #dc | dc |
[n = # of non-cube squares found; we stop when it hits 30]sz
[b = # found that are both squares and cubes]sz
0 d sn sb
[c = current cube, s = current square,
r = current cube root, q = current square root,
f = "first" flag, to control comma delimiting]sz
1 d sc d ss d sq d sr sf
[M = main loop]sz
[
lq d * d ss [square q into s]sz
lc r >I [if s > c then call Increment]sz
lc ls <F [if s < c then s is a non-cube square; call Found]sz
lc ls =R [if s = c then s is a cubic square; call Remember]sz
lq 1 + sq [increment q]sz
ln 30 >M [loop if n is still < 30]sz
]sM
[I = Increment. Bump r and c=r^3 until c >= s]sz
[
lr 1 + d sr
d d * * d sc
ls >I
]sI
[C = Comma. Print a comma and a space]sz
[
44P 32P
]sC
[F = Found. Print s and increment n]sz
[
ln 1 + sn
lf 0 =C 0 sf [print ", " if f is not set; clear f]sz
ls n
]sF
[R = Remember. Save s in array l for later.]sz
[
lb d ls r :l
1 + sb
]sR
[B = print Both. Print out the values saved in array l.]sz
[
lf 0 =C 0 sf [print ", " if f is not set; clear f]sz
li d ;l n
1 + d si
lb r <B
]sB
[Print label and newline]sz
[Squares but not cubes:]n 10P
[Run main loop]sz
lMx
[Print two more newlines]sz
10 d P P
[Print second label and newline]sz
[Both squares and cubes:]n 10P
[initialize i to 0, set f again, and call B to print out the values in l]sz
0 si 1 sf lBx 10P |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Maple | Maple | with(Statistics):
X_100 := Sample( Uniform(0,1), 100 );
Mean( X_100 );
StandardDeviation( X_100 );
Histogram( X_100 ); |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Sample[n_]:= (Print[#//Length," numbers, Mean : ",#//Mean,", StandardDeviation : ",#//StandardDeviation ];
BarChart[BinCounts[#,{0,1,.1}], Axes->False, BarOrigin->Left])&[(RandomReal[1,#])&[ n ]]
Sample/@{100,1 000,10 000,1 000 000} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Ruby | Ruby | require "prime"
class Integer
def square_free?
prime_division.none?{|pr, exp| exp > 1}
end
end
puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(" ")}
puts
m = 10**12
puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(" ")}
puts
markers = [100, 1000, 10_000, 100_000, 1_000_000]
count = 0
(1..1_000_000).each do |n|
count += 1 if n.square_free?
puts "#{count} square-frees upto #{n}" if markers.include?(n)
end
|
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #Raku | Raku | my @data = <
12 127 28 42 39 113 42 18 44 118 44
37 113 124 37 48 127 36 29 31 125 139
131 115 105 132 104 123 35 113 122 42 117
119 58 109 23 105 63 27 44 105 99 41
128 121 116 125 32 61 37 127 29 113 121
58 114 126 53 114 96 25 109 7 31 141
46 13 27 43 117 116 27 7 68 40 31
115 124 42 128 52 71 118 117 38 27 106
33 117 116 111 40 119 47 105 57 122 109
124 115 43 120 43 27 27 18 28 48 125
107 114 34 133 45 120 30 127 31 116 146
>».Int.sort;
my Int $stem_unit = 10;
my %h = @data.classify: * div $stem_unit;
my $range = [minmax] %h.keys».Int;
my $stem_format = "%{$range.min.chars max $range.max.chars}d";
for $range.list -> $stem {
my $leafs = %h{$stem} // [];
say $stem.fmt($stem_format), ' | ', ~$leafs.map: * % $stem_unit;
} |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *split(char *str);
int main(int argc,char **argv)
{
char input[13]="gHHH5YY++///\\";
printf("%s\n",split(input));
}
char *split(char *str)
{
char last=*str,*result=malloc(3*strlen(str)),*counter=result;
for (char *c=str;*c;c++) {
if (*c!=last) {
strcpy(counter,", ");
counter+=2;
last=*c;
}
*counter=*c;
counter++;
}
*(counter--)='\0';
return realloc(result,strlen(result));
} |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #Phix | Phix | sequence sb = {1,1}
integer c = 2
function stern_brocot(integer n)
while length(sb)<n do
sb &= sb[c]+sb[c-1] & sb[c]
c += 1
end while
return sb[1..n]
end function
sequence s = stern_brocot(15)
puts(1,"first 15:")
?s
integer n = 16, k
sequence idx = tagset(10)
for i=1 to length(idx) do
while 1 do
k = find(idx[i],s)
if k!=0 then exit end if
n *= 2
s = stern_brocot(n)
end while
idx[i] = k
end for
puts(1,"indexes of 1..10:")
?idx
puts(1,"index of 100:")
while 1 do
k = find(100,s)
if k!=0 then exit end if
n *= 2
s = stern_brocot(n)
end while
?k
s = stern_brocot(1000)
integer maxgcd = 1
for i=1 to 999 do
maxgcd = max(gcd(s[i],s[i+1]),maxgcd)
end for
printf(1,"max gcd:%d\n",{maxgcd})
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Bash | Bash | while : ; do
for rod in \| / - \\ ; do printf ' %s\r' $rod; sleep 0.25; done
done |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #C | C | #include <stdio.h>
#include <time.h>
int main() {
int i, j, ms = 250;
const char *a = "|/-\\";
time_t start, now;
struct timespec delay;
delay.tv_sec = 0;
delay.tv_nsec = ms * 1000000L;
printf("\033[?25l"); // hide the cursor
time(&start);
while(1) {
for (i = 0; i < 4; i++) {
printf("\033[2J"); // clear terminal
printf("\033[0;0H"); // place cursor at top left corner
for (j = 0; j < 80; j++) { // 80 character terminal width, say
printf("%c", a[i]);
}
fflush(stdout);
nanosleep(&delay, NULL);
}
// stop after 20 seconds, say
time(&now);
if (difftime(now, start) >= 20) break;
}
printf("\033[?25h"); // restore the cursor
return 0;
} |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Babel | Babel | main :
{ (1 2 3) foo set -- foo = (1 2 3)
4 foo push -- foo = (1 2 3 4)
0 foo unshift -- foo = (0 1 2 3 4)
foo pop -- foo = (0 1 2 3)
foo shift -- foo = (1 2 3)
check_foo
{ foo pop } 4 times -- Pops too many times, but this is OK and Babel won't complain
check_foo }
empty? : nil? -- just aliases 'empty?' to the built-in operator 'nil?'
check_foo! :
{ "foo is "
{foo empty?) {nil} {"not " .} ifte
"empty" .
cr << }
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #M2000_Interpreter | M2000 Interpreter |
Module UsingStatementSpeech {
Volume 100
Speech "This is an example of speech synthesis."
}
UsingStatementSpeech
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Speak["This is an example of speech synthesis."] |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Nim | Nim | import osproc
discard execCmd("espeak 'Hello world!'") |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #PARI.2FGP | PARI/GP | speak(txt,opt="")=extern(concat(["espeak ",opt," \"",txt,"\""])); |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Delphi | Delphi |
program Square_but_not_cube;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
begin
var count := 0;
var n := 1;
while count < 30 do
begin
var sq := n * n;
var cr := Trunc(Power(sq, 1 / 3));
if cr * cr * cr <> sq then
begin
inc(count);
writeln(sq);
end
else
Writeln(sq, ' is square and cube');
inc(n);
end;
{$IFNDEF UNIX} readln; {$ENDIF}
end. |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #MATLAB_.2F_Octave | MATLAB / Octave | % Initialize
N = 0; S=0; S2 = 0;
binlist = 0:.1:1;
h = zeros(1,length(binlist)); % initialize histogram
% read data and perform computation
while (1)
% read next sample x
if (no_data_available) break; end;
N = N + 1;
S = S + x;
S2= S2+ x*x;
ix= sum(x < binlist);
h(ix) = h(ix)+1;
end
% generate output
m = S/N; % mean
sd = sqrt(S2/N-mean*mean); % standard deviation
bar(binlist,h) |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #MiniScript | MiniScript | Stats = {}
Stats.count = 0
Stats.sum = 0
Stats.sumOfSquares = 0
Stats.histo = null
Stats.add = function(x)
self.count = self.count + 1
self.sum = self.sum + x
self.sumOfSquares = self.sumOfSquares + x*x
bin = floor(x*10)
if not self.histo then self.histo = [0]*10
self.histo[bin] = self.histo[bin] + 1
end function
Stats.mean = function()
return self.sum / self.count
end function
Stats.stddev = function()
m = self.sum / self.count
return sqrt(self.sumOfSquares / self.count - m*m)
end function
Stats.histogram = function()
for i in self.histo.indexes
print "0." + i + ": " + "=" * (self.histo[i]/self.count * 200)
end for
end function
for sampleSize in [100, 1000, 10000]
print "Samples: " + sampleSize
st = new Stats
for i in range(sampleSize)
st.add rnd
end for
print "Mean: " + st.mean + " Standard Deviation: " + st.stddev
st.histogram
end for |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Rust | Rust | fn square_free(mut n: usize) -> bool {
if n & 3 == 0 {
return false;
}
let mut p: usize = 3;
while p * p <= n {
let mut count = 0;
while n % p == 0 {
count += 1;
if count > 1 {
return false;
}
n /= p;
}
p += 2;
}
true
}
fn print_square_free_numbers(from: usize, to: usize) {
println!("Square-free numbers between {} and {}:", from, to);
let mut line = String::new();
for i in from..=to {
if square_free(i) {
if !line.is_empty() {
line.push_str(" ");
}
line.push_str(&i.to_string());
if line.len() >= 80 {
println!("{}", line);
line.clear();
}
}
}
if !line.is_empty() {
println!("{}", line);
}
}
fn print_square_free_count(from: usize, to: usize) {
let mut count = 0;
for i in from..=to {
if square_free(i) {
count += 1;
}
}
println!(
"Number of square-free numbers between {} and {}: {}",
from, to, count
)
}
fn main() {
print_square_free_numbers(1, 145);
print_square_free_numbers(1000000000000, 1000000000145);
let mut n: usize = 100;
while n <= 1000000 {
print_square_free_count(1, n);
n *= 10;
}
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Scala | Scala | import spire.math.SafeLong
import spire.implicits._
import scala.annotation.tailrec
object SquareFreeNums {
def main(args: Array[String]): Unit = {
println(
s"""|1 - 145:
|${formatTable(sqrFree.takeWhile(_ <= 145).toVector, 10)}
|
|1T - 1T+145:
|${formatTable(sqrFreeInit(1000000000000L).takeWhile(_ <= 1000000000145L).toVector, 6)}
|
|Square-Free Counts...
|100: ${sqrFree.takeWhile(_ <= 100).length}
|1000: ${sqrFree.takeWhile(_ <= 1000).length}
|10000: ${sqrFree.takeWhile(_ <= 10000).length}
|100000: ${sqrFree.takeWhile(_ <= 100000).length}
|1000000: ${sqrFree.takeWhile(_ <= 1000000).length}
|""".stripMargin)
}
def chkSqr(num: SafeLong): Boolean = !LazyList.iterate(SafeLong(2))(_ + 1).map(_.pow(2)).takeWhile(_ <= num).exists(num%_ == 0)
def sqrFreeInit(init: SafeLong): LazyList[SafeLong] = LazyList.iterate(init)(_ + 1).filter(chkSqr)
def sqrFree: LazyList[SafeLong] = sqrFreeInit(1)
def formatTable(lst: Vector[SafeLong], rlen: Int): String = {
@tailrec
def fHelper(ac: Vector[String], src: Vector[String]): String = {
if(src.nonEmpty) fHelper(ac :+ src.take(rlen).mkString, src.drop(rlen))
else ac.mkString("\n")
}
val maxLen = lst.map(n => f"${n.toBigInt}%,d".length).max
val formatted = lst.map(n => s"%,${maxLen + 2}d".format(n.toBigInt))
fHelper(Vector[String](), formatted)
}
} |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #REXX | REXX | /*REXX program displays a stem and leaf plot of any non-negative numbers [can include 0]*/
parse arg @ /* [↓] Not specified? Then use default*/
if @='' then @=12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139,
131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121,
116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117,
116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105,
57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
#.=; bot=.; top=. /* [↑] define all #. elements as null.*/
do j=1 for words(@); y=word(@, j) /*◄─── process each number in the list.*/
if \datatype(y,"N") then do; say '***error*** item' j "isn't numeric:" y; exit; end
if y<0 then do; say '***error*** item' j "is negative:" y; exit; end
n=format(y, , 0) / 1 /*normalize the numbers (not malformed)*/
stem=word(left(n, length(n) -1) 0, 1) /*obtain stem (1st digits) from number.*/
parse var n '' -1 leaf; _=stem * sign(n) /* " leaf (last digit) " " */
if bot==. then do; bot=_; top=_; end /*handle the first case for TOP and BOT*/
bot=min(bot, _); top=max(top, _) /*obtain the minimum and maximum so far*/
#.stem.leaf= #.stem.leaf leaf /*construct sorted stem-and-leaf entry.*/
end /*j*/
w=max(length(min), length(max) ) + 1 /*W: used to right justify the output.*/
/* [↓] display the stem-and-leaf plot.*/
do k=bot to top; $= /*$: is the output string, a plot line*/
do m=0 for 10; $=$ #.k.m /*build a line for the stem─&─leaf plot*/
end /*m*/
say right(k, w) '║' space($) /*display a line of stem─and─leaf plot.*/
end /*k*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
string s = @"gHHH5YY++///\";
Console.WriteLine(s.RunLengthSplit().Delimit(", "));
}
public static class Extensions
{
public static IEnumerable<string> RunLengthSplit(this string source) {
using (var enumerator = source.GetEnumerator()) {
if (!enumerator.MoveNext()) yield break;
char previous = enumerator.Current;
int count = 1;
while (enumerator.MoveNext()) {
if (previous == enumerator.Current) {
count++;
} else {
yield return new string(Enumerable.Repeat(previous, count).ToArray());
previous = enumerator.Current;
count = 1;
}
}
yield return new string(Enumerable.Repeat(previous, count).ToArray());
}
}
public static string Delimit<T>(this IEnumerable<T> source, string separator = "") => string.Join(separator ?? "", source);
} |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #PicoLisp | PicoLisp | (de nmbr (N)
(let (A 1 B 0)
(while (gt0 N)
(if (bit? 1 N)
(inc 'B A)
(inc 'A B) )
(setq N (>> 1 N)) )
B ) )
(let Lst (mapcar nmbr (range 1 2000))
(println 'First-15: (head 15 Lst))
(for N 10
(println 'First N 'found 'at: (index N Lst)) )
(println 'First 100 'found 'at: (index 100 Lst))
(for (L Lst (cdr L) (cddr L))
(test 1 (gcd (car L) (cadr L))) )
(prinl "All consecutive pairs are relative prime!") ) |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #C_Shell | C Shell | while 1
foreach rod ('|' '/' '-' '\')
printf ' %s\r' $rod; sleep 0.25
end
end |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared before the next frame appears:
|
/
- or ─
\
A stand-alone version that loops and/or a version that doesn't loop can be made. These examples can also be converted into a system used in game development which is called on a HUD or GUI element requiring it to be called each frame to output the text, and advance the frame when the frame delay has passed. You can also use alternate text such as the . animation ( . | .. | ... | .. | repeat from . ) or the logic can be updated to include a ping/pong style where the frames advance forward, reach the end and then play backwards and when they reach the beginning they start over ( technically, you'd stop one frame prior to prevent the first frame playing twice, or write it another way ).
There are many different ways you can incorporate text animations. Here are a few text ideas - each frame is in quotes. If you can think of any, add them to this page! There are 2 examples for several of these; the first is the base animation with only unique sets of characters. The second consists of the primary set from a - n and doubled, minus the first and last element ie: We only want the center. This way an animation can play forwards, and then in reverse ( ping ponging ) without having to code that feature. For the animations with 3 elements, we only add 1, the center. with 4, it becomes 6. with 10, it becomes 18.
We don't need the second option for some of the animations if they connect smoothly, when animated, back to the first element. ... doesn't connect with . cleanly - there is a large leap. The rotating pipe meets the first perfectly so it isn't necessary, etc..
Dots - Option A requires ping / pong enabled script. Option B just adds the elements in the center.
'.', '..', '...'
'.', '..', '...', '..'
Pipe - This has the uniform sideways pipe instead of a hyphen to prevent non-uniform sizing.
'|', '/', '─', '\'
Stars - Option A requires ping / pong enabled script. Option B just adds the elements from the center.
'⁎', '⁑', '⁂'
'⁎', '⁑', '⁂', '⁑'
Clock - These need to be ordered. I haven't done this yet as the application I was testing the system in doesn't support these wingdings / icons. But this would look quite nice and you could set it up to go forward, or backward during an undo process, etc..
'🕛', '🕧', '🕐', '🕜', '🕑', '🕝', '🕒', '🕞', '🕓', '🕟', '🕔', '🕠', '🕕', '🕖', '🕗', '🕘', '🕙', '🕚', '🕡', '🕢', '🕣', '🕤', '🕥', '🕦'
Arrows:
'⬍', '⬈', '➞', '⬊', '⬍', '⬋', '⬅', '⬉'
Bird - This looks decent but may be missing something.
'︷', '︵', '︹', '︺', '︶', '︸'
'︷', '︵', '︹', '︺', '︶', '︸', '︶', '︺', '︹', '︵'
Plants - This isn't quite complete
'☘', '❀', '❁'
'☘', '❀', '❁', '❀'
Eclipse - From Raku Throbber post author
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘'
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | SPINROD
; spin 10 times with quarter-second wait
for i = 1:1:10 {
for j = 1:1:4 {
set x = $case(j,1:"|",2:"/",3:"-",:"\")
; $char(8) backspaces on the terminal
write $char(8)_x
hang 0.25
}
}
quit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.