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/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | letters[words_,n_]Β := Sort[Flatten[Characters /@ Take[words,n]]];
groupSameQ[g1_, g2_]Β := Sort /@ Partition[g1, 2] === Sort /@ Partition[g2, 2];
permutations[{a_, b_, c_, d_}] = Union[Permutations[{a, b, c, d}], SameTest -> groupSameQ];
Select[Flatten[permutations /@
Subsets[Union[ToLowerCase/@{"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida",
"Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland",
"Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire",
"New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania",
"Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington",
"West Virginia", "Wisconsin", "Wyoming"}], {4}], 1],
letters[#, 2] === letters[#, -2] &] |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Pike | Pike | Β
string msg = "hello";
msg += " world";
write(msg +"\n");
Β |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #PL.2FI | PL/I | Cat: procedure options (main);
declare s character (100) varying;
s = 'dust ';
s ||= 'bowl';
put (s);
end Cat; |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Plain_English | Plain English | To run:
Start up.
Put "abc" into a string.
Append "123" to the string.
Write the string to the console.
Wait for the escape key.
Shut down. |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Perl | Perl | use constant pi => 3.14159265;
use List::Util qw(sum reduce min max);
Β
sub normdist {
my($m, $sigma) = @_;
my $r = sqrt -2 * log rand;
my $theta = 2 * pi * rand;
$r * cos($theta) * $sigma + $m;
}
Β
$size = 100000; $mean = 50; $stddev = 4;
Β
push @dataset, normdist($mean,$stddev) for 1..$size;
Β
my $m = sum(@dataset) / $size;
print "m = $m\n";
Β
my $sigma = sqrt( (reduce { $a + $b **2 } 0,@dataset) / $size - $m**2 );
print "sigma = $sigma\n";
Β
$hash{int $_}++ for @dataset;
my $scale = 180 * $stddev / $size;
my @subbar = < βΈ β β β β β β β β >;
for $i (min(@dataset)..max(@dataset)) {
my $x = ($hash{$i} // 0) * $scale;
my $full = int $x;
my $part = 8 * ($x - $full);
my $t1 = 'β' x $full;
my $t2 = $subbar[$part];
print "$i\t$t1$t2\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.
| #Go | Go | package main
Β
import (
"fmt"
"sort"
"strconv"
"strings"
)
Β
var data = `12 127 28 42` //...omitted...127 31 116 146`
Β
func main() {
// load data into map
m := make(map[int][]string)
for _, s := range strings.Fields(data) {
if len(s) == 1 {
m[0] = append(m[0], s)
} else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil {
m[i] = append(m[i], s[len(s)-1:])
} else {
panic("non numeric data")
}
}
// sort stem
s := make([]int, len(m))
var i int
for k := range m {
s[i] = k
i++
}
sort.Ints(s)
// print
for k := s[0]; ; k++ {
v := m[k]
sort.Strings(v)
fmt.Printf("%2d |Β %s\n", k, strings.Join(v, " "))
if k == s[len(s)-1] {
break
}
}
} |
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.
| #EchoLisp | EchoLisp | Β
;; stern (2n ) = stern (n)
;; stern(2n+1) = stern(n) + stern(n+1)
Β
(define (stern n)
(cond
(( < n 3) 1)
((even? n) (stern (/ n 2)))
(else (let ((m (/ (1- n) 2))) (+ (stern m) (stern (1+ m)))))))
(remember 'stern)
Β |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Java | Java | public class StackTracer {
public static void printStackTrace() {
StackTraceElement[] elems = Thread.currentThread().getStackTrace();
Β
System.out.println("Stack trace:");
for (int i = elems.length-1, j = 2 ; i >= 3 ; i--, j+=2) {
System.out.printf("%" + j + "s%s.%s%n", "",
elems[i].getClassName(), elems[i].getMethodName());
}
}
} |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #JavaScript | JavaScript | try {
throw new Error;
} catch(e) {
alert(e.stack);
} |
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();
}
}
| #Erlang | Erlang | Β
-module(stair).
-compile(export_all).
Β
step() ->
1 == random:uniform(2).
Β
step_up(true) ->
ok;
step_up(false) ->
step_up(step()),
step_up(step()).
Β
step_up() ->
step_up(step()).
Β |
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();
}
}
| #Euphoria | Euphoria | procedure step_up()
if not step() then
step_up()
step_up()
end if
end procedure |
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
| #ALGOL_68 | ALGOL 68 | BEGIN
# count/show some square free numbers #
# a number is square free if not divisible by any square and so not divisible #
# by any squared prime #
# to satisfy the task we need to know the primes up to root 1 000 000 000 145 #
# and the square free numbers up to 1 000 000 #
# sieve the primes #
LONG INT one trillion = LENG 1 000 000 * LENG 1 000 000;
INT prime max = ENTIER SHORTEN long sqrt( one trillion + 145 ) + 1;
[ prime max ]BOOL prime; FOR i TO UPB prime DO prime[ i ] := TRUE OD;
FOR s FROM 2 TO ENTIER sqrt( prime max ) DO
IF prime[ s ] THEN
FOR p FROM s * s BY s TO prime max DO prime[ p ] := FALSE OD
FI
OD;
# sieve the square free integers #
INT sf max = 1 000 000;
[ sf max ]BOOL square free;FOR i TO UPB square free DO square free[ i ] := TRUE OD;
FOR s FROM 2 TO ENTIER sqrt( sf max ) DO
IF prime[ s ] THEN
INT q = s * s;
FOR p FROM q BY q TO sf max DO square free[ p ] := FALSE OD
FI
OD;
# returns TRUE if n is square free, FALSE otherwise #
PROC is square free = ( LONG INT n )BOOL:
IF n <= sf max THEN square free[ SHORTEN n ]
ELSE
# n is larger than the sieve - use trial division #
INT max factor = ENTIER SHORTEN long sqrt( n ) + 1;
BOOL square free := TRUE;
FOR f FROM 2 TO max factor WHILE square free DO
IF prime[ f ] THEN
# have a prime #
square free := ( n MOD ( LENG f * LENG f ) /= 0 )
FI
OD;
square free
FI # is square free # ;
# returns the count of square free numbers between m and n (inclusive) #
PROC count square free = ( INT m, n )INT:
BEGIN
INT count := 0;
FOR i FROM m TO n DO IF square free[ i ] THEN count +:= 1 FI OD;
count
END # count square free # ;
Β
# task requirements #
# show square free numbers from 1 -> 145 #
print( ( "Square free numbers from 1 to 145", newline ) );
INT count := 0;
FOR i TO 145 DO
IF is square free( i ) THEN
print( ( whole( i, -4 ) ) );
count +:= 1;
IF count MOD 20 = 0 THEN print( ( newline ) ) FI
FI
OD;
print( ( newline ) );
# show square free numbers from 1 trillion -> one trillion + 145 #
print( ( "Square free numbers from 1 000 000 000 000 to 1 000 000 000 145", newline ) );
count := 0;
FOR i FROM 0 TO 145 DO
IF is square free( one trillion + i ) THEN
print( ( whole( one trillion + i, -14 ) ) );
count +:= 1;
IF count MOD 5 = 0 THEN print( ( newline ) ) FI
FI
OD;
print( ( newline ) );
# show counts of square free numbers #
INT sf 100 := count square free( 1, 100 );
print( ( "square free numbers between 1 and 100: ", whole( sf 100, -6 ), newline ) );
INT sf 1 000 := sf 100 + count square free( 101, 1 000 );
print( ( "square free numbers between 1 and 1 000: ", whole( sf 1 000, -6 ), newline ) );
INT sf 10 000 := sf 1 000 + count square free( 1 001, 10 000 );
print( ( "square free numbers between 1 and 10 000: ", whole( sf 10 000, -6 ), newline ) );
INT sf 100 000 := sf 10 000 + count square free( 10 001, 100 000 );
print( ( "square free numbers between 1 and 100 000: ", whole( sf 100 000, -6 ), newline ) );
INT sf 1 000 000 := sf 100 000 + count square free( 100 001, 1 000 000 );
print( ( "square free numbers between 1 and 1 000 000: ", whole( sf 1 000 000, -6 ), newline ) )
END |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import algorithm, sequtils, strformat, strutils, tables
Β
Β
const
States = @["Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"]
Β
Fictitious = @["New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]
Β
type MatchingPairs = ((string, string), (string, string))
Β
Β
proc matchingPairs(states: openArray[string]): seq[MatchingPairs] =
## Build the list of matching pairs of states.
Β
let states = sorted(states).deduplicate()
Β
# Build a mapping from ordered sequence of chars to sequence of (state, state).
var mapping: Table[seq[char], seq[(string, string)]]
for i in 0..<states.high:
let s1 = states[i]
for j in (i + 1)..states.high:
let s2 = states[j]
mapping.mgetOrPut(sorted(map(s1 & s2, toLowerAscii)), @[]).add (s1, s2)
Β
# Keep only the couples of pairs of states with no common state.
for pairs in mapping.values:
if pairs.len > 1:
# These pairs are candidates.
for i in 0..<pairs.high:
let pair1 = pairs[i]
for j in i..pairs.high:
let pair2 = pairs[j]
if pair1[0]Β != pair2[0] and pair1[0]Β != pair2[1] and
pair1[1]Β != pair2[0] and pair1[1]Β != pair2[1]:
# "pair1" and "pair2" have no common state.
result.add (pair1, pair2)
Β
Β
proc `$`(pairs: MatchingPairs): string =
## Return the string representation of two matching pairs.
"$1 & $2 = $3 & $4".format(pairs[0][0], pairs[0][1], pairs[1][0], pairs[1][1])
Β
echo "For real states:"
for n, pairs in matchingPairs(States):
echo &"{n+1:2}: {pairs}"
echo()
echo "For real + fictitious states:"
for n, pairs in matchingPairs(States & Fictitious):
echo &"{n+1:2}: {pairs}" |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Plain_TeX | Plain TeX | \def\addtomacro#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}
\def\foo{Hello}
Initial: \foo
Β
\addtomacro\foo{ world!}
Appended: \foo
\bye |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #PowerShell | PowerShell | Β
$str = "Hello, "
$str += "World!"
$str
Β |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Phix | Phix | with javascript_semantics
procedure sample(integer n)
-- show mean, standard deviation. Find max, min.
sequence dat = repeat(0,n)
for i=1 to n do
dat[i] = sqrt(-2*log(rnd()))*cos(2*PI*rnd())
end for
printf(1,"%d data terms used.\n",{n})
atom mean = sum(dat)/n,
mx = max(dat),
mn = min(dat),
range = mx-mn
printf(1,"Largest term wasΒ %g & smallest wasΒ %g\n",{mx,mn})
printf(1,"Mean =Β %g\n",{mean})
printf(1,"Stddev =Β %g\n",sqrt(sum(sq_mul(dat,dat))/n-mean*mean))
-- show histogram
integer nBins = 50
sequence bins = repeat(0,nBins+1)
for i=1 to n do
integer bdx = floor((dat[i]-mn)/range*nBins)+1
bins[bdx] += 1
end for
for b=1 to nBins do
puts(1,repeat('#',floor(nBins*bins[b]/n*30))&"\n")
end for
end procedure
sample(100000)
|
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.
| #Haskell | Haskell | import Data.List
import Control.Arrow
import Control.Monad
Β
nlsRaw = "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"
Β
nls :: [Int]
nls = map read $ words nlsRaw
Β
groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head))
justifyR = foldl ((. return) . (++) . tail) . flip replicate ' '
Β
task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip)
$ groupWith fst $ stems ++ map (second return) stemLeaf
where stemLeaf = map (`quotRem` 10) ds
stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf
showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b
fb = length $ show $ maximum $ map abs ds |
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.
| #Elixir | Elixir | defmodule SternBrocot do
def sequence do
Stream.unfold({0,{1,1}}, fn {i,acc} ->
a = elem(acc, i)
b = elem(acc, i+1)
{a, {i+1, Tuple.append(acc, a+b) |> Tuple.append(b)}}
end)
end
Β
def task do
IO.write "First fifteen members of the sequence:\n "
IO.inspect Enum.take(sequence, 15)
Enum.each(Enum.concat(1..10, [100]), fn n ->
i = Enum.find_index(sequence, &(&1==n)) + 1
IO.puts "#{n} first appears at #{i}"
end)
Enum.take(sequence, 1000)
|> Enum.chunk(2,1)
|> Enum.all?(fn [a,b] -> gcd(a,b) == 1 end)
|> if(do: "All GCD's are 1", else: "Whoops, not all GCD's are 1!")
|> IO.puts
end
Β
defp gcd(a,0), do: abs(a)
defp gcd(a,b), do: gcd(b, rem(a,b))
end
Β
SternBrocot.task |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Julia | Julia | f() = g()
g() = println.(stacktrace())
Β
f() |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Kotlin | Kotlin | // version 1.1.2 (stacktrace.kt which compiles to StacktraceKt.class)
Β
fun myFunc() {
println(Throwable().stackTrace.joinToString("\n"))
}
Β
fun main(args:Array<String>) {
myFunc()
println("\nContinuing ... ")
} |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Lasso | Lasso | // Define our own trace method
define trace => {
local(gb) = givenblock
Β
// Set a depth counter
var(::_tracedepth)->isnota(::integer)Β ? $_tracedepth = 0
handle => {$_tracedepth--}
Β
// Only output when supplied a capture
#gbΒ ? stdoutnl(
// Indent
('\t' * $_tracedepth++) +
Β
// Type + Method
#gb->self->type + '.' + #gb->calledname +
Β
// Call site file
': ' + #gb->home->callsite_file +
Β
// Line number and column number
' (line '+#gb->home->callsite_line + ', col ' + #gb->home->callsite_col +')'
)
return #gb()
} |
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();
}
}
| #Factor | Factor | : step-up ( -- ) step [ step-up step-up ] unlessΒ ; |
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();
}
}
| #Forth | Forth | : step-up begin step 0= while recurse repeatΒ ; |
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
| #AWK | AWK | Β
# syntax: GAWK -f SQUARE-FREE_INTEGERS.AWK
# converted from LUA
BEGIN {
main(1,145,1)
main(1000000000000,1000000000145,1)
main(1,100,0)
main(1,1000,0)
main(1,10000,0)
main(1,100000,0)
main(1,1000000,0)
exit(0)
}
function main(lo,hi,show_values, count,i,leng) {
printf("%d-%d: ",lo,hi)
leng = length(lo) + length(hi) + 3
for (i=lo; i<=hi; i++) {
if (square_free(i)) {
count++
if (show_values) {
if (leng > 110) {
printf("\n")
leng = 0
}
printf("%d ",i)
leng += length(i) + 1
}
}
}
printf("count=%d\n\n",count)
}
function square_free(n, root) {
for (root=2; root<=sqrt(n); root++) {
if (n % (root * root) == 0) {
return(0)
}
}
return(1)
}
Β |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | #!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
Β
Β
sub uniq {
my %uniq;
undef @uniq{ @_ };
return keys %uniq
}
Β
Β
sub puzzle {
my @states = uniq(@_);
Β
my %pairs;
for my $state1 (@states) {
for my $state2 (@states) {
next if $state1 le $state2;
my $both = join q(),
grep ' ' ne $_,
sort split //,
lc "$state1$state2";
push @{ $pairs{$both} }, [ $state1, $state2 ];
}
}
Β
for my $pair (keys %pairs) {
next if 2 > @{ $pairs{$pair} };
Β
for my $pair1 (@{ $pairs{$pair} }) {
for my $pair2 (@{ $pairs{$pair} }) {
next if 4 > uniq(@$pair1, @$pair2)
or $pair1->[0] lt $pair2->[0];
Β
say join ' = ', map { join ' + ', @$_ } $pair1, $pair2;
}
}
}
}
Β
my @states = ( 'Alabama', 'Alaska', 'Arizona', 'Arkansas',
'California', 'Colorado', 'Connecticut', 'Delaware',
'Florida', 'Georgia', 'Hawaii',
'Idaho', 'Illinois', 'Indiana', 'Iowa',
'Kansas', 'Kentucky', 'Louisiana',
'Maine', 'Maryland', 'Massachusetts', 'Michigan',
'Minnesota', 'Mississippi', 'Missouri', 'Montana',
'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey',
'New Mexico', 'New York', 'North Carolina', 'North Dakota',
'Ohio', 'Oklahoma', 'Oregon',
'Pennsylvania', 'Rhode Island',
'South Carolina', 'South Dakota', 'Tennessee', 'Texas',
'Utah', 'Vermont', 'Virginia',
'Washington', 'West Virginia', 'Wisconsin', 'Wyoming',
);
Β
my @fictious = ( 'New Kory', 'Wen Kory', 'York New', 'Kory New', 'New Kory' );
Β
say scalar @states, ' states:';
puzzle(@states);
Β
say @states + @fictious, ' states:';
puzzle(@states, @fictious); |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #PureBasic | PureBasic | S$ = "Hello"
S$ = S$ + " Wo" ;by referencing the string twice
S$ + "rld!" ;by referencing the string once
If OpenConsole()
PrintN(S$)
Β
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Python | Python | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
Β
str = "12345678";
str += "9!";
print(str) |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #PureBasic | PureBasic | Procedure.f randomf(resolution = 2147483647)
ProcedureReturn Random(resolution) / resolution
EndProcedure
Β
Procedure.f normalDist() ;Box Muller method
ProcedureReturn Sqr(-2 * Log(randomf())) * Cos(2 * #PI * randomf())
EndProcedure
Β
Procedure sample(n, nBins = 50)
Protected i, maxBinValue, binNumber
Protected.f d, mean, sum, sumSq, mx, mn, range
Β
Dim dat.f(n)
For i = 1 To n
dat(i) = normalDist()
Next
Β
;show mean, standard deviation, find max & min.
mx = -1000
mn = 1000
sum = 0
sumSq = 0
For i = 1 To n
d = dat(i)
If d > mx: mx = d: EndIf
If d < mn: mn = d: EndIf
sum + d
sumSq + d * d
Next
Β
PrintN(Str(n) + " data terms used.")
PrintN("Largest term was " + StrF(mx) + " & smallest was " + StrF(mn))
mean = sum / n
PrintN("Mean = " + StrF(mean))
PrintN("Stddev = " + StrF((sumSq / n) - Sqr(mean * mean)))
Β
;show histogram
range = mx - mn
Dim bins(nBins)
For i = 1 To n
binNumber = Int(nBins * (dat(i) - mn) / range)
bins(binNumber) + 1
Next
Β
maxBinValue = 1
For i = 0 To nBins
If bins(i) > maxBinValue
maxBinValue = bins(i)
EndIf
Next
Β
#normalizedMaxValue = 70
For binNumber = 0 To nBins
tickMarks = Round(bins(binNumber) * #normalizedMaxValue / maxBinValue, #PB_Round_Nearest)
PrintN(ReplaceString(Space(tickMarks), " ", "#"))
Next
PrintN("")
EndProcedure
Β
If OpenConsole()
sample(100000)
Β
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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.
| #HicEst | HicEst | REAL :: workspace(1000), base=16
Β
DLG(CHeckbox=bitmap, NameEdit=base, DNum, MIn=1, MAx=16) ! 1 <= stem base <= 16
READ(ClipBoard, ItemS=nData) workspace ! get raw data
Β
ALIAS(workspace,1, dataset,nData, stems,nData)
SORT(Vector=dataset, Sorted=dataset)
stems = (dataset - MOD(dataset,base)) / base
dataset = dataset - base*stems
max_stem = MAX(stems)
Β
IF( bitmap ) AXIS()
printed = 0
DO stem = 0, max_stem
last = INDEX(stems, stem, 4) ! option 4: search backward
IF( last > printed ) THEN
nLeaves = last - printed
IF(bitmap) THEN
LINE(PenUp=1,W=8, x=0, y=stem, x=nLeaves, y=stem)
ELSE
ALIAS(dataset,printed+1, leaves,nLeaves)
WRITE(Format="i3, ':', 100Z2") stem, leaves
ENDIF
printed = printed + nLeaves
ELSE
WRITE(Format="i3, ':'") stem
ENDIF
ENDDO |
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.
| #F.23 | F# | Β
// Generate Stern-Brocot Sequence. Nigel Galloway: October 11th., 2018
let sb=Seq.unfold(fun (n::g::t)->Some(n,[g]@t@[n+g;g]))[1;1]
Β |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Lua | Lua | function Inner( k )
print( debug.traceback() )
print "Program continues..."
end
Β
function Middle( x, y )
Inner( x+y )
end
Β
function Outer( a, b, c )
Middle( a*b, c )
end
Β
Outer( 2, 3, 5 ) |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | f[g[1, Print[Stack[]]; 2]] |
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();
}
}
| #Fortran | Fortran | module StairRobot
implicit none
Β
contains
Β
logical function step()
! try to climb up and return true or false
step = .true. ! to avoid compiler warning
end function step
Β
recursive subroutine step_up_rec
do while ( .not. step() )
call step_up_rec
end do
end subroutine step_up_rec
Β
subroutine step_up_iter
integer :: i = 0
do while ( i < 1 )
if ( step() ) then
i = i + 1
else
i = i - 1
end if
end do
end subroutine step_up_iter
Β
end module StairRobot |
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();
}
}
| #FreeBASIC | FreeBASIC | Sub step_up()
Dim As Integer i
Do
If step_() Then
i += 1
Else
i -= 1
End If
Loop Until i = 1
End Sub |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, βOn a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.β
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 β 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(βN), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 β 4ac = a(aΒ·k2 β 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every βN-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #C | C | #include <math.h>
#include <stdio.h>
Β
#define nelems(x) (sizeof(x) / sizeof((x)[0]))
Β
const unsigned long multiplier[] = {1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11};
Β
unsigned long long gcd(unsigned long long a, unsigned long long b)
{
while (b != 0)
{
a %= b;
a ^= b;
b ^= a;
a ^= b;
}
Β
return a;
}
Β
unsigned long long SQUFOF( unsigned long long N )
{
unsigned long long D, Po, P, Pprev, Q, Qprev, q, b, r, s;
unsigned long L, B, i;
s = (unsigned long long)(sqrtl(N)+0.5);
if (s*s == N) return s;
for (int k = 0; k < nelems(multiplier) && N <= 0xffffffffffffffff/multiplier[k]; k++) {
D = multiplier[k]*N;
Po = Pprev = P = sqrtl(D);
Qprev = 1;
Q = D - Po*Po;
L = 2 * sqrtl( 2*s );
B = 3 * L;
for (i = 2 ; i < B ; i++) {
b = (unsigned long long)((Po + P)/Q);
P = b*Q - P;
q = Q;
Q = Qprev + b*(Pprev - P);
r = (unsigned long long)(sqrtl(Q)+0.5);
if (!(i & 1) && r*r == Q) break;
Qprev = q;
Pprev = P;
};
if (i >= B) continue;
b = (unsigned long long)((Po - P)/r);
Pprev = P = b*r + P;
Qprev = r;
Q = (D - Pprev*Pprev)/Qprev;
i = 0;
do {
b = (unsigned long long)((Po + P)/Q);
Pprev = P;
P = b*Q - P;
q = Q;
Q = Qprev + b*(Pprev - P);
Qprev = q;
i++;
} while (P != Pprev);
r = gcd(N, Qprev);
if (r != 1 && r != N) return r;
}
return 0;
}
Β
int main(int argc, char *argv[]) {
int i;
const unsigned long long data[] = {
2501,
12851,
13289,
75301,
120787,
967009,
997417,
7091569,
13290059,
42854447,
223553581,
2027651281,
11111111111,
100895598169,
1002742628021,
60012462237239,
287129523414791,
9007199254740931,
11111111111111111,
314159265358979323,
384307168202281507,
419244183493398773,
658812288346769681,
922337203685477563,
1000000000000000127,
1152921505680588799,
1537228672809128917,
4611686018427387877};
Β
for(int i = 0; i < nelems(data); i++) {
unsigned long long example, factor, quotient;
example = data[i];
factor = SQUFOF(example);
if(factor == 0) {
printf("%llu was not factored.\n", example);
}
else {
quotient = example / factor;
printf("IntegerΒ %llu has factorsΒ %llu andΒ %llu\n",
example, factor, quotient);
}
}
}
Β |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
Β
#define TRUE 1
#define FALSE 0
#define TRILLION 1000000000000
Β
typedef unsigned char bool;
typedef unsigned long long uint64;
Β
void sieve(uint64 limit, uint64 *primes, uint64 *length) {
uint64 i, count, p, p2;
bool *c = calloc(limit + 1, sizeof(bool)); /* composite = TRUE */
primes[0] = 2;
count = 1;
/* no need to process even numbers > 2 */
p = 3;
for (;;) {
p2 = p * p;
if (p2 > limit) break;
for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE;
for (;;) {
p += 2;
if (!c[p]) break;
}
}
for (i = 3; i <= limit; i += 2) {
if (!c[i]) primes[count++] = i;
}
*length = count;
free(c);
}
Β
void squareFree(uint64 from, uint64 to, uint64 *results, uint64 *len) {
uint64 i, j, p, p2, np, count = 0, limit = (uint64)sqrt((double)to);
uint64 *primes = malloc((limit + 1) * sizeof(uint64));
bool add;
sieve(limit, primes, &np);
for (i = from; i <= to; ++i) {
add = TRUE;
for (j = 0; j < np; ++j) {
p = primes[j];
p2 = p * p;
if (p2 > i) break;
if (i % p2 == 0) {
add = FALSE;
break;
}
}
if (add) results[count++] = i;
}
*len = count;
free(primes);
}
Β
int main() {
uint64 i, *sf, len;
/* allocate enough memory to deal with all examples */
sf = malloc(1000000 * sizeof(uint64));
printf("Square-free integers from 1 to 145:\n");
squareFree(1, 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 20 == 0) {
printf("\n");
}
printf("%4lld", sf[i]);
}
Β
printf("\n\nSquare-free integers fromΒ %ld toΒ %ld:\n", TRILLION, TRILLION + 145);
squareFree(TRILLION, TRILLION + 145, sf, &len);
for (i = 0; i < len; ++i) {
if (i > 0 && i % 5 == 0) {
printf("\n");
}
printf("%14lld", sf[i]);
}
Β
printf("\n\nNumber of square-free integers:\n");
int a[5] = {100, 1000, 10000, 100000, 1000000};
for (i = 0; i < 5; ++i) {
squareFree(1, a[i], sf, &len);
printf(" fromΒ %d toΒ %d =Β %lld\n", 1, a[i], len);
}
free(sf);
return 0;
} |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phix | Phix | with javascript_semantics
constant states = {"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania",
"Rhode Island", "South Carolina", "South Dakota",
"Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"},
-- extras = {"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"}
extras = {"Slender Dragon", "Abalamara"}
function no_dup(sequence s)
s = sort(s)
for i=length(s) to 2 by -1 do
if s[i]=s[i-1] then
s[i] = s[$]
s = s[1..$-1]
end if
end for
return s
end function
procedure play(sequence s)
s = no_dup(deep_copy(s))
destroy_dict(1) -- empty dict
for i=1 to length(s)-1 do
for j=i+1 to length(s) do
string key = trim(sort(lower(s[i]&s[j])))
object data = getd(key)
if data=0 then
putd(key,{{i,j}})
else
for k=1 to length(data) do
integer {m,n} = data[k]
if m!=i and m!=j and n!=i and n!=j then
?{s[i],s[j],"<==>",s[m],s[n]}
end if
end for
putd(key,append(deep_copy(data),{i,j}))
end if
end for
end for
end procedure
play(states)
?"==="
play(states&extras)
|
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #QB64 | QB64 | s$ = "String"
s$ = s$ + " append"
PRINT s$ |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Quackery | Quackery | [ tuck take swap join swap put ] is append ( [ s --> )
Β
$ "L'homme qui attend de voir un canard roti voler " temp put
$ "dans sa bouche doit attendre tres, tres longtemps." temp append
temp take echo$ |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Python | Python | from __future__ import division
import matplotlib.pyplot as plt
import random
Β
mean, stddev, size = 50, 4, 100000
data = [random.gauss(mean, stddev) for c in range(size)]
Β
mn = sum(data) / size
sd = (sum(x*x for x in data) / size
- (sum(data) / size) ** 2) ** 0.5
Β
print("Sample mean =Β %g; Stddev =Β %g; max =Β %g; min =Β %g forΒ %i values"
Β % (mn, sd, max(data), min(data), size))
Β
plt.hist(data,bins=50) |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
prune := integer(\A[1]) | 10 # Boundary between leaf and stem
every put(data := [], integer(!&input))
writes(right(oldStem := 0,5)," |")
every item := !sort(data) do {
leaf := item % prune
stem := item / prune
while (oldStem < stem) do writes("\n",right(oldStem +:= 1, 5)," |")
writes(" ",right(leaf,*prune-1,"0"))
}
write()
end |
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.
| #Factor | Factor | USING: formatting io kernel lists lists.lazy locals math
math.ranges prettyprint sequencesΒ ;
IN: rosetta-code.stern-brocot
Β
: fn ( n -- m )
[ 1 0 ] dip
[ dup zero? ] [
dup 1 bitand zero?
[ dupd [ + ] 2dip ]
[ [ dup ] [ + ] [ ] tri* ] if
-1 shift
] until drop nipΒ ;
Β
:: search ( n -- m )
1 0 lfrom [ fn n = ] lfilter ltake list>array firstΒ ;
Β
: first15 ( -- )
15 [1,b] [ fn pprint bl ] each
"are the first fifteen." printΒ ;
Β
: first-appearances ( -- )
10 [1,b] 100 suffix
[ dup search "FirstΒ %3u at Stern #%u.\n" printf ] eachΒ ;
Β
: gcd-test ( -- )
1,000 [1,b] [ dup 1 + [ fn ] bi@ gcd nip 1 = not ] filter
empty? "" " not"Β ? "All GCDs are%s 1.\n" printfΒ ;
Β
: main ( -- ) first15 first-appearances gcd-testΒ ;
Β
MAIN: main |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Nanoquery | Nanoquery | def print_stack()
global __calls__
Β
println "stack trace:"
for i in range(len(__calls__) - 2, 0)
println "\t" + __calls__[i]
end
end
Β
print_stack()
println
Β
for i in range(1, 1)
print_stack()
end
Β
println
println "The program would continue." |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
Β
class RStackTraces
method inner() static
StackTracer.printStackTrace()
method middle() static
inner()
method outer() static
middle()
method main(args = String[]) public static
outer()
Β
class RStackTraces.StackTracer
method printStackTrace() public static
elems = Thread.currentThread().getStackTrace()
say 'Stack trace:'
j_ = 2
loop i_ = elems.length - 1 to 2 by -1
say ''.left(j_) || elems[i_].getClassName()'.'elems[i_].getMethodName()
j_ = j_ + 2
end i_
Β |
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();
}
}
| #Go | Go | func step_up(){for !step(){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();
}
}
| #Groovy | Groovy | Β
class Stair_climbing{
static void main(String[] args){
}
static def step_up(){
while not step(){
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();
}
}
| #Haskell | Haskell | stepUp :: Robot ()
stepUp = untilM step stepUp
Β
untilM :: Monad m => m Bool -> m () -> m ()
untilM test action = do
result <- test
if result then return () else action >> untilM test action |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, βOn a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.β
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 β 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(βN), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 β 4ac = a(aΒ·k2 β 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every βN-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #FreeBASIC | FreeBASIC | ' ***********************************************
'subject: Shanks's square form factorization:
' ambiguous forms of discriminant 4N
' give factors of N.
'testedΒ : FreeBasic 1.08.1
Β
Β
'------------------------------------------------
const MxN = culngint(1) shl 62
'input maximum
Β
const qx = (1 shl 5) - 1
'queue size
Β
type arg
'squfof arguments
as ulong m, f
as integer vb
end type
Β
type bqf
declare sub rho ()
'reduce indefinite form
declare function issq (byref r as ulong) as integer
'return -1 if c is square, set r:= sqrt(c)
declare sub qform (byref g as string, byval t as integer)
'print binary quadratic form #t (a, 2b, c)
Β
as ulong rN, a, b, c
as integer vb
end type
Β
type queue
declare sub enq (byref P as bqf)
'enqueue P.c, P.b if appropriate
declare function pro (byref P as bqf, byval r as ulong) as integer
'return -1 if a proper square form is found
Β
as ulong a(qx), L, m
as integer k, t
end type
Β
'global variables
dim shared N as ulongint
'the number to split
Β
dim shared flag as integer
'signal to end all threads
Β
dim shared as ubyte q1024(1023), q3465(3464)
'quadratic residue tables
Β
Β
'------------------------------------------------
sub bqf.rho ()
dim as ulong q, t
swap a, c
'residue
q = culng(rN + b) \ a
t = b: b = q * a - b
'pseudo-square
c += q * (t - b)
end sub
Β
'initialize form
#macro rhoin(F)
F.rhoΒ : h = F.b
F.c = (mN - h * h) \ F.a
#endmacro
Β
function bqf.issq (byref r as ulong) as integer
if q1024(c and 1023) andalso q3465(c mod 3465) then
'98.6% non-squares filtered
r = culng(sqr(c))
if r * r = c then return -1
end if
issq = 0
end function
Β
sub bqf.qform (byref g as string, byval t as integer)
if vb = 0 then exit sub
dim as longint u = a, v = b, w = c
if t and 1 then
w = -w
else
u = -u
end if
v shl= 1
print g;str(t);" = (";u;",";v;",";w;")"
end sub
Β
'------------------------------------------------
#macro red(r, a)
r = iif(a and 1, a, a shr 1)
if m > 2 then
r = iif(r mod m, r, r \ m)
end if
#endmacro
Β
sub queue.enq (byref P as bqf)
dim s as ulong
red(s, P.c)
if s < L then
'circular queue
k = (k + 2) and qx
if k > t then t = k
'enqueue P.b, P.c
a(k) = P.b mod s
a(k + 1) = s
end if
end sub
Β
function queue.pro (byref P as bqf, byval r as ulong) as integer
dim as integer i, sw
'skip improper square forms
for i = 0 to t step 2
sw = (P.b - a(i)) mod r = 0
sw and= a(i + 1) = r
if sw then return 0
next i
pro = -1
end function
Β
'------------------------------------------------
sub squfof (byval ap as any ptr)
dim as arg ptr rp = cptr(arg ptr, ap)
dim as ulong L2, m, r, t, f = 1
dim as integer ix, i, j
dim as ulongint mN, h
'principal and ambiguous cycles
dim as bqf P, A
dim Q as queue
Β
if (N and 1) = 0 then
rp->f = 2 ' even N
flag =-1: exit sub
end if
Β
h = culngint(sqr(N))
if h * h = N then
'N is square
rp->f = culng(h)
flag =-1: exit sub
end if
Β
rp->f = 1
'multiplier
m = rp->m
if m > 1 then
if (N mod m) = 0 then
rp->f = m ' m | N
flag =-1: exit sub
end if
Β
'check overflow m * N
if N > (MxN \ m) then exit sub
end if
mN = N * m
Β
r = int(sqr(mN))
'float64 fix
if culngint(r) * r > mN then r -= 1
P.rN = r
A.rN = r
Β
P.vb = rp->vb
A.vb = rp->vb
'verbosity switch
if P.vb then print "r = "; r
Β
Q.k = -2: Q.t = -1: Q.m = m
'Queue entry bounds
Q.L = int(sqr(r * 2))
L2 = Q.L * m shl 1
Β
'principal form
P.b = r: P.c = 1
rhoin(P)
P.qform("P", 1)
Β
ix = Q.L shl 2
for i = 2 to ix
'search principal cycle
Β
if P.c < L2 then Q.enq(P)
Β
P.rho
if (i and 1) = 0 andalso P.issq(r) then
'square form found
Β
if Q.pro(P, r) then
Β
P.qform("P", i)
'inverse square root
A.b =-P.b: A.c = r
rhoin(A): j = 1
A.qform("A", j)
Β
do
'search ambiguous cycle
t = A.b
A.rho: j += 1
Β
if A.b = t then
'symmetry point
A.qform("A", j)
red(f, A.a)
if f = 1 then exit do
Β
flag = -1
'factor found
end if
loop until flag
Β
end if ' proper square
end if ' square form
Β
if flag then exit for
next i
Β
rp->f = f
end sub
Β
'------------------------------------------------
data 2501
data 12851
data 13289
data 75301
data 120787
data 967009
data 997417
data 7091569
data 13290059
data 23515517
data 42854447
data 223553581
data 2027651281
data 11111111111
data 100895598169
data 1002742628021
data 60012462237239
data 287129523414791
data 9007199254740931
data 11111111111111111
data 314159265358979323
data 384307168202281507
data 419244183493398773
data 658812288346769681
data 922337203685477563
data 1000000000000000127
data 1152921505680588799
data 1537228672809128917
data 4611686018427387877
data 0
Β
'main
'------------------------------------------------
const tx = 4
dim as double tim = timer
dim h(4) as any ptr
dim a(4) as arg
dim as ulongint f
dim as integer s, t
Β
width 64, 30
cls
Β
'tabulate quadratic residues
for t = 0 to 1540
s = t * t
q1024(s and 1023) =-1
q3465(s mod 3465) =-1
next t
Β
a(0).vb = 0
'set one verbosity switch only
Β
a(0).m = 1
'multipliers
a(1).m = 3
a(2).m = 5
a(3).m = 7
a(4).m = 11
Β
do
print
Β
doΒ : read N
loop until N < MxN
if N < 2 then exit do
Β
print "N = "; N
Β
flag = 0
Β
for t = 1 to tx + 1 step 2
if t < tx then
h(t) = threadcreate(@squfof, @a(t))
end if
Β
squfof(@a(t - 1))
f = a(t - 1).f
Β
if t < tx then
threadwait(h(t))
if f = 1 then f = a(t).f
end if
Β
if f > 1 then exit for
next t
Β
'assert
if N mod f then f = 1
Β
if f = 1 then
print "fail"
else
print "f = ";f;" N/f = ";N \ f
end if
loop
Β
print "total time:"; csng(timer - tim); " s"
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
| #11l | 11l | F sd_mean(numbers)
V mean = sum(numbers) / numbers.len
V sd = (sum(numbers.map(n -> (n - @mean) ^ 2)) / numbers.len) ^ 0.5
R (sd, mean)
Β
F histogram(numbers)
V h = [0] * 10
V maxwidth = 50
L(n) numbers
h[Int(n * 10)]++
V mx = max(h)
print()
L(i) h
print(β#.1: #.β.format(L.index / 10, β+β * (i * maxwidth I/ mx)))
print()
Β
L(i) (1, 5)
V n = (0 .< 10 ^ i).map(j -> random:())
print("\n####\n#### #. numbers\n####".format(10 ^ i))
V (sd, mean) = sd_mean(n)
print(β sd: #.6, mean: #.6β.format(sd, mean))
histogram(n) |
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
| #C.2B.2B | C++ | #include <cstdint>
#include <iostream>
#include <string>
Β
using integer = uint64_t;
Β
bool square_free(integer n) {
if (n % 4 == 0)
return false;
for (integer p = 3; p * p <= n; p += 2) {
integer count = 0;
for (; n % p == 0; n /= p) {
if (++count > 1)
return false;
}
}
return true;
}
Β
void print_square_free_numbers(integer from, integer to) {
std::cout << "Square-free numbers between " << from
<< " and " << to << ":\n";
std::string line;
for (integer i = from; i <= to; ++i) {
if (square_free(i)) {
if (!line.empty())
line += ' ';
line += std::to_string(i);
if (line.size() >= 80) {
std::cout << line << '\n';
line.clear();
}
}
}
if (!line.empty())
std::cout << line << '\n';
}
Β
void print_square_free_count(integer from, integer to) {
integer count = 0;
for (integer i = from; i <= to; ++i) {
if (square_free(i))
++count;
}
std::cout << "Number of square-free numbers between "
<< from << " and " << to << ": " << count << '\n';
}
Β
int main() {
print_square_free_numbers(1, 145);
print_square_free_numbers(1000000000000LL, 1000000000145LL);
print_square_free_count(1, 100);
print_square_free_count(1, 1000);
print_square_free_count(1, 10000);
print_square_free_count(1, 100000);
print_square_free_count(1, 1000000);
return 0;
} |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PicoLisp | PicoLisp | (setq *States
(group
(mapcar '((Name) (cons (clip (sort (chop (lowc Name)))) Name))
(quote
"Alabama" "Alaska" "Arizona" "Arkansas"
"California" "Colorado" "Connecticut"
"Delaware"
"Florida" "Georgia" "Hawaii"
"Idaho" "Illinois" "Indiana" "Iowa"
"Kansas" "Kentucky" "Louisiana"
"Maine" "Maryland" "Massachusetts" "Michigan"
"Minnesota" "Mississippi" "Missouri" "Montana"
"Nebraska" "Nevada" "New Hampshire" "New Jersey"
"New Mexico" "New York" "North Carolina" "North Dakota"
"Ohio" "Oklahoma" "Oregon"
"Pennsylvania" "Rhode Island"
"South Carolina" "South Dakota" "Tennessee" "Texas"
"Utah" "Vermont" "Virginia"
"Washington" "West Virginia" "Wisconsin" "Wyoming"
"New Kory" "Wen Kory" "York New" "Kory New" "New Kory" ) ) ) )
Β
(extract
'((P)
(when (cddr P)
(mapcar
'((X)
(cons
(cadr (assoc (car X) *States))
(cadr (assoc (cdr X) *States)) ) )
(cdr P) ) ) )
(group
(mapcon
'((X)
(extract
'((Y)
(cons
(sort (conc (copy (caar X)) (copy (car Y))))
(caar X)
(car Y) ) )
(cdr X) ) )
*States ) ) ) |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
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
| #Prolog | Prolog | state_name_puzzle :-
L = ["Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa",
"Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming",
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"],
Β
maplist(goedel, L, R),
Β
% sort remove duplicates
sort(R, RS),
Β
study(RS).
Β
study([]).
Β
study([V-Word|T]) :-
study_1_Word(V-Word, T, T),
study(T).
Β
Β
study_1_Word(_, [], _).
study_1_Word(V1-W1, [V2-W2 | T1], T) :-
TT is V1+V2,
study_2_Word(W1, W2, TT, T),
study_1_Word(V1-W1, T1, T).
Β
study_2_Word(_W1, _W2, _TT, []).
Β
study_2_Word(W1, W2, TT, [V3-W3 | T]) :-
( W2 \= W3 -> study_3_Word(W1, W2, TT, V3-W3, T); true),
study_2_Word(W1, W2, TT, T).
Β
study_3_Word(_W1, _W2, _TT, _V3-_W3, []).
Β
study_3_Word(W1, W2, TT, V3-W3, [V4-W4|T]) :-
TT1 is V3 + V4,
( TT1 < TT -> study_3_Word(W1, W2, TT, V3-W3, T)
; (TT1 = TT -> ( W4 \= W2 -> format('~w & ~w with ~w & ~w~n', [W1, W2, W3, W4])
; true),
study_3_Word(W1, W2, TT, V3-W3, T))
; true).
Β
% Compute a Goedel number for the word
goedel(Word, Goedel-A) :-
name(A, Word),
downcase_atom(A, Amin),
atom_codes(Amin, LA),
compute_Goedel(LA, 0, Goedel).
Β
compute_Goedel([], G, G).
Β
compute_Goedel([32|T], GC, GF) :-
compute_Goedel(T, GC, GF).
Β
compute_Goedel([H|T], GC, GF) :-
Ind is H - 97,
GC1 is GC + 26 ** Ind,
compute_Goedel(T, GC1, GF).
Β |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Racket | Racket | ;there is no built-in way to set! append in racket
(define mystr "foo")
(set! mystr (string-append mystr " bar"))
(displayln mystr)
Β
;but you can create a quick macro to solve that problem
(define-syntax-rule (set-append! str value)
(set! str (string-append str value)))
Β
(define mymacrostr "foo")
(set-append! mymacrostr " bar")
(displayln mystr) |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Raku | Raku | my $str = "foo";
$str ~= "bar";
say $str; |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #R | R | n <- 100000
u <- sqrt(-2*log(runif(n)))
v <- 2*pi*runif(n)
x <- u*cos(v)
y <- v*sin(v)
hist(x) |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Racket | Racket | Β
#lang racket
(require math (planet williams/science/histogram-with-graphics))
Β
(define data (sample (normal-dist 50 4) 100000))
Β
(displayln (~a "Mean:\t" (mean data)))
(displayln (~a "Stddev:\t" (stddev data)))
(displayln (~a "Max:\t" (apply max data)))
(displayln (~a "Min:\t" (apply min data)))
Β
(define h (make-histogram-with-ranges-uniform 40 30 70))
(for ([x data]) (histogram-increment! h x))
(histogram-plot h "Normal distribution ΞΌ=50 Ο=4")
Β |
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.
| #J | J | stem =: <.@(%&10)
leaf =: 10&|
stemleaf =: (stem@{.Β ; leaf)/.~ stem
expandStems =: <./ ([ + i.@>:@-~) >./
expandLeaves=: (expandStems e. ])@[ #inv ]
Β
showStemLeaf=: (":@,.@expandStems@[Β ; ":&>@expandLeaves)&>/@(>@{.Β ; <@{:)@|:@stemleaf@/:~ |
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.
| #Forth | Forth | : stern ( n -- xΒ : return N'th item of Stern-Brocot sequence)
dup 2 >= if
2 /mod swap if
dup 1+ recurse
swap recurse
+
else
recurse
then
then
;
Β
: first ( n -- xΒ : return X such that stern X = n )
1 begin over over stern <> while 1+ repeat
swap drop
;
Β
: gcd ( a b -- a gcd b )
begin swap over mod dup 0= until drop
;
Β
: task
( Print first 15 numbers )
." First 15: " 1 begin dup stern . 1+ dup 15 > until
drop cr
Β
( Print first occurrence of 1..10 )
1 begin
." First " dup . ." at " dup first .
1+ cr
dup 10 > until
drop
Β
( Print first occurrence of 100 )
." First 100 at " 100 first . cr
Β
( Check that the GCD of each adjacent pair up to 1000 is 1 )
-1 2 begin
dup stern over 1- stern gcd 1 =
rot and swap
1+
dup 1000 > until
swap if
." All GCDs are 1."
drop
else
." GCD <> 1 at: " .
then
cr
;
Β
task
bye |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Nim | Nim | proc g() =
# Writes the current stack trace to stderr.
writeStackTrace()
# Or fetch the stack trace entries for the current stack trace:
echo "----"
for e in getStackTraceEntries():
echo e.filename, "@", e.line, " in ", e.procname
Β
proc f() =
g()
Β
f() |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Objective-C | Objective-C | #include <execinfo.h>
Β
void *frames[128];
int len = backtrace(frames, 128);
char **symbols = backtrace_symbols(frames, len);
for (int i = 0; i < len; ++i) {
NSLog(@"%s", symbols[i]);
}
free(symbols); |
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();
}
}
| #Icon_and_Unicon | Icon and Unicon | procedure step_up()
return step() | (step_up(),step_up())
end |
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();
}
}
| #J | J | step =: 0.6 >Β ?@0:
attemptClimb =: [: <:`>:@.step 0:
isNotUpOne =: -.@(+/@])
Β
step_up=: (] , attemptClimb)^:isNotUpOne^:_ |
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();
}
}
| #Java | Java | public void stepUp() {
while (!step()) stepUp();
} |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, βOn a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.β
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 β 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(βN), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 β 4ac = a(aΒ·k2 β 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every βN-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #Go | Go | package main
Β
import (
"fmt"
"math"
)
Β
func isqrt(x uint64) uint64 {
x0 := x >> 1
x1 := (x0 + x/x0) >> 1
for x1 < x0 {
x0 = x1
x1 = (x0 + x/x0) >> 1
}
return x0
}
Β
func gcd(x, y uint64) uint64 {
for y != 0 {
x, y = y, x%y
}
return x
}
Β
var multiplier = []uint64{
1, 3, 5, 7, 11, 3 * 5, 3 * 7, 3 * 11, 5 * 7, 5 * 11, 7 * 11, 3 * 5 * 7, 3 * 5 * 11, 3 * 7 * 11, 5 * 7 * 11, 3 * 5 * 7 * 11,
}
Β
func squfof(N uint64) uint64 {
s := uint64(math.Sqrt(float64(N)) + 0.5)
if s*s == N {
return s
}
for k := 0; k < len(multiplier) && N <= math.MaxUint64/multiplier[k]; k++ {
D := multiplier[k] * N
P := isqrt(D)
Pprev := P
Po := Pprev
Qprev := uint64(1)
Q := D - Po*Po
L := uint32(isqrt(8 * s))
B := 3 * L
i := uint32(2)
var b, q, r uint64
for ; i < B; i++ {
b = uint64((Po + P) / Q)
P = b*Q - P
q = Q
Q = Qprev + b*(Pprev-P)
r = uint64(math.Sqrt(float64(Q)) + 0.5)
if (i&1) == 0 && r*r == Q {
break
}
Qprev = q
Pprev = P
}
if i >= B {
continue
}
b = uint64((Po - P) / r)
P = b*r + P
Pprev = P
Qprev = r
Q = (D - Pprev*Pprev) / Qprev
i = 0
for {
b = uint64((Po + P) / Q)
Pprev = P
P = b*Q - P
q = Q
Q = Qprev + b*(Pprev-P)
Qprev = q
i++
if P == Pprev {
break
}
}
r = gcd(N, Qprev)
if r != 1 && r != N {
return r
}
}
return 0
}
Β
func main() {
examples := []uint64{
2501,
12851,
13289,
75301,
120787,
967009,
997417,
7091569,
13290059,
42854447,
223553581,
2027651281,
11111111111,
100895598169,
1002742628021,
60012462237239,
287129523414791,
9007199254740931,
11111111111111111,
314159265358979323,
384307168202281507,
419244183493398773,
658812288346769681,
922337203685477563,
1000000000000000127,
1152921505680588799,
1537228672809128917,
4611686018427387877,
}
fmt.Println("Integer Factor Quotient")
fmt.Println("------------------------------------------")
for _, N := range examples {
fact := squfof(N)
quot := "fail"
if fact > 0 {
quot = fmt.Sprintf("%d", N/fact)
}
fmt.Printf("%-20dΒ %-10dΒ %s\n", N, fact, quot)
}
} |
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
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
Β
DEFINE SIZE="10000"
DEFINE HIST_SIZE="10"
BYTE ARRAY data(SIZE)
CARD ARRAY hist(HIST_SIZE)
Β
PROC Generate()
INT i
Β
FOR i=0 TO SIZE-1
DO
data(i)=Rand(0)
OD
RETURN
Β
PROC CalcMean(INT count REAL POINTER mean)
REAL tmp1,tmp2,r255
INT i
Β
IntToReal(0,mean)
IntToReal(255,r255)
FOR i=0 TO count-1
DO
IntToReal(data(i),tmp1)
RealDiv(tmp1,r255,tmp2)
RealAdd(mean,tmp2,tmp1)
RealAssign(tmp1,mean)
OD
IntToReal(count,tmp1)
RealDiv(mean,tmp1,tmp2)
RealAssign(tmp2,mean)
RETURN
Β
PROC CalcStdDev(INT count REAL POINTER mean,sdev)
REAL tmp1,tmp2,r255
INT i
Β
IntToReal(0,sdev)
IntToReal(255,r255)
FOR i=0 TO count-1
DO
IntToReal(data(i),tmp1)
RealDiv(tmp1,r255,tmp2)
RealSub(tmp2,mean,tmp1)
RealMult(tmp1,tmp1,tmp2)
RealAdd(sdev,tmp2,tmp1)
RealAssign(tmp1,sdev)
OD
IntToReal(count,tmp1)
RealDiv(sdev,tmp1,tmp2)
Sqrt(tmp2,sdev)
RETURN
Β
PROC ClearHistogram()
BYTE i
Β
FOR i=0 TO HIST_SIZE-1
DO
hist(i)=0
OD
RETURN
Β
PROC CalcHistogram(INT count)
INT i,index
Β
ClearHistogram()
FOR i=0 TO count-1
DO
index=data(i)*10/256
hist(index)==+1
OD
RETURN
Β
PROC PrintHistogram()
BYTE i,j,n
INT max
REAL tmp1,tmp2,rmax,rlen
Β
max=0
FOR i=0 TO HIST_SIZE-1
DO
IF hist(i)>max THEN
max=hist(i)
FI
OD
IntToReal(max,rmax)
IntToReal(25,rlen)
Β
FOR i=0 TO HIST_SIZE-1
DO
PrintF("0.%Bx: ",i)
IntToReal(hist(i),tmp1)
RealMult(tmp1,rlen,tmp2)
RealDiv(tmp2,rmax,tmp1)
n=RealToInt(tmp1)
FOR j=0 TO n
DO
Put('*)
OD
PrintF("Β %U",hist(i))
IF i<HIST_SIZE-1 THEN
PutE()
FI
OD
RETURN
Β
PROC Test(INT count)
REAL mean,sdev
Β
PrintI(count)
CalcMean(count,mean)
Print(": m=") PrintR(mean)
CalcStdDev(count,mean,sdev)
Print(" sd=") PrintRE(sdev)
CalcHistogram(count)
PrintHistogram()
RETURN
Β
PROC Main()
Put(125) PutE()Β ;clear screen
MathInit()
Generate()
Test(100)
PutE() PutE()
Test(10000)
RETURN |
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
| #Ada | Ada | with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random,
Ada.Numerics.Generic_Elementary_Functions;
Β
procedure Basic_Stat is
Β
package FRG renames Ada.Numerics.Float_Random;
package TIO renames Ada.Text_IO;
Β
type Counter is range 0 .. 2**31-1;
type Result_Array is array(Natural range <>) of Counter;
Β
package FIO is new TIO.Float_IO(Float);
Β
procedure Put_Histogram(R: Result_Array; Scale, Full: Counter) is
begin
for I in R'Range loop
FIO.Put(Float'Max(0.0, Float(I)/10.0 - 0.05),
Fore => 1, Aft => 2, Exp => 0); TIO.Put("..");
FIO.Put(Float'Min(1.0, Float(I)/10.0 + 0.05),
Fore => 1, Aft => 2, Exp => 0); TIO.Put(": ");
for J in 1 .. (R(I)* Scale)/Full loop
Ada.Text_IO.Put("X");
end loop;
Ada.Text_IO.New_Line;
end loop;
end Put_Histogram;
Β
procedure Put_Mean_Et_Al(Sample_Size: Counter;
Val_Sum, Square_Sum: Float) is
Mean: constant FloatΒ := Val_Sum / Float(Sample_Size);
package Math is new Ada.Numerics.Generic_Elementary_Functions(Float);
begin
TIO.Put("Mean: ");
FIO.Put(Mean, Fore => 1, Aft => 5, Exp => 0);
TIO.Put(", Standard Deviation: ");
FIO.Put(Math.Sqrt(abs(Square_Sum / Float(Sample_Size)
- (Mean * Mean))), Fore => 1, Aft => 5, Exp => 0);
TIO.New_Line;
end Put_Mean_Et_Al;
Β
N: CounterΒ := Counter'Value(Ada.Command_Line.Argument(1));
Gen: FRG.Generator;
Results: Result_Array(0 .. 10)Β := (others => 0);
X: Float;
Val_Sum, Squ_Sum: FloatΒ := 0.0;
Β
begin
FRG.Reset(Gen);
for I in 1 .. N loop
XΒ := FRG.Random(Gen);
Val_Sum Β := Val_Sum + X;
Squ_SumΒ := Squ_Sum + X*X;
declare
Index: IntegerΒ := Integer(X*10.0);
begin
Results(Index)Β := Results(Index) + 1;
end;
end loop;
TIO.Put_Line("After sampling" & Counter'Image(N) & " random numnbers: ");
Put_Histogram(Results, Scale => 600, Full => N);
TIO.New_Line;
Put_Mean_Et_Al(Sample_Size => N, Val_Sum => Val_Sum, Square_Sum => Squ_Sum);
end Basic_Stat; |
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
| #D | D | import std.array;
import std.math;
import std.stdio;
Β
long[] sieve(long limit) {
long[] primes = [2];
bool[] c = uninitializedArray!(bool[])(cast(size_t)(limit + 1));
long p = 3;
while (true) {
long p2 = p * p;
if (p2 > limit) {
break;
}
for (long i = p2; i <= limit; i += 2 * p) {
c[cast(size_t)i] = true;
}
while (true) {
p += 2;
if (!c[cast(size_t)p]) {
break;
}
}
}
for (long i = 3; i <= limit; i += 2) {
if (!c[cast(size_t)i]) {
primes ~= i;
}
}
return primes;
}
Β
long[] squareFree(long from, long to) {
long limit = cast(long)sqrt(cast(real)to);
auto primes = sieve(limit);
long[] results;
Β
outer:
for (long i = from; i <= to; i++) {
foreach (p; primes) {
long p2 = p * p;
if (p2 > i) {
break;
}
if (i % p2 == 0) {
continue outer;
}
}
results ~= i;
}
Β
return results;
}
Β
enum TRILLION = 1_000_000_000_000L;
Β
void main() {
writeln("Square-free integers from 1 to 145:");
auto sf = squareFree(1, 145);
foreach (i,v; sf) {
if (i > 0 && i % 20 == 0) {
writeln;
}
writef("%4d", v);
}
Β
writefln("\n\nSquare-free integers fromΒ %d toΒ %d:", TRILLION, TRILLION + 145);
sf = squareFree(TRILLION, TRILLION + 145);
foreach (i,v; sf) {
if (i > 0 && i % 5 == 0) {
writeln;
}
writef("%14d", v);
}
Β
writeln("\n\nNumber of square-free integers:");
foreach (to; [100, 1_000, 10_000, 100_000, 1_000_000]) {
writefln(" from 1 toΒ %d =Β %d", to, squareFree(1, to).length);
}
} |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Python | Python | from collections import defaultdict
Β
states = ["Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "Florida",
"Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas",
"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
"Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
"New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma",
"Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming",
# Uncomment the next line for the fake states.
# "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
]
Β
states = sorted(set(states))
Β
smap = defaultdict(list)
for i, s1 in enumerate(states[:-1]):
for s2 in states[i + 1:]:
smap["".join(sorted(s1 + s2))].append(s1 + " + " + s2)
Β
for pairs in sorted(smap.itervalues()):
if len(pairs) > 1:
print " = ".join(pairs) |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Relation | Relation | Β
set a = "Hello"
set b = " World"
set c = a.b
echo c
Β |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #REXX | REXX | s='he'
s=s'llo world!'
Say s |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Ring | Ring | Β
aString1 = "Welcome to the "
aString2 = "Ring Programming Language"
aString3 = aString1 + aString2
see aString3
Β |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #Raku | Raku | sub normdist ($m, $Ο) {
my $r = sqrt -2 * log rand;
my $Ξ = Ο * rand;
$r * cos($Ξ) * $Ο + $m;
}
Β
sub MAIN ($size = 100000, $mean = 50, $stddev = 4) {
my @dataset = normdist($mean,$stddev) xx $size;
Β
my $m = [+](@dataset) / $size;
say (:$m);
Β
my $Ο = sqrt [+](@dataset X** 2) / $size - $m**2;
say (:$Ο);
Β
(my %hash){.round}++ for @dataset;
my $scale = 180 * $stddev / $size;
constant @subbar = < βΈ β β β β β β β β >;
for %hash.keysΒ».Int.minmax(+*) -> $i {
my $x = (%hash{$i} // 0) * $scale;
my $full = floor $x;
my $part = 8 * ($x - $full);
say $i, "\t", 'β' x $full, @subbar[$part];
}
} |
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.
| #Java | Java | import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
Β
public class StemAndLeaf {
private static int[] 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 };
Β
public static Map<Integer, List<Integer>> createPlot(int... data){
Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>();
int highestStem = -1; //for filling in stems with no leaves
for(int datum:data){
int leaf = datum % 10;
int stem = datum / 10; //integer division
if(stem > highestStem){
highestStem = stem;
}
if(plot.containsKey(stem)){
plot.get(stem).add(leaf);
}else{
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(leaf);
plot.put(stem, list);
}
}
if(plot.keySet().size() < highestStem + 1 /*highest stem value and 0*/ ){
for(int i = 0; i <= highestStem; i++){
if(!plot.containsKey(i)){
LinkedList<Integer> list = new LinkedList<Integer>();
plot.put(i, list);
}
}
}
return plot;
}
Β
public static void printPlot(Map<Integer, List<Integer>> plot){
for(Map.Entry<Integer, List<Integer>> lineΒ : plot.entrySet()){
Collections.sort(line.getValue());
System.out.println(line.getKey() + " | " + line.getValue());
}
}
Β
public static void main(String[] args){
Map<Integer, List<Integer>> plot = createPlot(data);
printPlot(plot);
}
} |
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.
| #Fortran | Fortran | * STERN-BROCOT SEQUENCE - FORTRAN IV
DIMENSION ISB(2400)
NN=2400
ISB(1)=1
ISB(2)=1
I=1
J=2
K=2
1 IF(K.GE.NN) GOTO 2
K=K+1
ISB(K)=ISB(K-I)+ISB(K-J)
K=K+1
ISB(K)=ISB(K-J)
I=I+1
J=J+1
GOTO 1
2 N=15
WRITE(*,101) N
101 FORMAT(1X,'FIRST',I4)
WRITE(*,102) (ISB(I),I=1,15)
102 FORMAT(15I4)
DO 5 J=1,11
JJ=J
IF(J.EQ.11) JJ=100
DO 3 I=1,K
IF(ISB(I).EQ.JJ) GOTO 4
3 CONTINUE
4 WRITE(*,103) JJ,I
103 FORMAT(1X,'FIRST',I4,' AT ',I4)
5 CONTINUE
END |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #OCaml | OCaml | let div a b = a / b
Β
let () =
try let _ = div 3 0 in ()
with e ->
prerr_endline(Printexc.to_string e);
Printexc.print_backtrace stderr;
;; |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Oforth | Oforth | : f1 Exception throw("An exception")Β ;
Integer method: f2 self f1Β ;
: f3 f2Β ;
: f4 f3Β ;
Β
10 f4 |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #OxygenBasic | OxygenBasic | Β
'32bit x86
Β
static string Report
Β
Β
macro ReportStack(n)
'===================
Β
'
scope
'
static sys stack[0X100],stackptr,e
'
'CAPTURE IMAGE OF UP TO 256 ENTRIES
'
'
mov eax,n
cmp eax,0x100
(
jle exit
mov eax,0x100 'UPPER LIMIT
)
mov e,eax
mov stackptr,esp
lea edx,stack
mov ecx,e
mov esi,esp
(
mov eax,[esi]
mov [edx],eax
add esi,4
add edx,4
dec ecx
jg repeat
)
sys i
string cr=chr(13)+chr(10), tab=chr(9)
'
for i=1 to e
report+=hex(stackptr+(i-1)*4,8) tab hex(i-1,2) tab hex(stack[i],8) cr
next
'
end scope
'
end macro
Β
'====
'TEST
'====
Β
function foo()
'=============
Β
push 0x44556677
push 0x33445566
push 0x22334455
push 0x11223344
ReportStack(8)
Β
end function
Β
Report+="Trace inside foo
"
foo()
print report
'putfile "s.txt",Report
Β
/*
RESULT:
Β
Trace inside foo
0017FE00 00 11223344
0017FE04 01 22334455
0017FE08 02 33445566
0017FE0C 03 44556677
0017FE10 04 005EAB1C
0017FE14 05 0017FE40
0017FE18 06 10002D5F
0017FE1C 07 00000000
*/
Β |
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();
}
}
| #jq | jq | def tick: .+1; |
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();
}
}
| #Julia | Julia | Β
step_up() = whileΒ !step() step_up() end
Β |
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();
}
}
| #Kotlin | Kotlin | // version 1.2.0
Β
import java.util.Random
Β
val rand = Random(6321L) // generates short repeatable sequence
var position = 0
Β
fun step(): Boolean {
val r = rand.nextBoolean()
if (r)
println("Climbed up to ${++position}")
else
println("Fell down to ${--position}")
return r
}
Β
fun stepUp() {
while (!step()) stepUp()
}
Β
fun main(args: Array<String>) {
stepUp()
} |
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.
| #11l | 11l | V n = 1
V count = 0
Β
L count < 30
V sq = n * n
V cr = Int(sq ^ (1/3) + 1e-6)
I cr * cr * crΒ != sq
count++
print(sq)
E
print(sqβ is square and cubeβ)
n++ |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, βOn a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.β
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 β 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(βN), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 β 4ac = a(aΒ·k2 β 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every βN-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #jq | jq | def gcd(a; b):
# subfunction expects [a,b] as input
# i.e. a ~ .[0] and b ~ .[1]
def rgcd: if .[1] == 0 then .[0]
else [.[1], .[0]Β % .[1]] | rgcd
end;
[a,b] | rgcd;
Β
# for infinite precision integer-arithmetic
def idivide($p; $q): ($p - ($pΒ % $q)) / $qΒ ;
def idivide($q): (. - (.Β % $q)) / $qΒ ;
Β
def isqrt:
def irt:
. as $x
| 1 | until(. > $x; . * 4) as $q
| {$q, $x, r: 0}
| until( .q <= 1;
.q |= idivide(4)
| .t = .x - .r - .q
| .r |= idivide(2)
| if .t >= 0
then .x = .t
| .r += .q
else .
end)
| .rΒ ;
if type == "number" and (isinfinite|not) and (isnan|not) and . >= 0
then irt
else "isqrt requires a non-negative integer for accuracy" | error
endΒ ; |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, βOn a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.β
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 β 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(βN), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 β 4ac = a(aΒ·k2 β 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every βN-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #Julia | Julia | function square_form_factor(n::T)::T where T <: Integer
multiplier = T.([1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11])
s = T(round(sqrt(n)))
s * s == n && return s
for k in multiplier
TΒ != BigInt && n > typemax(T) Γ· k && break
d = k * n
p0 = pprev = p = isqrt(d)
qprev = one(T)
Q = d - p0 * p0
l = T(floor(2 * sqrt(2 * s)))
B, i = 3 * l, 2
while i < B
b = (p0 + p) Γ· Q
p = b * Q - p
q = Q
Q = qprev + b * (pprev - p)
r = T(round(sqrt(Q)))
iseven(i) && r * r == Q && break
qprev, pprev = q, p
i += 1
end
i >= B && continue
b = (p0 - p) Γ· r
pprev = p = b * r + p
qprev = r
Q = (d - pprev * pprev) Γ· qprev
i = 0
while true
b = (p0 + p) Γ· Q
pprev = p
p = b * Q - p
q = Q
Q = qprev + b * (pprev - p)
qprev = q
i += 1
p == pprev && break
end
r = gcd(n, qprev)
rΒ != 1 && rΒ != n && return r
end
return zero(T)
end
Β
println("Integer Factor Quotient\n", "-"^45)
@time for n in Int128.([
2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, 42854447, 223553581,
2027651281, 11111111111, 100895598169, 1002742628021, 60012462237239, 287129523414791,
9007199254740931, 11111111111111111, 314159265358979323, 384307168202281507, 419244183493398773,
658812288346769681, 922337203685477563, 1000000000000000127, 1152921505680588799,
1537228672809128917, 4611686018427387877])
print(rpad(n, 22))
factr = square_form_factor(n)
print(rpad(factr, 10))
println(factr == 0Β ? "fail"Β : n Γ· factr)
end
Β |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, βOn a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.β
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients and discriminant D = b2 β 4ac.
For each positive discriminant there are multiple forms (a, b, c).
The next form in a periodic sequence (cycle) of adjacent forms is found by applying a reduction operator
rho, essentially a variant of Euclid's algorithm for finding the continued fraction of a square root.
Using floor(βN), rho constructs a principal form
(1, b, c) with D = 4N.
SquFoF is based on the existence of cycles containing ambiguous forms, with the property that a divides b.
They come in pairs of associated forms (a, b, c) and (c, b, a) called symmetry points.
If an ambiguous form is found (there is one for each divisor of D), write the discriminant as
(ak)2 β 4ac = a(aΒ·k2 β 4c) = 4N
and (if a is not equal to 1 or 2) N is split.
Shanks used square forms to jump to a random ambiguous cycle. Fact: if any form in an ambiguous cycle
is squared, that square form will always land in the principal cycle. Conversely, the square root of any
form in the principal cycle lies in an ambiguous cycle. (Possibly the principal cycle itself).
A square form is easy to find: the last coefficient c is a perfect square. This happens about once
every βN-th cycle step and for even indices only. Let rho compute the inverse square root form and track
the ambiguous cycle backward until the symmetry point is reached. (Taking the inverse reverses the cycle).
Then a or a/2 divides D and therefore N.
To avoid trivial factorizations, Shanks created a list (queue) to hold small coefficients appearing
early in the principal cycle, that may be roots of square forms found later on. If these forms are skipped,
no roots land in the principal cycle itself and cases a = 1 or a = 2 do not happen.
Sometimes the cycle length is too short to find a proper square form. This is fixed by running five instances
of SquFoF in parallel, with input N and 3, 5, 7, 11 times N; the discriminants then will have different periods.
If N is prime or the cube of a prime, there are improper squares only and the program will duly report failure.
Reference.
[1] A detailed analysis of SquFoF (2007)
| #Nim | Nim | import math, strformat
Β
const M = [uint64 1, 3, 5, 7, 11]
Β
template isqrt(n: uint64): uint64 = uint64(sqrt(float(n)))
template isEven(n: uint64): bool = (n and 1) == 0
Β
proc squfof(n: uint64): uint64 =
Β
if n.isEven: return 2
var h = uint64(sqrt(float(n)) + 0.5)
if h * h == n: return h
Β
for m in M:
if m > 1 and (n mod m == 0): return m
# Check overflow m * n.
if n > uint64.high div m: break
let mn = m * n
var r = isqrt(mn)
if r * r > mn: dec r
let rn = r
Β
# Principal form.
var b = r
var a = 1u64
h = (rn + b) div a * a - b
var c = (mn - h * h) div a
Β
for i in 2..<(4 * isqrt(2 * r)):
# Search principal cycle.
swap a, c
var q = (rn + b) div a
let t = b
b = q * a - b
c += q * (t - b)
Β
if i.isEven:
r = uint64(sqrt(float(c)) + 0.5)
if r * r == c: # Square form found?
Β
# Inverse square root.
q = (rn - b) div r
var v = q * r + b
var w = (mn - v * v) div r
Β
# Search ambiguous cycle.
var u = r
while true:
swap w, u
r = v
q = (rn + v) div u
v = q * u - v
if v == r: break
w += q * (r - v)
Β
# Symmetry point.
h = gcd(n, u)
if hΒ != 1: return h
Β
result = 1
Β
const Data = [2501u64,
12851u64,
13289u64,
75301u64,
120787u64,
967009u64,
997417u64,
7091569u64,
13290059u64,
42854447u64,
223553581u64,
2027651281u64,
11111111111u64,
100895598169u64,
1002742628021u64,
60012462237239u64,
287129523414791u64,
9007199254740931u64,
11111111111111111u64,
314159265358979323u64,
384307168202281507u64,
419244183493398773u64,
658812288346769681u64,
922337203685477563u64,
1000000000000000127u64,
1152921505680588799u64,
1537228672809128917u64,
4611686018427387877u64]
Β
echo "N f N/f"
echo "======================================"
for n in Data:
let f = squfof(n)
let res = if f == 1: "fail" else: &"{f:<10} {n div f}"
echo &"{n:<22} {res}" |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
Β
#define n_bins 10
Β
double rand01() { return rand() / (RAND_MAX + 1.0); }
Β
double avg(int count, double *stddev, int *hist)
{
double x[count];
double m = 0, s = 0;
Β
for (int i = 0; i < n_bins; i++) hist[i] = 0;
for (int i = 0; i < count; i++) {
m += (x[i] = rand01());
hist[(int)(x[i] * n_bins)] ++;
}
Β
m /= count;
for (int i = 0; i < count; i++)
s += x[i] * x[i];
*stddev = sqrt(s / count - m * m);
return m;
}
Β
void hist_plot(int *hist)
{
int max = 0, step = 1;
double inc = 1.0 / n_bins;
Β
for (int i = 0; i < n_bins; i++)
if (hist[i] > max) max = hist[i];
Β
/* scale if numbers are too big */
if (max >= 60) step = (max + 59) / 60;
Β
for (int i = 0; i < n_bins; i++) {
printf("[%5.2g,%5.2g]%5d ", i * inc, (i + 1) * inc, hist[i]);
for (int j = 0; j < hist[i]; j += step)
printf("#");
printf("\n");
}
}
Β
/* record for moving average and stddev. Values kept are sums and sum data^2
* to avoid excessive precision loss due to divisions, but some loss is inevitable
*/
typedef struct {
uint64_t size;
double sum, x2;
uint64_t hist[n_bins];
} moving_rec;
Β
void moving_avg(moving_rec *rec, double *data, int count)
{
double sum = 0, x2 = 0;
/* not adding data directly to the sum in case both recorded sum and
* count of this batch are large; slightly less likely to lose precision*/
for (int i = 0; i < count; i++) {
sum += data[i];
x2 += data[i] * data[i];
rec->hist[(int)(data[i] * n_bins)]++;
}
Β
rec->sum += sum;
rec->x2 += x2;
rec->size += count;
}
Β
int main()
{
double m, stddev;
int hist[n_bins], samples = 10;
Β
while (samples <= 10000) {
m = avg(samples, &stddev, hist);
printf("sizeΒ %5d:Β %gΒ %g\n", samples, m, stddev);
samples *= 10;
}
Β
printf("\nHistograph:\n");
hist_plot(hist);
Β
printf("\nMoving average:\n N Mean Sigma\n");
moving_rec rec = { 0, 0, 0, {0} };
double data[100];
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 100; j++) data[j] = rand01();
Β
moving_avg(&rec, data, 100);
Β
if ((i % 1000) == 999) {
printf("%4llukΒ %fΒ %f\n",
rec.size/1000,
rec.sum / rec.size,
sqrt(rec.x2 * rec.size - rec.sum * rec.sum)/rec.size
);
}
}
} |
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
| #Factor | Factor | USING: formatting grouping io kernel math math.functions
math.primes.factors math.ranges sequences setsΒ ;
IN: rosetta-code.square-free
Β
: sq-free? ( n --Β ? ) factors all-unique?Β ;
Β
! Word wrap for numbers.
: numbers-per-line ( m -- n ) log10 >integer 2 + 80 swap /iΒ ;
Β
: sq-free-show ( from to -- )
2dup "Square-free integers fromΒ %d toΒ %d:\n" printf
[ [a,b] [ sq-free? ] filter ] [ numbers-per-line group ] bi
[ [ "%3d " printf ] each nl ] each nlΒ ;
Β
: sq-free-count ( limit -- )
dup [1,b] [ sq-free? ] count swap
"%6d square-free integers from 1 toΒ %d\n" printfΒ ;
Β
1 145 10 12 ^ dup 145 + [ sq-free-show ] 2bi@ Β ! part 1
2 6 [a,b] [ 10 swap ^ ] map [ sq-free-count ] each Β ! part 2 |
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
| #Forth | Forth | : square_free? ( n --Β ? )
dup 4 mod 0= if drop false exit then
3
begin
2dup dup * >=
while
0 >r
begin
2dup mod 0=
while
r> 1+ dup 1 > if
2drop drop false exit
then
>r
tuck / swap
repeat
rdrop
2 +
repeat
2drop trueΒ ;
Β
\ print square-free numbers from n3 to n2, n1 per line
: print_square_free_numbers ( n1 n2 n3 -- )
2dup
." Square-free integers between "
1 .r ." and " 1 .r ."Β :" cr
0 -rot
swap 1+ swap do
i square_free? if
i 3 .r space
1+
dup 2 pick mod 0= if cr then
then
loop 2drop crΒ ;
Β
: count_square_free_numbers ( n1 n2 -- n )
0 -rot
swap 1+ swap do
i square_free? if 1+ then
loopΒ ;
Β
: main
20 145 1 print_square_free_numbers cr
5 1000000000145 1000000000000 print_square_free_numbers cr
." Number of square-free integers:" cr
100
begin
dup 1000000 <=
while
dup 1
2dup ." from " 1 .r ." to " 7 .r ."Β : "
count_square_free_numbers . cr
10 *
repeat dropΒ ;
Β
main
bye |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Racket | Racket | Β
#lang racket
(define states
(list->set
(map string-downcase
'("Alabama" "Alaska" "Arizona" "Arkansas"
"California" "Colorado" "Connecticut"
"Delaware"
"Florida" "Georgia" "Hawaii"
"Idaho" "Illinois" "Indiana" "Iowa"
"Kansas" "Kentucky" "Louisiana"
"Maine" "Maryland" "Massachusetts" "Michigan"
"Minnesota" "Mississippi" "Missouri" "Montana"
"Nebraska""Nevada" "New Hampshire" "New Jersey"
"New Mexico" "New York" "North Carolina" "North Dakota"
"Ohio" "Oklahoma" "Oregon"
"Pennsylvania" "Rhode Island"
"South Carolina" "South Dakota" "Tennessee" "Texas"
"Utah" "Vermont" "Virginia"
"Washington" "West Virginia" "Wisconsin" "Wyoming"
Β ; "New Kory" "Wen Kory" "York New" "Kory New" "New Kory"
))))
Β
(define (canon s t)
(sort (append (string->list s) (string->list t)) char<? ))
Β
(define seen (make-hash))
(for* ([s1 states] [s2 states] #:when (string<? s1 s2))
(define c (canon s1 s2))
(cond [(hash-ref seen c (Ξ»() (hash-set! seen c (list s1 s2)) #f))
=> (Ξ»(states) (displayln (~v states (list s1 s2))))]))
Β |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two different U.S. States (so that all four state names differ from one another).
What states are these?
The problem was reissued on the Unicon Discussion Web which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to GΓΆdel numbering, equivalence relations, and equivalence classes. The basic merits of these were discussed in the Unicon Discussion Web.
A second challenge in the form of a set of fictitious new states was also presented.
Task
Write a program to solve the challenge using both the original list of states and the fictitious list.
Caveats
case and spacing aren't significant - just letters (harmonize case)
don't expect the names to be in any order - such as being sorted
don't rely on names to be unique (eliminate duplicates - meaning if Iowa appears twice you can only use it once)
Comma separated list of state names used in the original puzzle:
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware",
"Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana",
"Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New Mexico", "New York", "North Carolina", "North Dakota",
"Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island",
"South Carolina", "South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin", "Wyoming"
Comma separated list of additional fictitious state names to be added to the original (Includes a duplicate):
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string Β (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff Β (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Raku | Raku | my @states = <
Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware
Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky
Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi
Missouri Montana Nebraska Nevada New_Hampshire New_Jersey New_Mexico
New_York North_Carolina North_Dakota Ohio Oklahoma Oregon Pennsylvania
Rhode_Island South_Carolina South_Dakota Tennessee Texas Utah Vermont
Virginia Washington West_Virginia Wisconsin Wyoming
>;
Β
say "50 states:";
.say for anastates @states;
Β
say "\n54 states:";
.say for sort anastates @states, < New_Kory Wen_Kory York_New Kory_New New_Kory >;
Β
sub anastates (*@states) {
my @s = @states.uniqueΒ».subst('_', ' ');
Β
my @pairs = gather for ^@s -> $i {
for $i ^..^ @s -> $j {
take [ @s[$i], @s[$j] ];
}
}
Β
my $equivs = hash @pairs.classify: *.lc.comb.sort.join;
Β
gather for $equivs.values -> @c {
for ^@c -> $i {
for $i ^..^ @c -> $j {
my $set = set @c[$i].list, @c[$j].list;
take @c[$i].list.join(', ') ~ ' = ' ~ @c[$j].list.join(', ') if $set == 4;
}
}
}
} |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Robotic | Robotic | Β
set "$str1" to "Hello "
inc "$str1" by "world!"
* "&$str1&"
end
Β |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Ruby | Ruby | s = "Hello wo"
s += "rld" # new string object
s << "!" # mutates in place, same object
puts s |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #Rust | Rust | Β
use std::ops::Add;
Β
fn main(){
let hello = String::from("Hello world");
println!("{}", hello.add("!!!!"));
} |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.
Mention any native language support for the generation of normally distributed random numbers.
Reference
You may refer to code in Statistics/Basic if available.
| #REXX | REXX | /*REXX program generates 10,000 normally distributed numbers (Gaussian distribution).*/
numeric digits 20 /*use twenty decimal digs for accuracy.*/
parse arg n seed . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 10000 /*Not specified? Then use the default.*/
if datatype(seed, 'W') then call random ,,seed /*seed is for repeatable RANDOM numbers*/
call pi /*call subroutine to define pi constant*/
do g=1 for n; #.g= sqrt( -2 * ln( rand() ) ) * cos( 2 * pi * rand() )
end /*g*/ /* [β] uniform random number ββββΊ #.g */
s= 0
mn= #.1; mx= mn; noise= n * .0005 /*calculate the noise: 1/20thΒ % of N.*/
ss= 0
do j=1 for n; _= #.j /*the sum, and the sum of squares. */
s= s + _; ss= ss + _ * _ /*the sum, and the sum of squares. */
mn= min(mn, _); mx= max(mx, _) /*find the minimum and the maximum. */
end /*j*/
!.= 0
say 'number of data points = ' fmt(n )
say ' minimum = ' fmt(mn )
say ' maximum = ' fmt(mx )
say ' arithmetic mean = ' fmt(s/n)
say ' standard deviation = ' fmt(sqrt( ss/n - (s/n) **2) )
?mn=Β !.1; Β ?mx=Β ?mn /*define minimum & maximum value so far*/
parse value scrSize() with sd sw . /*obtain the (true) screen size of term*/ /*βββnot all REXXes have this BIF*/
sdE= sd - 4 /*the effective (usable) screen depth. */
swE= sw - 1 /* " " " " width.*/
$= 1 / max(1, mx-mn) * sdE /*$ is used for scaling depth of histo*/
do i=1 for n;Β ?= trunc((#.i-mn) *$) /*calculate the relative line. */
Β !.?=Β !.? + 1 /*bump the counter. */
Β ?mn= min(?mn,Β !.?) /*find the minimum. */
Β ?mx= max(?mx,Β !.?) /* " " maximum. */
end /*i*/
f= swE/?mx /*limit graph to 1 full screen*/
do h=0 for sdE; _=Β !.h /*obtain a data point. */
if _>noise then say copies('β', trunc(_*f) ) /*display a bar of histogram. */
end /*h*/ /*[β] use a hyphen for histo.*/
exit /*stick a fork in it, we're all done. */
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
fmt: parse arg @; return left('', (@>=0) + 2 * datatype(@, 'W'))@ /*prepend a blank if #>=0, add 2 blanks if whole.*/
e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e
pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi
r2r: return arg(1) // (pi() * 2) /*normalize the given angle (in radians) to Β±2pi.*/
rand: return random(1, 1e5) / 1e5 /*REXX generates uniform random postive integers.*/
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
ln: procedure; parse arg x,f; call e; ig= x>1.5; is= 1 -2*(ig\==1); ii= 0; xx= x; do while ig & xx>1.5 | \ig & xx<.5
_= e; do k=-1; iz= xx*_ **-is; if k>=0 & (ig & iz<1 | \ig & iz>.5) then leave; _= _*_; izz= iz; end; xx= izz
ii= ii +is*2**k; end; x= x*e**-ii-1; z=0; _=-1; p=z; do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end; return z+ii
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi= pi*.5; numeric fuzz min(6, digits()-3); if a=pi then return -1
if a=hpi | a=hpi*3 then return 0; if a=pi/3 then return .5; if a=pi*2/3 then return -.5; z= 1; _= 1
x= x*x; p= z; do k=2 by 2; _= -_ * x / (k*(k-1)); z= z + _; if z=p then leave; p= z; end; return z
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
sqrt: procedure; parse arg x; if x=0 then return 0; d= digits(); m.= 9; numeric digits; numeric form; h= d+6
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; numeric digits d; return g/1 |
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.
| #JavaScript | JavaScript | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>stem and leaf plot</title>
<script type='text/javascript'>
Β
function has_property(obj, propname) {
return typeof(obj[propname]) === "undefined"Β ? falseΒ : true;
}
Β
function compare_numbers(a, b) {return a-b;}
Β
function stemplot(data, target) {
var stem_data = {};
var all_stems = [];
for (var i = 0; i < data.length; i++) {
var stem = Math.floor(data[i] / 10);
var leaf = Math.round(data[i]Β % 10);
if (has_property(stem_data, stem)) {
stem_data[stem].push(leaf);
} else {
stem_data[stem] = [leaf];
all_stems.push(stem);
}
}
all_stems.sort(compare_numbers);
Β
var min_stem = all_stems[0];
var max_stem = all_stems[all_stems.length - 1];
Β
var table = document.createElement('table');
for (var stem = min_stem; stem <= max_stem; stem++) {
var row = document.createElement('tr');
var label = document.createElement('th');
row.appendChild(label);
label.appendChild(document.createTextNode(stem));
if (has_property(stem_data, stem)) {
stem_data[stem].sort(compare_numbers);
for (var i = 0; i < stem_data[stem].length; i++) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(stem_data[stem][i]));
row.appendChild(cell);
}
}
table.appendChild(row);
}
target.appendChild(table);
}
Β
</script>
<style type='text/css'>
body {font-family: monospace;}
table {border-collapse: collapse;}
th {border-right: 1px solid black; text-align: right;}
td {text-align: right;}
</style>
</head>
<body>
Β
<div id="target"></div>
Β
<script type='text/javascript'>
Β
var 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
];
stemplot(data, document.getElementById('target'));
Β
</script>
Β
</body>
</html> |
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.
| #FreeBASIC | FreeBASIC | ' version 02-03-2019
' compile with: fbc -s console
Β
#Define max 2000
Β
Dim Shared As UInteger stern(max +2)
Β
Sub stern_brocot
Β
stern(1) = 1
stern(2) = 1
Β
Dim As UInteger i = 2 , n = 2, ub = UBound(stern)
Β
Do While i < ub
i += 1
stern(i) = stern(n) + stern(n -1)
i += 1
stern(i) = stern(n)
n += 1
Loop
Β
End Sub
Β
Function gcd(x As UInteger, y As UInteger) As UInteger
Β
Dim As UInteger t
Β
While y
t = y
y = x Mod y
x = t
Wend
Β
Return x
Β
End Function
Β
' ------=< MAIN >=------
Β
Dim As UInteger i
Β
stern_brocot
Β
Print "The first 15 are: "Β ;
For i = 1 To 15
Print stern(i); " ";
Next
Β
PrintΒ : Print
Print " Index First nr."
Dim As UInteger d = 1
For i = 1 To max
If stern(i) = d Then
Print Using " ######"; i; stern(i)
d += 1
If d = 11 Then d = 100
If d = 101 Then Exit For
i = 0
End If
Next
Β
PrintΒ : Print
d = 0
For i = 1 To 1000
If gcd(stern(i), stern(i +1)) <> 1 Then
d = gcd(stern(i), stern(i +1))
Exit For
End If
Next
Β
If d = 0 Then
Print "GCD of two consecutive members of the series up to the 1000th member is 1"
Else
Print "The GCD for index "; i; " and "; i +1; " = "; d
End If
Β
' empty keyboard buffer
While Inkey <> ""Β : Wend
PrintΒ : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Oz | Oz | declare
proc {Test}
_ = 1 div 0
end
in
try
{Test}
catch E then
{Inspect E}
end |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Perl | Perl | use Carp 'cluck';
Β
sub g {cluck 'Hello from &g';}
sub f {g;}
Β
f; |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.
The amount of information printed for each frame on the call stack is not constrained, but should include at least the name of the function or method at that level of the stack frame.
You may explicitly add a call to produce the stack trace to the (example) code being instrumented for examination.
The task should allow the program to continue after generating the stack trace.
The task report here must include the trace from a sample program.
| #Phix | Phix | constant W = machine_word(),
{RTN,PREVEBP} = iff(W=4?{8,20}:{16,40})
procedure show_stack()
sequence symtab, symtabN
integer rtn
atom prev_ebp
#ilASM{
[32]
lea edi,[symtab]
callΒ :%opGetST -- [edi]=symtab (ie our local:=the real symtab)
mov edi,[ebp+20] -- prev_ebp
mov eax,[edi+8] -- calling routine no
mov [rtn],eax
mov eax,edi
lea edi,[prev_ebp]
callΒ :%pStoreMint
[64]
lea rdi,[symtab]
callΒ :%opGetST -- [rdi]=symtab (ie our local:=the real symtab)
mov rdi,[rbp+40] -- prev_ebp
mov rax,[rdi+16] -- calling routine no
mov [rtn],rax
mov rax,rdi
lea rdi,[prev_ebp]
callΒ :%pStoreMint
[]
}
while rtn!=21 do -- (T_maintls, main top level routine, always present)
symtabN = symtab[rtn]
?symtabN[1]
prev_ebp = peekNS(prev_ebp+PREVEBP,W,0)
rtn = peekNS(prev_ebp+RTN,W,0)
end while
end procedure
procedure three(bool die)
if die then
?9/0
else
show_stack()
end if
end procedure
procedure two(bool die)
three(die)
end procedure
procedure one(bool die)
two(die)
end procedure
one(0)
?routine_id("dummy") -- see note below
one(1)
|
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();
}
}
| #Liberty_BASIC | Liberty BASIC | 'This demo will try to get the robot to step up
'Run it several times to see the differences; sometimes the robot falls
'quite a ways before making it to the next step up, but sometimes he makes it
'on the first try
Β
result = Stepp.Up()
Β
Function Stepp.Up()
While Not(Stepp())
result = Stepp.Up()
Wend
End Function
Β
Function Stepp()
Stepp = Int((Rnd(1) * 2))
If Stepp Then
Print "Robot stepped up"
Else
Print "Robot fell down"
End If
End Function |
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();
}
}
| #Logo | Logo | to step.up
if not step [step.up step.up]
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.