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/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.
| #C.23 | C# | using System;
using System.Diagnostics;
class Program
{
static void Inner()
{
Console.WriteLine(new StackTrace());
}
static void Middle()
{
Inner();
}
static void Outer()
{
Middle();
}
static void Main()
{
Outer();
}
} |
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.
| #Clojure | Clojure |
(doall
(map println (.dumpAllThreads (java.lang.management.ManagementFactory/getThreadMXBean) false false)))
|
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();
}
}
| #Aime | Aime | void step_up(void)
{
while (!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();
}
}
| #ALGOL_68 | ALGOL 68 | PROC step up = VOID:
BEGIN
WHILE NOT step DO
step up
OD
END # step up #; |
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
| #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Data.Char (isLetter, toLower)
import Data.Function (on)
import Data.List (groupBy, nub, sort, sortBy)
-------------------- STATE NAME PUZZLE -------------------
puzzle :: [String] -> [((String, String), (String, String))]
puzzle states =
concatMap
((filter isValid . pairs) . map snd)
( filter ((> 1) . length) $
groupBy ((==) `on` fst) $
sortBy
(compare `on` fst)
[ (pkey (a <> b), (a, b))
| (a, b) <- pairs (nub $ sort states)
]
)
where
pkey = sort . filter isLetter . map toLower
isValid ((a0, a1), (b0, b1)) =
(a0 /= b0)
&& (a0 /= b1)
&& (a1 /= b0)
&& (a1 /= b1)
pairs :: [a] -> [(a, a)]
pairs [] = []
pairs (y : ys) = map (y,) ys <> pairs ys
--------------------------- TEST -------------------------
main :: IO ()
main = do
putStrLn $
"Matching pairs generated from "
<> show (length stateNames)
<> " state names and "
<> show (length fakeStateNames)
<> " fake state names:"
mapM_ print $ puzzle $ stateNames <> fakeStateNames
stateNames :: [String]
stateNames =
[ "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"
]
fakeStateNames :: [String]
fakeStateNames =
[ "New Kory",
"Wen Kory",
"York New",
"Kory New",
"New Kory"
] |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Processing | Processing | println("hello world");
line(0, 0, width, height); |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #PureBasic | PureBasic | [ say "Please use the shell to calculate a value" cr
say "and leave it on the stack. Type 'leave' when" cr
say "you have done this." cr
shell ] constant is my-value |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Quackery | Quackery | [ say "Please use the shell to calculate a value" cr
say "and leave it on the stack. Type 'leave' when" cr
say "you have done this." cr
shell ] constant is my-value |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Racket | Racket |
#/usr/bin/env racket -tm
#lang racket
(provide main)
(define (main . args) (displayln "Hello World!"))
|
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Raku | Raku | BEGIN {...} # as soon as parsed
CHECK {...} # end of compile time
INIT {...} # beginning of run time
END {...} # end of run time |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #REXX | REXX | /*REXX*/
address 'XEDIT'
.
.
.
[XEDIT commands here.]
.
.
. |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #Scala | Scala | object StraddlingCheckerboard extends App {
private val dictonary = Map("H" -> "0", "O" -> "1",
"L" -> "2", "M" -> "4", "E" -> "5", "S" -> "6", "R" -> "8", "T" -> "9",
"A" -> "30", "B" -> "31", "C" -> "32", "D" -> "33", "F" -> "34", "G" -> "35",
"I" -> "36", "J" -> "37", "K" -> "38", "N" -> "39", "P" -> "70", "Q" -> "71",
"U" -> "72", "V" -> "73", "W" -> "74", "X" -> "75", "Y" -> "76", "Z" -> "77",
"." -> "78", "/" -> "79", "0" -> "790", "1" -> "791", "2" -> "792", "3" -> "793",
"4" -> "794", "5" -> "795", "6" -> "796", "7" -> "797", "8" -> "798", "9" -> "799")
private def encode(s: String) =
s.toUpperCase.map { case ch: Char => dictonary.getOrElse(ch.toString, "") }.mkString
private def decode(s: String) = {
val revDictionary: Map[String, String] = dictonary.map {case (k, v) => (v, k)}
val pat = "(79.|3.|7.|.)".r
pat.findAllIn(s).map { el => revDictionary.getOrElse(el, "")}.addString(new StringBuilder)
}
val enc = encode(
"One night-it was on the twentieth of March, " + "1888-I was returning"
)
println(enc)
println(decode(enc))
} |
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.
| #NetRexx | NetRexx | s_ = 'Hello'
s_ = s_', 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.
| #NewLISP | NewLISP | (setq str "foo")
(push "bar" str -1)
; or as an alternative introduced in v.10.1
(extend str "bar")
(println 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.
| #Lasso | Lasso | define stat1(a) => {
if(#a->size) => {
local(mean = (with n in #a sum #n) / #a->size)
local(sdev = math_pow(((with n in #a sum Math_Pow((#n - #mean),2)) / #a->size),0.5))
return (:#sdev, #mean)
else
return (:0,0)
}
}
define stat2(a) => {
if(#a->size) => {
local(sx = 0, sxx = 0)
with x in #a do => {
#sx += #x
#sxx += #x*#x
}
local(sdev = math_pow((#a->size * #sxx - #sx * #sx),0.5) / #a->size)
return (:#sdev, #sx / #a->size)
else
return (:0,0)
}
}
define histogram(a) => {
local(
out = '\r',
h = array(0,0,0,0,0,0,0,0,0,0,0),
maxwidth = 50,
sc = 0
)
with n in #a do => {
if((#n * 10) <= 0) => {
#h->get(1) += 1
else((#n * 10) >= 10)
#h->get(#h->size) += 1
else
#h->get(integer(decimal(#n)*10)+1) += 1
}
}
local(mx = decimal(with n in #h max #n))
with i in #h do => {
#out->append((#sc/10.0)->asString(-precision=1)+': '+('+' * integer(#i / #mx * #maxwidth))+'\r')
#sc++
}
return #out
}
define normalDist(mean,sdev) => {
// Uses Box-Muller transform
return ((-2 * decimal_random->log)->sqrt * (2 * pi * decimal_random)->cos) * #sdev + #mean
}
with scale in array(100,1000,10000) do => {^
local(n = array)
loop(#scale) => { #n->insert(normalDist(0.5, 0.2)) }
local(sdev1,mean1) = stat1(#n)
local(sdev2,mean2) = stat2(#n)
#scale' numbers:\r'
'Naive method: sd: '+#sdev1+', mean: '+#mean1+'\r'
'Second method: sd: '+#sdev2+', mean: '+#mean2+'\r'
histogram(#n)
'\r\r'
^} |
http://rosettacode.org/wiki/Statistics/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.
| #Liberty_BASIC | Liberty BASIC | call sample 100000
end
sub sample n
dim dat( n)
for i =1 to n
dat( i) =normalDist( 1, 0.2)
next i
'// show mean, standard deviation. Find max, min.
mx =-1000
mn = 1000
sum =0
sSq =0
for i =1 to n
d =dat( i)
mx =max( mx, d)
mn =min( mn, d)
sum =sum +d
sSq =sSq +d^2
next i
print n; " data terms used."
mean =sum / n
print "Largest term was "; mx; " & smallest was "; mn
range =mx -mn
print "Mean ="; mean
print "Stddev ="; ( sSq /n -mean^2)^0.5
'// show histogram
nBins =50
dim bins( nBins)
for i =1 to n
z =int( ( dat( i) -mn) /range *nBins)
bins( z) =bins( z) +1
next i
for b =0 to nBins -1
for j =1 to int( nBins *bins( b)) /n *30)
print "#";
next j
print
next b
print
end sub
function normalDist( m, s) ' Box Muller method
u =rnd( 1)
v =rnd( 1)
normalDist =( -2 *log( u))^0.5 *cos( 2 *3.14159265 *v)
end function |
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.
| #Euphoria | Euphoria | include sort.e
procedure leaf_plot(sequence s)
sequence stem
s = sort(s)
stem = repeat({},floor(s[$]/10)+1)
for i = 1 to length(s) do
stem[floor(s[i]/10)+1] &= remainder(s[i],10)
end for
for i = 1 to length(stem) do
printf(1, "%3d | ", i-1)
for j = 1 to length(stem[i]) do
printf(1, "%d ", stem[i][j])
end for
puts(1,'\n')
end for
end procedure
constant 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 }
leaf_plot(data) |
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.
| #C.2B.2B | C++ |
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
unsigned gcd( unsigned i, unsigned j ) {
return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j;
}
void createSequence( std::vector<unsigned>& seq, int c ) {
if( 1500 == seq.size() ) return;
unsigned t = seq.at( c ) + seq.at( c + 1 );
seq.push_back( t );
seq.push_back( seq.at( c + 1 ) );
createSequence( seq, c + 1 );
}
int main( int argc, char* argv[] ) {
std::vector<unsigned> seq( 2, 1 );
createSequence( seq, 0 );
std::cout << "First fifteen members of the sequence:\n ";
for( unsigned x = 0; x < 15; x++ ) {
std::cout << seq[x] << " ";
}
std::cout << "\n\n";
for( unsigned x = 1; x < 11; x++ ) {
std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), x );
if( i != seq.end() ) {
std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
}
}
std::cout << "\n";
std::vector<unsigned>::iterator i = std::find( seq.begin(), seq.end(), 100 );
if( i != seq.end() ) {
std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n";
}
std::cout << "\n";
unsigned g;
bool f = false;
for( int x = 0, y = 1; x < 1000; x++, y++ ) {
g = gcd( seq[x], seq[y] );
if( g != 1 ) f = true;
std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", "
<< seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" );
}
std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n";
return 0;
}
|
http://rosettacode.org/wiki/Stream_merge | Stream merge | 2-stream merge
Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.
Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.
N-stream merge
The same as above, but reading from N sources.
Common algorithm: same as above, but keep buffered items and their source descriptors in a heap.
Assume streams are very big. You must not suck them whole in the memory, but read them as streams.
| #zkl | zkl | fcn mergeStreams(s1,s2,etc){ //-->Walker
streams:=vm.arglist.pump(List(),fcn(s){ // prime and prune
if( (w:=s.walker())._next() ) return(w);
Void.Skip // stream is dry
});
Walker().tweak(fcn(streams){
if(not streams) return(Void.Stop); // all streams are dry
values:=streams.apply("value"); // head of the streams
v:=values.reduce('wrap(min,x){ if(min<=x) min else x });
n:=values.find(v); w:=streams[n]; w._next(); // read next value from min stream
if(w.atEnd) streams.del(n); // prune empty streams
v
}.fp(streams));
} |
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.
| #Common_Lisp | Common Lisp | (swank-backend:call-with-debugging-environment
(lambda ()
(swank:backtrace 0 nil))) |
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.
| #D | D | import std.stdio, core.runtime;
void inner() { defaultTraceHandler.writeln; }
void middle() { inner; }
void outer() { middle; }
void main() {
outer;
"After the stack trace.".writeln;
} |
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();
}
}
| #Arturo | Arturo | Position: 0
stepUp: function [].export:[Position][
startPos: Position
until -> step [
Position = startPos + 1
]
]
step: function [].export:[Position][
(0.5 > random 0 1.0)? [
Position: Position - 1
print ~"fall (|Position|)"
false
][
Position: Position + 1
print ~"rise (|Position|)"
true
]
]
stepUp |
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();
}
}
| #AutoHotkey | AutoHotkey | step_up()
{
While !step()
step_up()
} |
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
| #Icon_and_Unicon | Icon and Unicon | link strings # for csort and deletec
procedure main(arglist)
ECsolve(S1 := getStates()) # original state names puzzle
ECsolve(S2 := getStates2()) # modified fictious names puzzle
GNsolve(S1)
GNsolve(S2)
end
procedure ECsolve(S) # Solve challenge using equivalence classes
local T,x,y,z,i,t,s,l,m
st := &time # mark runtime
/S := getStates() # default
every insert(states := set(),deletec(map(!S),' \t')) # ignore case & space
# Build a table containing sets of state name pairs
# keyed off of canonical form of the pair
# Use csort(s) rather than cset(s) to preserve the numbers of each letter
# Since we care not of X&Y .vs. Y&X keep only X&Y
T := table()
every (x := !states ) & ( y := !states ) do
if z := csort(x || (x << y)) then {
/T[z] := []
put(T[z],set(x,y))
}
# For each unique key (canonical pair) find intersection of all pairs
# Output is <current key matched> <key> <pairs>
i := m := 0 # keys (i) and pairs (m) matched
every z := key(T) do {
s := &null
every l := !T[z] do {
/s := l
s **:= l
}
if *s = 0 then {
i +:= 1
m +:= *T[z]
every x := !T[z] do {
#writes(i," ",z) # uncomment for equiv class and match count
every writes(!x," ")
write()
}
}
}
write("... runtime ",(&time - st)/1000.,"\n",m," matches found.")
end |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Ring | Ring |
func Main
see "Hello World!" + nl
|
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Ruby | Ruby | BEGIN {
# begin code
}
END {
# end code
} |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Scala | Scala | object PrimaryMain extends App {
Console.println("Hello World: " + (args mkString ", "))
}
object MainTheSecond extends App {
Console.println("Goodbye, World: " + (args mkString ", "))
} |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #sed | sed | # This code runs only for line 1.
1 {
i\
Explain-a-lot processed this file and
i\
replaced every period with three exclamation points!!!
i\
}
# This code runs for each line of input.
s/\./!!!/g |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
begin
writeln("hello world");
end func; |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Tcl | Tcl | SUB Main()
' This is the start of the program
END |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #Tcl | Tcl | package require Tcl 8.6
oo::class create StraddlingCheckerboardCypher {
variable encmap decmap
constructor table {
# Sanity check the table
foreach ch [lindex $table 0] i {"" 0 1 2 3 4 5 6 7 8 9} {
if {$ch eq "" && $i ne "" && [lsearch -index 0 $table $i] < 1} {
error "bad checkerboard table"
}
}
# Synthesize the escaped number row
foreach row $table {
if {"/" ni $row} continue
set pfx [lindex $row 0][expr {[lsearch -exact $row "/"]-1}]
lappend table [list $pfx 0 1 2 3 4 5 6 7 8 9]
break
}
# Build the actual per-character mapping
foreach row $table {
foreach ch [lrange $row 1 end] n {0 1 2 3 4 5 6 7 8 9} {
if {$ch in {"" "/"}} continue; # Skip escape cases
lappend encmap $ch [lindex $row 0]$n
lappend decmap [lindex $row 0]$n $ch
}
}
}
# These methods just sanitize their input and apply the map
method encode msg {
string map $encmap [regsub -all {[^A-Z0-9.]} [string toupper $msg] ""]
}
method decode msg {
string map $decmap [regsub -all {[^0-9]} $msg ""]
}
} |
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.
| #Nim | Nim | var str = "123456"
str.add("78") # Using procedure "add".
str &= "9!" # Using operator "&=".
echo str
|
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.
| #NS-HUBASIC | NS-HUBASIC | 10 S$ = "HELLO"
20 S$ = S$ + " WORLD!"
30 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.
| #Objeck | Objeck |
class Append {
function : Main(args : String[]) ~ Nil {
x := "foo";
x->Append("bar");
x->PrintLine();
}
}
|
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.
| #Lua | Lua | function gaussian (mean, variance)
return math.sqrt(-2 * variance * math.log(math.random())) *
math.cos(2 * math.pi * math.random()) + mean
end
function mean (t)
local sum = 0
for k, v in pairs(t) do
sum = sum + v
end
return sum / #t
end
function std (t)
local squares, avg = 0, mean(t)
for k, v in pairs(t) do
squares = squares + ((avg - v) ^ 2)
end
local variance = squares / #t
return math.sqrt(variance)
end
function showHistogram (t)
local lo = math.ceil(math.min(unpack(t)))
local hi = math.floor(math.max(unpack(t)))
local hist, barScale = {}, 200
for i = lo, hi do
hist[i] = 0
for k, v in pairs(t) do
if math.ceil(v - 0.5) == i then
hist[i] = hist[i] + 1
end
end
io.write(i .. "\t" .. string.rep('=', hist[i] / #t * barScale))
print(" " .. hist[i])
end
end
math.randomseed(os.time())
local t, average, variance = {}, 50, 10
for i = 1, 1000 do
table.insert(t, gaussian(average, variance))
end
print("Mean:", mean(t) .. ", expected " .. average)
print("StdDev:", std(t) .. ", expected " .. math.sqrt(variance) .. "\n")
showHistogram(t) |
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.
| #F.23 | F# | open System
let data =
[ 12; 127; 28; 42; 39; 113; 42; 18; 44; 118; 44; 37; 113; 124; 37; 48;
127; 36; 29; 31; 125; 139; 131; 115; 105; 132; 104; 123; 35; 113; 122;
42; 117; 119; 58; 109; 23; 105; 63; 27; 44; 105; 99; 41; 128; 121; 116;
125; 32; 61; 37; 127; 29; 113; 121; 58; 114; 126; 53; 114; 96; 25; 109;
7; 31; 141; 46; 13; 27; 43; 117; 116; 27; 7; 68; 40; 31; 115; 124; 42;
128; 52; 71; 118; 117; 38; 27; 106; 33; 117; 116; 111; 40; 119; 47; 105;
57; 122; 109; 124; 115; 43; 120; 43; 27; 27; 18; 28; 48; 125; 107; 114;
34; 133; 45; 120; 30; 127; 31; 116; 146 ]
let plotStemAndLeafs items =
let groupedItems = items |> Seq.sort
|> Seq.map (fun i -> i / 10, i % 10)
|> Seq.groupBy fst
let maxStem = groupedItems |> Seq.maxBy fst |> fst
let stemLeafMap = Map.ofSeq groupedItems
[0..maxStem] |> List.iter (fun stm -> printf " %2d | " stm
match stemLeafMap.TryFind stm with
| None -> ()
| Some items -> items |> Seq.iter (snd >> printf "%d ")
printfn "")
plotStemAndLeafs data |
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.
| #Clojure | Clojure | ;; each step adds two items
(defn sb-step [v]
(let [i (quot (count v) 2)]
(conj v (+ (v (dec i)) (v i)) (v i))))
;; A lazy, infinite sequence -- `take` what you want.
(def all-sbs (sequence (map peek) (iterate sb-step [1 1])))
;; zero-based
(defn first-appearance [n]
(first (keep-indexed (fn [i x] (when (= x n) i)) all-sbs)))
;; inlined abs; rem is slightly faster than mod, and the same result for positive values
(defn gcd [a b]
(loop [a (if (neg? a) (- a) a)
b (if (neg? b) (- b) b)]
(if (zero? b)
a
(recur b (rem a b)))))
(defn check-pairwise-gcd [cnt]
(let [sbs (take (inc cnt) all-sbs)]
(every? #(= 1 %) (map gcd sbs (rest sbs)))))
;; one-based index required by problem statement
(defn report-sb []
(println "First 15 Stern-Brocot members:" (take 15 all-sbs))
(println "First appearance of N at 1-based index:")
(doseq [n [1 2 3 4 5 6 7 8 9 10 100]]
(println " first" n "at" (inc (first-appearance n))))
(println "Check pairwise GCDs = 1 ..." (check-pairwise-gcd 1000))
true)
(report-sb) |
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.
| #DWScript | DWScript | procedure Inner;
begin
try
raise Exception.Create('');
except
on E: Exception do
PrintLn(E.StackTrace);
end;
end;
procedure Middle;
begin
Inner;
end;
procedure Outer;
begin
Middle;
end;
Outer; |
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.
| #Elena | Elena | import extensions;
public singleton program
{
inner()
{
console.printLine(new CallStack())
}
middle()
{
self.inner()
}
outer()
{
self.middle()
}
// program entry point
function()
{
program.outer()
}
} |
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();
}
}
| #AWK | AWK |
function step_up() {
while (!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();
}
}
| #BASIC | BASIC | SUB stepup
IF NOT step1 THEN stepup: stepup
END SUB |
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
| #J | J | require'strings stats'
states=:<;._2]0 :0-.LF
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,
Maine,Maine,Maine,Maine,Maine,Maine,Maine,Maine,
)
pairUp=: (#~ matchUp)@({~ 2 comb #)@~.
matchUp=: (i.~ ~: i:~)@:(<@normalize@;"1)
normalize=: /:~@tolower@-.&' ' |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Visual_Basic | Visual Basic | SUB Main()
' This is the start of the program
END |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Collections.ObjectModel
Imports Microsoft.VisualBasic.ApplicationServices
Namespace My
' The following events are available for MyApplication:
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
'''<summary>Sets the visual styles, text display styles, and current principal for the main application thread
'''(if the application uses Windows authentication), and initializes the splash screen, if defined.</summary>
'''<param name="commandLineArgs">A <see cref="ReadOnlyCollection(Of T)" /> of <see langword="String" />,
'''containing the command-line arguments as strings for the current application.</param>
'''<returns>A <see cref="T:System.Boolean" /> indicating if application startup should continue.</returns>
Protected Overrides Function OnInitialize(commandLineArgs As ReadOnlyCollection(Of String)) As Boolean
Console.WriteLine("oninitialize; args: " & String.Join(", ", commandLineArgs))
Return MyBase.OnInitialize(commandLineArgs)
End Function
' WindowsFormsApplicationBase.Startup occurs "when the application starts".
Private Sub MyApplication_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup
Console.WriteLine("startup; args: " & String.Join(", ", e.CommandLine))
End Sub
'''<summary>Provides the starting point for when the main application is ready to start running, after the
'''initialization is done.</summary>
Protected Overrides Sub OnRun()
Console.WriteLine("onrun")
MyBase.OnRun()
End Sub
End Class
End Namespace |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Wren | Wren | var main = Fn.new {
System.print("Hello from the main function.")
}
main.call() |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #VBScript | VBScript | ' Straddling checkerboard - VBScript - 19/04/2019
Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2)
Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ."
Dim i, j, curChar, escChar, outText
Dim cipher 'Hash table
Set cipher = CreateObject("Scripting.Dictionary")
'build cipher reference
alphabet = UCase(alphabet) : j = 0
For i = 1 To 28
curChar = Mid(alphabet, i, 1)
Select Case True
Case i>= 1 And i<= 8
If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank
cipher.Add curChar, CStr(j)
j = j + 1
Case i>= 9 And i<=18
cipher.Add curChar, CStr(blank1) & CStr(i - 9)
Case i>=19 And i<=28
cipher.Add curChar, CStr(blank2) & CStr(i - 19)
End Select 'i
If InStr(notEscape, curChar) = 0 Then
escChar = curChar
'Wscript.Echo "escChar=" & escChar & " cipher(escChar)=" & cipher(escChar)
End If
Next 'i
For i = 0 To 9: cipher.Add CStr(i), cipher(escChar) & CStr(i): Next
'encrypt each character
originalText = UCase(originalText)
For i = 1 To Len(originalText)
outText = outText & cipher(Mid(originalText, i, 1))
Next
encrypt=outText
End Function 'encrypt
Function decrypt(ByVal cipherText, ByVal alphabet, blank1, blank2)
Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ."
Dim i, j, curChar, escCipher, outText
Dim cipher 'Hash table
Set cipher = CreateObject("Scripting.Dictionary")
'build decipher reference
alphabet = UCase(alphabet) : j = 0
For i = 1 To 28
curChar = Mid(alphabet, i, 1)
Select Case True
Case i>= 1 And i<= 8
If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank
cipher.Add CStr(j),curChar
j = j + 1
Case i>= 9 And i<=18
cipher.Add CStr(blank1) & CStr(i - 9), curChar
Case i>=19 And i<=28
cipher.Add CStr(blank2) & CStr(i - 19), curChar
End Select 'i
If InStr(notEscape, curChar) = 0 Then
'the last element of cipher
arrayKeys=cipher.keys
escCipher = arrayKeys(cipher.count-1)
'Wscript.Echo "escCipher=" & escCipher & " cipher(escCipher)=" & cipher(escCipher)
End If
Next 'i
For i = 0 To 9: cipher.Add escCipher & CStr(i), CStr(i): Next
'decrypt each character
i = 1
Do While i <= Len(cipherText)
curChar = Mid(cipherText, i, 1)
If curChar = CStr(blank1) Or curChar = CStr(blank2) Then
curChar = Mid(cipherText, i, 2)
If curChar = escCipher Then curChar = Mid(cipherText, i, 3)
End If
outText = outText & cipher(curChar)
i = i + Len(curChar)
Loop 'i
decrypt=outText
End Function 'decrypt
message = "One night-it was on the twentieth of March, 1888-I was returning"
cipher = "HOLMESRTABCDFGIJKNPQUVWXYZ./"
'3 7 <=8
'HOL MES RT
'ABCDFGIJKN
'PQUVWXYZ./
Buffer=Buffer & "Original: " & message & vbCrlf
encoded = encrypt(message, cipher, 3, 7)
Buffer=Buffer & "encoded: " & encoded & vbCrlf
decoded = decrypt(encoded, cipher, 3, 7)
Buffer=Buffer & "decoded: " & decoded & vbCrlf
Wscript.Echo Buffer |
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.
| #OCaml | OCaml | let () =
let s = Buffer.create 17 in
Buffer.add_string s "Bonjour";
Buffer.add_string s " tout le monde!";
print_endline (Buffer.contents 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.
| #Oforth | Oforth | StringBuffer new "Hello, " << "World!" << println |
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.
| #Maple | Maple | with(Statistics):
n := 100000:
X := Sample( Normal(0,1), n );
Mean( X );
StandardDeviation( X );
Histogram( 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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | x:= RandomReal[1]
SampleNormal[n_] := (Print[#//Length, " numbers, Mean : ", #//Mean, ", StandardDeviation : ", #//StandardDeviation];
Histogram[#, BarOrigin -> Left,Axes -> False])& [(Table[(-2*Log[x])^0.5*Cos[2*Pi*x], {n} ]]
Invocation:
SampleNormal[ 10000 ]
->10000 numbers, Mean : -0.0122308, StandardDeviation : 1.00646
|
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.
| #Factor | Factor | USING: assocs formatting grouping.extras io kernel math
prettyprint sequences sorting ;
: leaf-plot ( seq -- )
natural-sort [ 10 /i ] group-by dup keys last 1 +
[ dup "%2d | " printf of [ 10 mod pprint bl ] each nl ] with
each-integer ;
{
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 146 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
} leaf-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.
| #CLU | CLU | stern = proc (n: int) returns (array[int])
s: array[int] := array[int]$fill(1, n, 1)
for i: int in int$from_to(2, n/2) do
s[i*2-1] := s[i] + s[i-1]
s[i*2] := s[i]
end
return (s)
end stern
gcd = proc (a,b: int) returns (int)
while b ~= 0 do
a, b := b, a//b
end
return (a)
end gcd
find = proc [T: type] (a: array[T], val: T) returns (int) signals (not_found)
where T has equal: proctype (T,T) returns (bool)
for i: int in array[T]$indexes(a) do
if a[i] = val then return (i) end
end
signal not_found
end find
start_up = proc ()
po: stream := stream$primary_output()
s: array[int] := stern(1200)
stream$puts(po, "First 15 numbers:")
for i: int in int$from_to(1, 15) do
stream$puts(po, " " || int$unparse(s[i]))
end
stream$putl(po, "")
for i: int in int$from_to(1, 10) do
stream$putl(po, "First " || int$unparse(i) || " at " ||
int$unparse(find[int](s, i)))
end
stream$putl(po, "First 100 at " || int$unparse(find[int](s, 100)))
begin
for i: int in int$from_to(2, array[int]$high(s)) do
if gcd(s[i-1], s[i]) ~= 1 then
exit gcd_not_one(i)
end
end
stream$putl(po, "The GCD of every pair of adjacent elements is 1.")
end except when gcd_not_one(i: int):
stream$putl(po, "The GCD of the pair at " || int$unparse(i) || " is not 1.")
end
end start_up |
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.
| #Elixir | Elixir | defmodule Stack_traces do
def main do
{:ok, a} = outer
IO.inspect a
end
defp outer do
{:ok, a} = middle
{:ok, a}
end
defp middle do
{:ok, a} = inner
{:ok, a}
end
defp inner do
try do
throw(42)
catch 42 -> {:ok, :erlang.get_stacktrace}
end
end
end
Stack_traces.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.
| #Erlang | Erlang | -module(stack_traces).
-export([main/0]).
main() ->
{ok,A} = outer(),
io:format("~p\n", [A]).
outer() ->
{ok,A} = middle(),
{ok,A}.
middle() ->
{ok,A} = inner(),
{ok,A}.
inner() ->
try throw(42) catch 42 -> {ok,erlang:get_stacktrace()} 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();
}
}
| #BBC_BASIC | BBC BASIC | DEF PROCstepup
IF NOT FNstep PROCstepup : PROCstepup
ENDPROC |
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();
}
}
| #C | C | void step_up(void)
{
while (!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();
}
}
| #C.23 | C# | void step_up() {
while (!step()) step_up();
} |
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
| #Java | Java | import java.util.*;
import java.util.stream.*;
public class StateNamePuzzle {
static String[] states = {"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "Florida",
"Georgia", "hawaii", "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",};
public static void main(String[] args) {
solve(Arrays.asList(states));
}
static void solve(List<String> input) {
Map<String, String> orig = input.stream().collect(Collectors.toMap(
s -> s.replaceAll("\\s", "").toLowerCase(), s -> s, (s, a) -> s));
input = new ArrayList<>(orig.keySet());
Map<String, List<String[]>> map = new HashMap<>();
for (int i = 0; i < input.size() - 1; i++) {
String pair0 = input.get(i);
for (int j = i + 1; j < input.size(); j++) {
String[] pair = {pair0, input.get(j)};
String s = pair0 + pair[1];
String key = Arrays.toString(s.chars().sorted().toArray());
List<String[]> val = map.getOrDefault(key, new ArrayList<>());
val.add(pair);
map.put(key, val);
}
}
map.forEach((key, list) -> {
for (int i = 0; i < list.size() - 1; i++) {
String[] a = list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String[] b = list.get(j);
if (Stream.of(a[0], a[1], b[0], b[1]).distinct().count() < 4)
continue;
System.out.printf("%s + %s = %s + %s %n", orig.get(a[0]),
orig.get(a[1]), orig.get(b[0]), orig.get(b[1]));
}
}
});
}
} |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #XBasic | XBasic | FUNCTION main ()
'This is the beginning of the program
END FUNCTION |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #Z80_Assembly | Z80 Assembly | org &8000 |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #zkl | zkl | "Hello".println() |
http://rosettacode.org/wiki/Start_from_a_main_routine | Start from a main routine |
Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.
Task
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | SAVE "MYPROG" LINE 500: REM For a program with main code starting at line 500 |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #Wren | Wren | import "/str" for Str
var board = "ET AON RISBCDFGHJKLMPQ/UVWXYZ."
var digits = "0123456789"
var rows = " 26"
var escape = "62"
var key = "0452"
var encrypt = Fn.new { |message|
var msg = Str.upper(message).
where { |c| (board.contains(c) || digits.contains(c)) && !" /".contains(c) }.join()
var sb = ""
for (c in msg) {
var idx = board.indexOf(c)
if (idx > -1) {
var row = (idx/10).floor
var col = idx % 10
sb = sb + ((row == 0) ? "%(col)" : "%(rows[row])%(col)")
} else {
sb = sb + "%(escape)%(c)"
}
}
var enc = sb.bytes.toList
var i = 0
for (c in enc) {
var k = key[i%4].bytes[0] - 48
if (k != 0) {
var j = c - 48
enc[i] = 48 + ((j + k) % 10)
}
i = i + 1
}
return enc.map { |b| String.fromByte(b) }.join()
}
var decrypt = Fn.new { |encoded|
var enc = encoded.bytes.toList
var i = 0
for (c in enc) {
var k = key[i%4].bytes[0] - 48
if (k != 0) {
var j = c - 48
enc[i] = 48 + ((j >= k) ? (j - k) % 10 : (10 + j - k) % 10)
}
i = i + 1
}
var len = enc.count
var sb = ""
i = 0
while (i < len) {
var c = enc[i]
var idx = rows.indexOf((c-48).toString)
if (idx == -1) {
var idx2 = c - 48
sb = sb + board[idx2]
i = i + 1
} else if ("%(c-48)%(enc[i + 1]-48)" == escape) {
sb = sb + (enc[i + 2] - 48).toString
i = i + 3
} else {
var idx2 = idx * 10 + enc[i + 1] - 48
sb = sb + board[idx2]
i = i + 2
}
}
return sb
}
var messages = [
"Attack at dawn",
"One night-it was on the twentieth of March, 1888-I was returning",
"In the winter 1965/we were hungry/just barely alive",
"you have put on 7.5 pounds since I saw you.",
"The checkerboard cake recipe specifies 3 large eggs and 2.25 cups of flour."
]
for (message in messages) {
var encrypted = encrypt.call(message)
var decrypted = decrypt.call(encrypted)
System.print("\nMessage : %(message)")
System.print("Encrypted : %(encrypted)")
System.print("Decrypted : %(decrypted)")
} |
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.
| #PARI.2FGP | PARI/GP | s = "Hello";
s = Str(s, ", world!") |
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.
| #Pascal | Pascal | program StringAppend;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
s: String = 'Hello';
begin
s += ' World !';
WriteLn(S);
ReadLn;
end. |
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.
| #MATLAB_.2F_Octave | MATLAB / Octave | N = 100000;
x = randn(N,1);
mean(x)
std(x)
[nn,xx] = hist(x,100);
bar(xx,nn); |
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.
| #Nim | Nim | import math, random, sequtils, stats, strformat, strutils
proc drawHistogram(ns: seq[float]) =
# Distribute values in bins.
const NBins = 50
var minval = min(ns)
var maxval = max(ns)
var h = newSeq[int](NBins + 1)
for n in ns:
let pos = ((n - minval) * NBins / (maxval - minval)).toInt
inc h[pos]
# Eliminate extremes values.
const MaxWidth = 50
let mx = max(h)
var first = 0
while (h[first] / mx * MaxWidth).toInt == 0: inc first
var last = h.high
while (h[last] / mx * MaxWidth).toInt == 0: dec last
# Draw the histogram.
echo ""
for n in first..last:
echo repeat('+', (h[n] / mx * MaxWidth).toInt)
echo ""
const N = 100_000
randomize()
let u1, u2 = newSeqWith(N, rand(1.0))
var z = newSeq[float](N)
for i in 0..<N:
z[i] = sqrt(-2 * ln(u1[i])) * cos(2 * PI * u2[i])
echo &"μ = {z.mean:.12f} σ = {z.standardDeviation:.12f}"
z.drawHistogram() |
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.
| #Forth | Forth | create 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 ,
here constant data-end
: sort ( end start -- )
over cell - swap do
dup i cell+ do
i @ j @ < if
i @ j @ i ! j !
then
cell +loop
cell +loop drop ;
: plot
data-end data sort
data
data-end cell - @ 10 / 1+
data @ 10 /
do
cr i 2 u.r ." | "
begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then
loop
drop ;
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.
| #Common_Lisp | Common Lisp | (defun stern-brocot (numbers)
(declare ((or null (vector integer)) numbers))
(cond ((null numbers)
(setf numbers (make-array 2 :element-type 'integer :adjustable t :fill-pointer t
:initial-element 1)))
((zerop (length numbers))
(vector-push-extend 1 numbers)
(vector-push-extend 1 numbers))
(t
(assert (evenp (length numbers)))
(let* ((considered-index (/ (length numbers) 2))
(considered (aref numbers considered-index))
(precedent (aref numbers (1- considered-index))))
(vector-push-extend (+ considered precedent) numbers)
(vector-push-extend considered numbers))))
numbers)
(defun first-15 ()
(loop for input = nil then seq
for seq = (stern-brocot input)
while (< (length seq) 15)
finally (format t "First 15: ~{~A~^ ~}~%" (coerce (subseq seq 0 15) 'list))))
(defun first-1-to-10 ()
(loop with seq = (stern-brocot nil)
for i from 1 to 10
for index = (loop with start = 0
for pos = (position i seq :start start)
until pos
do (setf start (length seq)
seq (stern-brocot seq))
finally (return (1+ pos)))
do (format t "First ~D at ~D~%" i index)))
(defun first-100 ()
(loop for input = nil then seq
for start = (length input)
for seq = (stern-brocot input)
for pos = (position 100 seq :start start)
until pos
finally (format t "First 100 at ~D~%" (1+ pos))))
(defun check-gcd ()
(loop for input = nil then seq
for seq = (stern-brocot input)
while (< (length seq) 1000)
finally (if (loop for i from 0 below 999
always (= 1 (gcd (aref seq i) (aref seq (1+ i)))))
(write-line "Correct. The GCDs of all the two consecutive numbers are 1.")
(write-line "Wrong."))))
(defun main ()
(first-15)
(first-1-to-10)
(first-100)
(check-gcd)) |
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.
| #F.23 | F# | open System.Diagnostics
type myClass() =
member this.inner() = printfn "%A" (new StackTrace())
member this.middle() = this.inner()
member this.outer() = this.middle()
[<EntryPoint>]
let main args =
let that = new myClass()
that.outer()
0 |
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.
| #Factor | Factor | USE: prettyprint
get-callstack callstack. |
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();
}
}
| #C.2B.2B | C++ | void step_up()
{
while (!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();
}
}
| #Clojure | Clojure | ;; the initial level
(def level (atom 41))
;; the probability of success
(def prob 0.5001)
(defn step
[]
(let [success (< (rand) prob)]
(swap! level (if success inc dec))
success) ) |
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
| #jq | jq | # Input: a string
# Output: an array, being the exploded form of the normalized input
def normalize:
explode
| map(if . >= 97 then (. - 97) elif . >= 65 then (. - 65) else empty end);
# Input: an array of strings
# Output: a dictionary with key:value pairs: normalizedString:string
def dictionary:
reduce .[] as $s ( {}; . + { ($s|normalize|implode): $s });
# Input: an array of strings (e.g. state names)
# Output: a stream of solutions
def solve:
# Given a pair of normalized state names as lists of integers:
def nletters: map(length) | add;
# input [[s1,s2], [t2,t2]]
def solved:
( .[0] | add | sort) == (.[1] | add | sort);
unique
| length as $l
| dictionary as $dictionary
| ($dictionary | keys | map(explode)) as $states
| reduce ( range(0; $l) as $s1
| range($s1+1; $l) as $s2
| range($s1+1; $l) as $t1
| select($s2 != $t1)
| range($t1+1; $l) as $t2
| select($s2 != $t2)
| [[$states[$s1], $states[$s2]], [$states[$t1], $states[$t2]]] ) as $quad
([];
if ($quad[0] | nletters) == ($quad[1] | nletters)
and ($quad | solved)
then . + [$quad | map( map( $dictionary[ implode ] ))]
else .
end)
| .[]; |
http://rosettacode.org/wiki/Straddling_checkerboard | Straddling checkerboard | Task
Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits.
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
| #zkl | zkl | var [const]
val2key=Dictionary(
"A","30", "B","31", "C","32", "D","33", "E","5", "F","34", "G","35",
"H","0", "I","36", "J","37", "K","38", "L","2", "M","4", ".","78",
"N","39", "/","79", "O","1", "0","790", "P","70", "1","791", "Q","71",
"2","792", "R","8", "3","793", "S","6", "4","794" ,"T","9", "5","795",
"U","72", "6","796", "V","73", "7","797", "W","74", "8","798", "X","75",
"9","799", "Y","76", "Z","77"),
key2val=val2key.pump(Dictionary(),"reverse");
fcn encode(txt){ txt.toUpper().pump(String,val2key.find.fp1("")) }
fcn decode(str){ RegExp("79.|3.|7.|.").pump(str,String,key2val.get) } |
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.
| #Perl | Perl | my $str = 'Foo';
$str .= 'bar';
print $str; |
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.
| #Phix | Phix | string s = "this string" ?s
s &= " is now longer" ?s
|
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.
| #PARI.2FGP | PARI/GP | rnormal()={
my(u1=random(1.),u2=random(1.);
sqrt(-2*log(u1))*cos(2*Pi*u1)
\\ Could easily be extended with a second normal at very little cost.
};
mean(v)={
sum(i=1,#v,v[i])/#v
};
stdev(v,mu="")={
if(mu=="",mu=mean(v));
sqrt(sum(i=1,#v,(v[i]-mu)^2))/#v
};
histogram(v,bins=16,low=0,high=1)={
my(u=vector(bins),width=(high-low)/bins);
for(i=1,#v,u[(v[i]-low)\width+1]++);
u
};
show(n)={
my(v=vector(n,i,rnormal()),m=mean(v),s=stdev(v,m),h,sz=ceil(n/300));
h=histogram(v,,vecmin(v)-.1,vecmax(v)+.1);
for(i=1,#h,for(j=1,h[i]\sz,print1("#"));print());
};
show(10^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.
| #Fortran | Fortran |
SUBROUTINE COMBSORT(A,N)
INTEGER A(*) !The array.
INTEGER N !The count.
INTEGER H,T !Assistants.
LOGICAL CURSE
H = N - 1 !Last - First, and not +1.
1 H = MAX(1,H*10/13) !The special feature.
IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle.
CURSE = .FALSE. !So far, so good.
DO I = N - H,1,-1 !If H = 1, this is a BubbleSort.
IF (A(I) .GT. A(I + H)) THEN !One compare.
T=A(I); A(I)=A(I+H); A(I+H)=T !One swap.
CURSE = .TRUE. !One curse.
END IF !One test.
END DO !One loop.
IF (CURSE .OR. H.GT.1) GO TO 1 !Work remains?
END SUBROUTINE COMBSORT !Good performance, small code.
SUBROUTINE TOPIARY(A,N) !Produces a "stem&leaf" display for the integers in A, damaging A.
INTEGER A(*) !An array of integers.
INTEGER N !Their number.
INTEGER CLIP !Semi-generalisation.
PARAMETER (CLIP = 10) !Or at least, annotation.
INTEGER I1,I2,STEM !Assistants.
CALL COMBSORT(A,N) !Rearrange the array!
STEM = A(1)/CLIP !The first stem value.
I1 = 1 !The first stem's span starts here.
I2 = I1 !And so far as I know, ends here.
10 I2 = I2 + 1 !Probe ahead one position.
IF (I2 .GT. N) GO TO 11 !Off the end? Don't look!
IF (A(I2)/CLIP .EQ.STEM) GO TO 10 !Still in the same stem? Probe on.
Cast forth a STEM line, corresponding to elements I1:I2 - 1.
11 WRITE (6,12) STEM,ABS(MOD(A(I1:I2 - 1),CLIP)) !ABS: MOD with negatives can be unexpected.
12 FORMAT (I4,"|",(100I1)) !Layout. If more than a hundred, starts a new line.
IF (I2 .GT. N) RETURN !Are we there yet?
I1 = I2 !No. This is my new span's start.
Chug along to the next STEM value.
13 STEM = STEM + 1 !Advance to the next stem.
IF (A(I2)/CLIP.GT.STEM) GO TO 11!Has the stem reached the impending value?
GO TO 10 !Yes. Scan its span.
END SUBROUTINE TOPIARY !The days of carefully-arranged output.
PROGRAM TEST
INTEGER VALUES(121) !The exact number of values.
DATA VALUES/ !As in the specified example.
o 12,127, 28, 42, 39,113, 42, 18, 44,118, !A regular array
1 44, 37,113,124, 37, 48,127, 36, 29, 31, !Makes counting easier.
2 125,139,131,115,105,132,104,123, 35,113,
3 122, 42,117,119, 58,109, 23,105, 63, 27,
4 44,105, 99, 41,128,121,116,125, 32, 61,
5 37,127, 29,113,121, 58,114,126, 53,114,
6 96, 25,109, 7, 31,141, 46, 13, 27, 43,
7 117,116, 27, 7, 68, 40, 31,115,124, 42,
8 128, 52, 71,118,117, 38, 27,106, 33,117,
9 116,111, 40,119, 47,105, 57,122,109,124,
o 115, 43,120, 43, 27, 27, 18, 28, 48,125,
1 107,114, 34,133, 45,120, 30,127, 31,116,
2 146/
CALL TOPIARY(VALUES,121)
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.
| #Cowgol | Cowgol | include "cowgol.coh";
# Redefining these is enough to change the type and length everywhere,
# but arrays are 0-based so you need one extra element.
typedef Stern is uint8; # 8-bit math is enough for the numbers we need
var stern: Stern[1201]; # Array containing Stern-Brocot sequence
# Fill up the Stern-Brocot array
sub GenStern() is
stern[1] := 1;
stern[2] := 1;
var i: @indexof stern := 1;
var last: @indexof stern := @sizeof stern / 2;
while i <= last loop
stern[i*2-1] := stern[i] + stern[i-1];
stern[i*2] := stern[i];
i := i + 1;
end loop;
end sub;
# Find the first location of a given number
sub FindFirst(n: Stern): (i: @indexof stern) is
i := 1;
while i < @sizeof stern and stern[i] != n loop
i := i + 1;
end loop;
end sub;
GenStern(); # Generate sequence
# Print the first 15 numbers
var i: @indexof stern := 1;
while i <= 15 loop
print_i32(stern[i] as uint32);
print_char(' ');
i := i + 1;
end loop;
print_nl();
# Print the first occurrence of 1..10
var j: Stern := 1;
while j <= 10 loop
print_i32(FindFirst(j) as uint32);
print_char(' ');
j := j + 1;
end loop;
print_nl();
# Print the first occurrence of 100
print_i32(FindFirst(100) as uint32);
print_nl();
# Check that all GCDs of consecutive pairs are 1
sub gcd(a: Stern, b: Stern): (r: Stern) is
while a != b loop
if a > b then
a := a - b;
else
b := b - a;
end if;
end loop;
r := a;
end sub;
i := 1;
while i < @sizeof stern / 2 loop
if gcd(stern[i], stern[i+1]) != 1 then
print("GCD not 1 at: ");
print_i32(i as uint32);
print_nl();
ExitWithError();
end if;
i := i + 1;
end loop;
print("All GCDs are 1.\n"); |
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.
| #Forth | Forth | [UNDEFINED] R.S [IF]
\ Return stack counterpart of DEPTH
\ Note the STACK-CELLS correction is there to hide RDEPTH itself
( -- n)
: RDEPTH STACK-CELLS -2 [+] CELLS RP@ - ;
\ Return stack counterpart of .S
\ Note the : R.S R> .. >R ; sequence is there to hide R.S itself
( --)
: R.S R> CR RDEPTH DUP 0> IF DUP
BEGIN DUP WHILE R> -ROT 1- REPEAT DROP DUP
BEGIN DUP WHILE ROT DUP . >R 1- REPEAT DROP
THEN ." (TORS) " DROP >R ;
[THEN] |
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.
| #Fortran | Fortran | Gnash: croak Life is troubled
Goodbye, cruel world!
Routine XeqACard croaks: Life is troubled
...from XeqACard Confronting croak Life is troubled
...from Attack some input
...from Gnash Gnash gnashing
Omitted exit from level 3:XeqACard
Omitted exit from level 2:Attack
|
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.
| #Go | Go | package main
import (
"fmt"
"runtime"
)
func main() {
stackTrace := make([]byte, 1024)
n := runtime.Stack(stackTrace, true)
stackTrace = stackTrace[:n]
fmt.Printf("%s\n", stackTrace)
fmt.Printf("(%d bytes)\n", len(stackTrace))
} |
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();
}
}
| #Common_Lisp | Common Lisp | (defun step-up ()
(unless (step) (step-up) (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();
}
}
| #D | D | void step_up()
{
while(!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();
}
}
| #E | E | var level := 41
var prob := 0.5001
def step() {
def success := entropy.nextDouble() < prob
level += success.pick(1, -1)
return success
} |
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
| #Julia | Julia | module StateNamePuzzle
const realnames = ["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"]
const fictitious = ["New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]
function combine(a::AbstractString, b::AbstractString)
chars = vcat(collect(Char, a), collect(Char, b))
sort!(chars)
return join(chars)
end
function solve(input::Vector{<:AbstractString})
dict = Dict{String,String}()
for state in input
key = replace(state, " ", "") |> lowercase
if !haskey(dict, key)
dict[key] = state
end
end
keyset = collect(keys(dict))
solutions = String[]
duplicates = String[]
for i in eachindex(keyset), j in (i+1):endof(keyset)
len1 = length(keyset[i]) + length(keyset[j])
combined1 = combine(keyset[i], keyset[j])
for k in eachindex(keyset), l in k+1:endof(keyset)
k ∈ (i, j) && continue
l ∈ (i, j) && continue
len2 = length(keyset[k]) + length(keyset[l])
len1 != len2 && continue
combined2 = combine(keyset[k], keyset[l])
if combined1 == combined2
f1 = dict[keyset[i]] * " + " * dict[keyset[j]]
f2 = dict[keyset[k]] * " + " * dict[keyset[l]]
f3 = f1 * " = " * f2
f3 ∈ duplicates && continue
push!(solutions, f3)
f4 = f2 * " = " * f1
push!(duplicates, f4)
end
end
end
return sort!(solutions)
end
end # module StateNamePuzzle |
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
| #Kotlin | Kotlin | // version 1.2.10
fun solve(states: List<String>) {
val dict = mutableMapOf<String, String>()
for (state in states) {
val key = state.toLowerCase().replace(" ", "")
if (dict[key] == null) dict.put(key, state)
}
val keys = dict.keys.toList()
val solutions = mutableListOf<String>()
val duplicates = mutableListOf<String>()
for (i in 0 until keys.size) {
for (j in i + 1 until keys.size) {
val len = keys[i].length + keys[j].length
val chars = (keys[i] + keys[j]).toCharArray()
chars.sort()
val combined = String(chars)
for (k in 0 until keys.size) {
for (l in k + 1 until keys.size) {
if (k == i || k == j || l == i || l == j) continue
val len2 = keys[k].length + keys[l].length
if (len2 != len) continue
val chars2 = (keys[k] + keys[l]).toCharArray()
chars2.sort()
val combined2 = String(chars2)
if (combined == combined2) {
val f1 = "${dict[keys[i]]} + ${dict[keys[j]]}"
val f2 = "${dict[keys[k]]} + ${dict[keys[l]]}"
val f3 = "$f1 = $f2"
if (f3 in duplicates) continue
solutions.add(f3)
val f4 = "$f2 = $f1"
duplicates.add(f4)
}
}
}
}
}
solutions.sort()
for ((i, sol) in solutions.withIndex()) {
println("%2d %s".format(i + 1, sol))
}
}
fun main(args: Array<String>) {
val states = listOf(
"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"
)
println("Real states only:")
solve(states)
println()
val fictitious = listOf(
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory"
)
println("Real and fictitious states:")
solve(states + fictitious)
} |
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.
| #Picat | Picat | main =>
S = "a string",
S := S + " that is longer",
println(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.
| #PicoLisp | PicoLisp | (setq Str1 "12345678")
(setq Str1 (pack Str1 "9!"))
(println Str1) |
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.
| #Pascal | Pascal | Program Example40;
{$IFDEF FPC}
{$MOde objFPC}
{$ENDIF}
{ Program to demonstrate the randg function. }
Uses Math;
type
tTestData = extended;//because of math.randg
ttstfunc = function (mean, sd: tTestData): tTestData;
tExArray = Array of tTestData;
tSolution = record
SolExArr : tExArray;
SollowVal,
SolHighVal,
SolMean,
SolStdDiv : tTestData;
SolSmpCnt : LongInt;
end;
function getSol(genFunc:ttstfunc;Mean,StdDiv: tTestData;smpCnt: LongInt): tSolution;
var
GenValue,
sumValue,
sumsqrVal : extended;
Begin
with result do
Begin
SolSmpCnt := smpCnt;
SolMean := 0;
SolStdDiv := 0;
SolLowVal := Mean+50* StdDiv;
SolHighVal := Mean-50* StdDiv;
setlength(SolExArr,smpCnt);
if smpCnt <= 0 then
EXIT;
sumValue := 0;
sumsqrVal := 0;
repeat
GenValue := genFunc(Mean,StdDiv);
sumValue := sumvalue+GenValue;
sumsqrVal := sumsqrVal+sqr(GenValue);
IF GenValue < SollowVal then
SollowVal:= GenValue
else
IF GenValue > SolHighVal then
SolHighVal := GenValue;
dec(smpCnt);
SolExArr[smpCnt] := GenValue;
until smpCnt<= 0;
SolMean := sumValue/SolSmpCnt;
SolStdDiv := sqrt(sumsqrVal/SolSmpCnt-sqr(SolMean));
end;
end;
//http://wiki.freepascal.org/Generating_Random_Numbers#Normal_.28Gaussian.29_Distribution
function rnorm (mean, sd: tTestData): tTestData;
{Calculates Gaussian random numbers according to the Box-Müller approach}
var
u1, u2: extended;
begin
u1 := random;
u2 := random;
rnorm := mean * abs(1 + sqrt(-2 * (ln(u1))) * cos(2 * pi * u2) * sd);
end;
procedure Histo(const sol:TSolution;Colcnt,ColLen :LongInt);
var
CntHisto : array of integer;
LoLmt,HiLmt,span : tTestData;
i, j,cnt,maxCnt: LongInt;
sCross : Ansistring;
Begin
setlength(CntHisto,Colcnt);
with Sol do
Begin
span := solHighVal-solLowVal;
LoLmt := solLowVal;
writeln('Count: ',SolSmpCnt:10,' Mean ',SolMean:10:6,' StdDiv ',SolStdDIv:10:6);
writeln('span : ',span:10:5,' Low ',solLowVal:10:6,' high ',solHighVal:10:6);
end;
maxCnt := 0;
For j := 0 to Colcnt-1 do
Begin
HiLmt:= LoLmt+span/Colcnt;
cnt := 0;
with sol do
For i := 0 to High(SolExArr) do
IF (HiLmt > SolExArr[i]) AND (SolExArr[i]>= LoLmt) then
inc(cnt);
CntHisto[j] := cnt;
IF maxCnt < cnt then
maxCnt := cnt;
LoLmt:= HiLmt;
end;
inc(CntHisto[Colcnt]); // for HiLmt itself
writeln;
LoLmt := sol.solLowVal;
For i := 0 to Colcnt-1 do
Begin
Writeln(LoLmt:8:4,': ');
cnt:= Round(CntHisto[i]*ColLen/maxCnt);
setlength(sCross,cnt+3);
fillChar(sCross[1],3,' ');
fillChar(sCross[4],cnt,'#');
writeln(CntHisto[i]:10,sCross);
LoLmt := LoLmt+span/Colcnt;
end;
Writeln(sol.solHighVal:8:4,': ');
end;
const
cHistCnt = 11;
cColLen = 65;
cStdDiv = 0.25;
cMean = 20*cStdDiv;
var
mySol : tSolution;
begin
Randomize;
// test of randg of unit math
Writeln('function randg');
mySol := getSol(@randg,cMean,cMean*cStdDiv,100000);
Histo(mySol,cHistCnt,cColLen);
writeln;
// test of rnorm from wiki
Writeln('function rnorm');
mySol := getSol(@rnorm,cMean,cStdDiv,1000000);
Histo(mySol,cHistCnt,cColLen);
end. |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #FreeBASIC | FreeBASIC | ' version 22-06-2015
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
' from the rosetta code FreeBASIC entry
#Define out_of_data 99999999 ' any number that is not in the set will do
Sub shellsort(s() As Integer)
' from the FreeBASIC entry at rosetta code
' sort from lower bound to the highter bound
Dim As Integer lb = LBound(s)
Dim As Integer ub = UBound(s)
Dim As Integer done, i, inc = ub - lb
Do
inc = inc / 2.2
If inc < 1 Then inc = 1
Do
done = 0
For i = lb To ub - inc
If s(i) > s(i + inc) Then
Swap s(i), s(i + inc)
done = 1
End If
Next
Loop Until done = 0
Loop Until inc = 1
End Sub
' ------=< TASK DATA >=------
Data 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124
Data 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123
Data 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105
Data 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58
Data 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43
Data 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118
Data 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122
Data 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114
Data 34, 133, 45, 120, 30, 127, 31, 116, 146
Data out_of_data
' ------=< MAIN >=------
Dim As String read_in
Dim As Integer i, x, y, count = -1 ' to let the index start on 0
Dim As Integer d()
ReDim d(300) ' big enough to hold data index start at 0
Do
Read i
If i = out_of_data Then Exit Do
count = count + 1
d(count) = i
Loop
ReDim Preserve d(count) ' trim the data array
shellsort(d()) ' sort data array
i = 0
For y = d(0) \ 10 To d(UBound(d)) \ 10
Print Using "#### |"; y;
Do
x = d(i) \ 10 ' \ = integer division
If y = x Then
Print Using "##"; d(i) Mod 10;
i = i + 1
Else
Exit Do
End If
Loop While i <= UBound(d)
Print ' force linefeed
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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.
| #D | D | import std.stdio, std.numeric, std.range, std.algorithm;
/// Generates members of the stern-brocot series, in order,
/// returning them when the predicate becomes false.
uint[] sternBrocot(bool delegate(in uint[]) pure nothrow @safe @nogc pred=seq => seq.length < 20)
pure nothrow @safe {
typeof(return) sb = [1, 1];
size_t i = 0;
while (pred(sb)) {
sb ~= [sb[i .. i + 2].sum, sb[i + 1]];
i++;
}
return sb;
}
void main() {
enum nFirst = 15;
writefln("The first %d values:\n%s\n", nFirst,
sternBrocot(seq => seq.length < nFirst).take(nFirst));
foreach (immutable nOccur; iota(1, 10 + 1).chain(100.only))
writefln("1-based index of the first occurrence of %3d in the series: %d",
nOccur, sternBrocot(seq => nOccur != seq[$ - 2]).length - 1);
enum nGcd = 1_000;
auto s = sternBrocot(seq => seq.length < nGcd).take(nGcd);
assert(zip(s, s.dropOne).all!(ss => ss[].gcd == 1),
"A fraction from adjacent terms is reducible.");
} |
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.
| #Groovy | Groovy | def rawTrace = { Thread.currentThread().stackTrace } |
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.
| #Icon_and_Unicon | Icon and Unicon |
import Utils # for buildStackTrace
procedure main()
g()
write()
f()
end
procedure f()
g()
end
procedure g()
# Using 1 as argument omits the trace of buildStackTrace itself
every write("\t",!buildStackTrace(1))
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.
| #J | J | 13!:0]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();
}
}
| #EchoLisp | EchoLisp |
(define (step-up) (while (not (step)) (step-up)))
;; checking this is tail-recusive :
step-up
→ (#λ null (#while (#not (step)) (#lambda-tail-call)))
;; Experimentation (not part of the task)
;; How much step calls to climb 1000 stairs ?
;; success is the robot success probability
(define (step)
(set! STEPS (1+ STEPS)) ;; count
(< (random) SUCCESS)) ;; ->#t or #f
(define (climb stairs)
(when (> stairs 0) (step-up) (climb (1- stairs))))
(define (task (stairs 1000))
(for ((success (in-range 1 0 -5/100)))
(set! SUCCESS success)
(set! STEPS 0)
(climb stairs)
(writeln 'stairs stairs 'probability success 'steps STEPS)))
|
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();
}
}
| #Elixir | Elixir | defmodule Stair_climbing do
defp step, do: 1 == :rand.uniform(2)
defp step_up(true), do: :ok
defp step_up(false) do
step_up(step)
step_up(step)
end
def step_up, do: step_up(step)
end
IO.inspect Stair_climbing.step_up |
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
| #11l | 11l | F SquareFree(_number)
V max = Int(sqrt(_number))
L(root) 2 .. max
I 0 == _number % (Int64(root) ^ 2)
R 0B
R 1B
F ListSquareFrees(Int64 _start, Int64 _end)
V count = 0
L(i) _start .. _end
I SquareFree(i)
print(i"\t", end' ‘’)
I count % 5 == 4
print()
count++
print("\n\nTotal count of square-free numbers between #. and #.: #.".format(_start, _end, count))
ListSquareFrees(1, 100)
ListSquareFrees(1000000000000, 1000000000145) |
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
| #LiveCode | LiveCode | function pairwiseAnagrams X
if the optionkey is down then breakpoint
put the long seconds into T
put empty into itemsSoFar
repeat for each item W in X
put word 1 to -1 of W into W
if D[W] = 1 then next repeat
put 1 into D[W]
repeat for each item W2 in itemsSoFar
put W,W2 & cr after WPairs[sortChars(W & W2,true)]
end repeat
put W & comma after itemsSoFar
end repeat
repeat for each key K in WPairs
put empty into pairsSoFar
repeat for each line L in WPairs[K]
repeat for each line L2 in pairsSoFar
if item 1 of L is among the items of L2 or item 2 of L is among the items of L2 then next repeat
put L && "and" && L2 & cr after R
end repeat
put L & cr after pairsSoFar
end repeat
end repeat
put the long seconds - T
return char 1 to -2 of R
end pairwiseAnagrams
function sortChars X,lettersOnly
get charsToItems(X,lettersOnly)
sort items of it
return itemsToChars(it)
end sortChars
function charsToItems X,lettersOnly
repeat for each char C in X
if lettersOnly and C is not in "abcdefghijklmnopqrstuvwxyz" then next repeat
put C & comma after R
end repeat
return char 1 to -2 of R
end charsToItems
function itemsToChars X
replace comma with empty in X
return X
end itemsToChars |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.