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/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.
| #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
import "/math" for Nums
var rgen = Random.new()
// Box-Muller method from Wikipedia
var normal = Fn.new { |mu, sigma|
var u1 = rgen.float()
var u2 = rgen.float()
var mag = sigma * (-2 * u1.log).sqrt
var z0 = mag * (2 * Num.pi * u2).cos + mu
var z1 = mag * (2 * Num.pi * u2).sin + mu
return [z0, z1]
}
var N = 100000
var NUM_BINS = 12
var HIST_CHAR = "■"
var HIST_CHAR_SIZE = 250
var bins = List.filled(NUM_BINS, 0)
var binSize = 0.1
var samples = List.filled(N, 0)
var mu = 0.5
var sigma = 0.25
for (i in 0...N/2) {
var rns = normal.call(mu, sigma)
for (j in 0..1) {
var rn = rns[j]
var bn
if (rn < 0) {
bn = 0
} else if (rn >= 1) {
bn = 11
} else {
bn = (rn/binSize).floor + 1
}
bins[bn] = bins[bn] + 1
samples[i*2 + j] = rn
}
}
Fmt.print("Normal distribution with mean $0.2f and S/D $0.2f for $,d samples:\n", mu, sigma, N)
System.print(" Range Number of samples within that range")
for (i in 0...NUM_BINS) {
var hist = HIST_CHAR * (bins[i] / HIST_CHAR_SIZE).round
if (i == 0) {
Fmt.print(" -∞ ..< 0.00 $s $,d", hist, bins[0])
} else if (i < NUM_BINS - 1) {
Fmt.print("$4.2f ..< $4.2f $s $,d", binSize * (i-1), binSize * i, hist, bins[i])
} else {
Fmt.print("1.00 ... +∞ $s $,d", hist, bins[NUM_BINS - 1])
}
}
Fmt.print("\nActual mean for these samples : $0.5f", Nums.mean(samples))
Fmt.print("Actual S/D for these samples : $0.5f", Nums.stdDev(samples)) |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | len[n_] := RealDigits[n][[2]]; padding = len[Max@ Quotient[inputdata, 10]];
For[i = Min@ Quotient[inputdata, 10],i <= Max@ Quotient[inputdata, 10], i++,
(Print[i, If[(padding - len[i]) > 0, (padding - len[i])*" " <> " |", " |"] ,
StringJoin[(" " <> #) & /@ Map[ToString, #]]])&@
Select[{Quotient[#, 10], Mod[#, 10]} & /@ Sort[inputdata],Part[#, 1] == i &][[;; , 2]]] |
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.
| #jq | jq | def until(cond; update):
def _until:
if cond then . else (update | _until) end;
try _until catch if .== "break" then empty else . end ;
def gcd(a; b):
# subfunction expects [a,b] as input
# i.e. a ~ .[0] and b ~ .[1]
def rgcd: if .[1] == 0 then .[0]
else [.[1], .[0] % .[1]] | rgcd
end;
[a,b] | rgcd ; |
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.
| #Scala | Scala | def callStack = try { error("exception") } catch { case ex => ex.getStackTrace drop 2 }
def printStackTrace = callStack drop 1 /* don't print ourselves! */ foreach println |
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.
| #Slate | Slate | slate[1]> d@(Debugger traits) printCurrentStack &limit: limit &stream: out &showLocation: showLocation
[
d clone `>> [baseFramePointer: (d interpreter framePointerOf: #printCurrentStack).
buildFrames.
printBacktrace &limit: limit &stream: out &showLocation: showLocation ]
].
Defining function 'printCurrentStack' on: 'Debugger traits'
[printCurrentStack &limit: &stream: &showLocation:] |
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();
}
}
| #Python | Python | def step_up1():
"""Straightforward implementation: keep track of how many level we
need to ascend, and stop when this count is zero."""
deficit = 1
while deficit > 0:
if step():
deficit -= 1
else:
deficit += 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();
}
}
| #Quackery | Quackery | [ step if done recurse again ] is 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();
}
}
| #R | R | step <- function() {
success <- runif(1) > p
## Requires that the "robot" is a variable named "level"
level <<- level - 1 + (2 * success)
success
} |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Action.21 | Action! | DEFINE MAXSIZE="200"
BYTE ARRAY stack(MAXSIZE)
BYTE stacksize=[0]
BYTE FUNC IsEmpty()
IF stacksize=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Push(BYTE v)
IF stacksize=maxsize THEN
PrintE("Error: stack is full!")
Break()
FI
stack(stacksize)=v
stacksize==+1
RETURN
BYTE FUNC Pop()
IF IsEmpty() THEN
PrintE("Error: stack is empty!")
Break()
FI
stacksize==-1
RETURN (stack(stacksize))
PROC TestIsEmpty()
IF IsEmpty() THEN
PrintE("Stack is empty")
ELSE
PrintE("Stack is not empty")
FI
RETURN
PROC TestPush(BYTE v)
PrintF("Push: %B%E",v)
Push(v)
RETURN
PROC TestPop()
BYTE v
Print("Pop: ")
v=Pop()
PrintBE(v)
RETURN
PROC Main()
TestIsEmpty()
TestPush(10)
TestIsEmpty()
TestPush(31)
TestPop()
TestIsEmpty()
TestPush(5)
TestPop()
TestPop()
TestPop()
RETURN |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Java | Java | import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.math.BigInteger;
class UserManager {
private Connection dbConnection;
public UserManager() {
}
private String md5(String aString) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
String hex;
StringBuffer hexString;
byte[] bytesOfMessage;
byte[] theDigest;
hexString = new StringBuffer();
bytesOfMessage = aString.getBytes("UTF-8");
md = MessageDigest.getInstance("MD5");
theDigest = md.digest(bytesOfMessage);
for (int i = 0; i < theDigest.length; i++) {
hex = Integer.toHexString(0xff & theDigest[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
public void connectDB(String host, int port, String db, String user, String password)
throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
this.dbConnection = DriverManager.getConnection("jdbc:mysql://"
+ host
+ ":"
+ port
+ "/"
+ db, user, password);
}
public boolean createUser(String user, String password) {
SecureRandom random;
String insert;
String salt;
random = new SecureRandom();
salt = new BigInteger(130, random).toString(16);
insert = "INSERT INTO users "
+ "(username, pass_salt, pass_md5) "
+ "VALUES (?, ?, ?)";
try (PreparedStatement pstmt = this.dbConnection.prepareStatement(insert)) {
pstmt.setString(1, user);
pstmt.setString(2, salt);
pstmt.setString(3, this.md5(salt + password));
pstmt.executeUpdate();
return true;
} catch(NoSuchAlgorithmException | SQLException | UnsupportedEncodingException ex) {
return false;
}
}
public boolean authenticateUser(String user, String password) {
String pass_md5;
String pass_salt;
String select;
ResultSet res;
select = "SELECT pass_salt, pass_md5 FROM users WHERE username = ?";
res = null;
try(PreparedStatement pstmt = this.dbConnection.prepareStatement(select)) {
pstmt.setString(1, user);
res = pstmt.executeQuery();
res.next(); // We assume that username is unique
pass_salt = res.getString(1);
pass_md5 = res.getString(2);
if (pass_md5.equals(this.md5(pass_salt + password))) {
return true;
} else {
return false;
}
} catch(NoSuchAlgorithmException | SQLException | UnsupportedEncodingException ex) {
return false;
} finally {
try {
if (res instanceof ResultSet && !res.isClosed()) {
res.close();
}
} catch(SQLException ex) {
}
}
}
public void closeConnection() {
try {
this.dbConnection.close();
} catch(NullPointerException | SQLException ex) {
}
}
public static void main(String[] args) {
UserManager um;
um = new UserManager();
try {
um.connectDB("localhost", 3306, "test", "root", "admin");
if (um.createUser("johndoe", "test")) {
System.out.println("User created");
}
if (um.authenticateUser("johndoe", "test")) {
System.out.println("User authenticated");
}
} catch(ClassNotFoundException | SQLException ex) {
ex.printStackTrace();
} finally {
um.closeConnection();
}
}
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #AWK | AWK |
# syntax: GAWK -f SQUARE_BUT_NOT_CUBE.AWK
BEGIN {
while (n < 30) {
sqpow = ++square ^ 2
if (is_cube(sqpow) == 0) {
n++
printf("%4d\n",sqpow)
}
else {
printf("%4d is square and cube\n",sqpow)
}
}
exit(0)
}
function is_cube(x, i) {
for (i=1; i<=x; i++) {
if (i ^ 3 == x) {
return(1)
}
}
return(0)
}
|
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Fortran | Fortran | program basic_stats
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer, parameter :: r64 = selected_real_kind(15)
integer(i64), parameter :: samples = 1000000000_i64
real(r64) :: r
real(r64) :: mean, stddev
real(r64) :: sumn = 0, sumnsq = 0
integer(i64) :: n = 0
integer(i64) :: bin(10) = 0
integer :: i, ind
call random_seed
n = 0
do while(n <= samples)
call random_number(r)
ind = r * 10 + 1
bin(ind) = bin(ind) + 1_i64
sumn = sumn + r
sumnsq = sumnsq + r*r
n = n + 1_i64
end do
mean = sumn / n
stddev = sqrt(sumnsq/n - mean*mean)
write(*, "(a, i0)") "sample size = ", samples
write(*, "(a, f17.15)") "Mean : ", mean,
write(*, "(a, f17.15)") "Stddev : ", stddev
do i = 1, 10
write(*, "(f3.1, a, a)") real(i)/10.0, ": ", repeat("=", int(bin(i)*500/samples))
end do
end program |
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
| #Lua | Lua | function squareFree (n)
for root = 2, math.sqrt(n) do
if n % (root * root) == 0 then return false end
end
return true
end
function run (lo, hi, showValues)
io.write("From " .. lo .. " to " .. hi)
io.write(showValues and ":\n" or " = ")
local count = 0
for i = lo, hi do
if squareFree(i) then
if showValues then
io.write(i, "\t")
else
count = count + 1
end
end
end
print(showValues and "\n" or count)
end
local testCases = {
{1, 145, true},
{1000000000000, 1000000000145, true},
{1, 100},
{1, 1000},
{1, 10000},
{1, 100000},
{1, 1000000}
}
for _, example in pairs(testCases) do run(unpack(example)) end |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Most languages provide a way to concatenate two string values, but some languages also provide a convenient way to append in-place to an existing string variable without referring to the variable twice.
Task
Create a string variable equal to any text value.
Append the string variable with another string literal in the most idiomatic way, without double reference if your language supports it.
Show the contents of the variable after the append operation.
| #zkl | zkl | var s="foo";
s.append("bar"); //-->new string "foobar", var s unchanged
s+="bar"; //-->new string "foobar", var s modifed to new value
s=Data(Void,"foo"); // byte blob/character blob/text editor buffer
s.append("bar"); // or s+="bar"
s.text; //-->"foobar" |
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.
| #zkl | zkl | fcn norm2{ // Box-Muller
const PI2=(0.0).pi*2;;
rnd:=(0.0).random.fp(1); // random number in [0,1), using partial application
r,a:=(-2.0*rnd().log()).sqrt(), PI2*rnd();
return(r*a.cos(), r*a.sin()); // z0,z1
}
const N=100000, BINS=12, SIG=3, SCALE=500;
var sum=0.0,sumSq=0.0, h=BINS.pump(List(),0); // (0,0,0,...)
fcn accum(v){
sum+=v;
sumSq+=v*v;
b:=(v + SIG)*BINS/SIG/2;
if(0<=b<BINS) h[b]+=1;
}; |
http://rosettacode.org/wiki/Stem-and-leaf_plot | Stem-and-leaf plot | Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits:
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146
The primary intent of this task is the presentation of information. It is acceptable to hardcode the data set or characteristics of it (such as what the stems are) in the example, insofar as it is impractical to make the example generic to any data set. For example, in a computation-less language like HTML the data set may be entirely prearranged within the example; the interesting characteristics are how the proper visual formatting is arranged.
If possible, the output should not be a bitmap image. Monospaced plain text is acceptable, but do better if you can. It may be a window, i.e. not a file.
Note: If you wish to try multiple data sets, you might try this generator.
| #MATLAB_.2F_Octave | MATLAB / Octave | function stem_and_leaf_plot(x,stem_unit,leaf_unit)
if nargin < 2, stem_unit = 10; end;
if nargin < 3,
leaf_unit = 1;
else
x = leaf_unit*round(x/leaf_unit);
end;
stem = floor(x/stem_unit);
leaf = mod(x,stem_unit);
for k = min(stem):max(stem)
printf('\n%d |',k)
printf(' %d' ,sort(leaf(k==stem)))
end;
printf('\nkey:6|3=63\n');
printf('leaf unit: %.1f\n',leaf_unit);
printf('stem unit: %.1f\n',stem_unit);
end;
x = [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146];
stem_and_leaf_plot(x); |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | F split(input, delim)
V res = ‘’
L(ch) input
I !res.empty & ch != res.last
res ‘’= delim
res ‘’= ch
R res
print(split(‘gHHH5YY++///\’, ‘, ’)) |
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.
| #Julia | Julia | using Printf
function sternbrocot(f::Function=(x) -> length(x) ≥ 20)::Vector{Int}
rst = Int[1, 1]
i = 2
while !f(rst)
append!(rst, Int[rst[i] + rst[i-1], rst[i]])
i += 1
end
return rst
end
println("First 15 elements of Stern-Brocot series:\n", sternbrocot(x -> length(x) ≥ 15)[1:15], "\n")
for i in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100)
occurr = findfirst(x -> x == i, sternbrocot(x -> i ∈ x))
@printf("Index of first occurrence of %3i in the series: %4i\n", i, occurr)
end
print("\nAssertion: the greatest common divisor of all the two\nconsecutive members of the series up to the 1000th member, is always one: ")
sb = sternbrocot(x -> length(x) > 1000)
if all(gcd(prev, this) == 1 for (prev, this) in zip(sb[1:1000], sb[2:1000]))
println("Confirmed.")
else
println("Rejected.")
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.
| #Smalltalk | Smalltalk | Object subclass: Container [
Container class >> outer: a and: b and: c [
self middle: (a+b) and: (b+c)
]
Container class >> middle: x and: y [
self inner: (x*y)
]
Container class >> inner: k [
Smalltalk backtrace
]
].
Container outer: 2 and: 3 and: 5.
'Anyway, we continue with it' displayNl. |
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.
| #Tcl | Tcl | proc printStackTrace {} {
puts "Stack trace:"
for {set i 1} {$i < [info level]} {incr i} {
puts [string repeat " " $i][info level $i]
}
} |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Racket | Racket | #lang racket
(define p 0.5001)
(define (step)
(> p (random)))
(define (step-up n)
(cond ((zero? n) 'done)
((step) (step-up (sub1 n)))
(else (step-up (add1 n)))))
(step-up 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();
}
}
| #Raku | Raku | sub step_up { step_up until step; } |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #REBOL | REBOL | rebol [
Title: "Stair Climber"
URL: http://rosettacode.org/wiki/Stair_Climbing
]
random/seed now
step: does [random/only reduce [yes no]]
; Iterative solution with symbol stack. No numbers, draws a nifty
; diagram of number of steps to go. This is intended more to
; demonstrate a correct solution:
step_up: func [/steps s] [
either not steps [
print "Starting up..."
step_up/steps copy [|]
][
while [not empty? s][
print [" Steps left:" s]
either step [remove s][append s '|]
]
]
]
step_up print ["Success!" crlf]
; Recursive solution. No numbers, no variables. "R" means a recover
; step, "+" means a step up.
step_upr: does [if not step [prin "R " step_upr prin "+ " step_upr]]
step_upr print ["Success!" crlf]
; Small recursive solution, no monitoring:
step_upt: does [if not step [step_upt step_upt]]
step_upt print "Success!" |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ActionScript | ActionScript | var stack:Array = new Array();
stack.push(1);
stack.push(2);
trace(stack.pop()); // outputs "2"
trace(stack.pop()); // outputs "1" |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Julia | Julia |
using MySQL
using Nettle # for md5
function connect_db(uri, user, pw, dbname)
mydb = mysql_connect(uri, user, pw, dbname)
const command = """CREATE TABLE IF NOT EXISTS users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);"""
mysql_execute(mydb, command)
mydb
end
function create_user(dbh, user, pw)
mysql_stmt_prepare(dbh, "INSERT IGNORE INTO users (username, pass_salt, pass_md5) values (?, ?, ?);")
salt = join([Char(c) for c in rand(UInt8, 16)], "")
passmd5 = digest("md5", salt * pw)
mysql_execute(dbh, [MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR], [user, salt, passmd5])
end
function addusers(dbh, userdict)
for user in keys(userdict)
create_user(dbh, user, userdict[user])
end
end
"""
authenticate_user
Note this returns true if password provided authenticates as correct, false otherwise
"""
function authenticate_user(dbh, username, pw)
mysql_stmt_prepare(dbh, "SELECT pass_salt, pass_md5 FROM users WHERE username = ?;")
pass_salt, pass_md5 = mysql_execute(dbh, [MYSQL_TYPE_VARCHAR], [username], opformat=MYSQL_TUPLES)[1]
pass_md5 == digest("md5", pass_salt * pw)
end
const users = Dict("Joan" => "joanspw", "John" => "johnspw", "Mary" => "marpw", "Mark" => "markpw")
const mydb = connect_db("192.168.1.1", "julia", "julia", "mydb")
addusers(mydb, users)
println("""John authenticates correctly: $(authenticate_user(mydb, "John", "johnspw")==true)""")
println("""Mary does not authenticate with password of 123: $(authenticate_user(mydb, "Mary", "123")==false)""")
mysql_disconnect(mydb)
|
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Kotlin | Kotlin | // Version 1.2.41
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.security.MessageDigest
import java.security.SecureRandom
import java.math.BigInteger
class UserManager {
private lateinit var dbConnection: Connection
private fun md5(message: String): String {
val hexString = StringBuilder()
val bytes = message.toByteArray()
val md = MessageDigest.getInstance("MD5")
val dig = md.digest(bytes)
for (i in 0 until dig.size) {
val hex = (0xff and dig[i].toInt()).toString(16)
if (hex.length == 1) hexString.append('0')
hexString.append(hex)
}
return hexString.toString()
}
fun connectDB(host: String, port: Int, db: String, user: String, pwd: String) {
Class.forName("com.mysql.jdbc.Driver")
dbConnection = DriverManager.getConnection(
"jdbc:mysql://$host:$port/$db", user, pwd
)
}
fun createUser(user: String, pwd: String): Boolean {
val random = SecureRandom()
val salt = BigInteger(130, random).toString(16)
val insert = "INSERT INTO users " +
"(username, pass_salt, pass_md5) " +
"VALUES (?, ?, ?)"
try {
val pstmt = dbConnection.prepareStatement(insert)
with (pstmt) {
setString(1, user)
setString(2, salt)
setString(3, md5(salt + pwd))
val rowCount = executeUpdate()
close()
if (rowCount == 0) return false
}
return true
}
catch (ex: Exception) {
return false
}
}
fun authenticateUser(user: String, pwd: String): Boolean {
val select = "SELECT pass_salt, pass_md5 FROM users WHERE username = ?"
lateinit var res: ResultSet
try {
val pstmt = dbConnection.prepareStatement(select)
with (pstmt) {
setString(1, user)
res = executeQuery()
res.next() // assuming that username is unique
val passSalt = res.getString(1)
val passMD5 = res.getString(2)
close()
return passMD5 == md5(passSalt + pwd)
}
}
catch (ex: Exception) {
return false
}
finally {
if (!res.isClosed) res.close()
}
}
fun closeConnection() {
if (!dbConnection.isClosed) dbConnection.close()
}
}
fun main(args: Array<String>) {
val um = UserManager()
with (um) {
try {
connectDB("localhost", 3306, "test", "root", "admin")
if (createUser("johndoe", "test")) println("User created")
if (authenticateUser("johndoe", "test")) {
println("User authenticated")
}
}
catch(ex: Exception) {
ex.printStackTrace()
}
finally {
closeConnection()
}
}
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #BASIC | BASIC | 10 DEFINT C,S,Q,R,N: C=1: S=1: Q=1: R=1: N=1
20 IF N>30 THEN END
30 S=Q*Q
40 IF S>C THEN R=R+1: C=R*R*R: GOTO 40
50 IF S<C THEN N=N+1: PRINT S;
60 Q=Q+1
70 GOTO 20 |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #BCPL | BCPL | get "libhdr"
let square(x) = x * x
let cube(x) = x * x * x
let start() be
$( let c, s, seen = 1, 1, 0
while seen < 30 do
$( while cube(c) < square(s) do c := c + 1
if square(s) ~= cube(c) then
$( writed(square(s), 5)
seen := seen + 1
if seen rem 5 = 0 then wrch('*N')
$)
s := s + 1
$)
$) |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Randomize
Sub basicStats(sampleSize As Integer)
If sampleSize < 1 Then Return
Dim r(1 To sampleSize) As Double
Dim h(0 To 9) As Integer '' all zero by default
Dim sum As Double = 0.0
Dim hSum As Integer = 0
' Generate 'sampleSize' random numbers in the interval [0, 1)
' calculate their sum
' and in which box they will fall when drawing the histogram
For i As Integer = 1 To sampleSize
r(i) = Rnd
sum += r(i)
h(Int(r(i) * 10)) += 1
Next
For i As Integer = 0 To 9 : hSum += h(i) : Next
' adjust one of the h() values if necessary to ensure hSum = sampleSize
Dim adj As Integer = sampleSize - hSum
If adj <> 0 Then
For i As Integer = 0 To 9
h(i) += adj
If h(i) >= 0 Then Exit For
h(i) -= adj
Next
End If
Dim mean As Double = sum / sampleSize
Dim sd As Double
sum = 0.0
' Now calculate their standard deviation
For i As Integer = 1 To sampleSize
sum += (r(i) - mean) ^ 2.0
Next
sd = Sqr(sum/sampleSize)
' Draw a histogram of the data with interval 0.1
Dim numStars As Integer
' If sample size > 500 then normalize histogram to 500
Dim scale As Double = 1.0
If sampleSize > 500 Then scale = 500.0 / sampleSize
Print "Sample size "; sampleSize
Print
Print Using " Mean #.######"; mean;
Print Using " SD #.######"; sd
Print
For i As Integer = 0 To 9
Print Using " #.## : "; i/10.0;
Print Using "##### " ; h(i);
numStars = Int(h(i) * scale + 0.5)
Print String(numStars, "*")
Next
End Sub
basicStats 100
Print
basicStats 1000
Print
basicStats 10000
Print
basicStats 100000
Print
Print "Press any key to quit"
Sleep |
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
| #Maple | Maple |
with(NumberTheory):
with(ArrayTools):
squareFree := proc(n::integer)
if mul(PrimeFactors(n)) = n then return true;
else return false; end if;
return true;
end proc:
sfintegers := Array([]):
for count from 1 to 145 do
if squareFree(count) then Append(sfintegers, count); end if;
end do:
print(sfintegers):
sfintegers := Array([]):
for count from 10^12 to 10^12+145 do
if squareFree(count) then Append(sfintegers, count); end if;
end do:
print(sfintegers):
sfgroups := Array([]):
sfcount := 0:
for number from 1 to 100 do
if squareFree(number) then sfcount += 1: end if:
end do:
Append(sfgroups, sfcount):
for expon from 3 to 6 do
for number from 10^(expon - 1) to 10^expon do
if squareFree(number) then sfcount += 1: end if:
end do:
Append(sfgroups, sfcount):
end do:
seq(cat(sfgroups[i], " from 1 to ", 10^(i+1)), i = 1..5);
|
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.
| #Maxima | Maxima | load(descrptive)$
data: [12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127,
36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119,
58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127,
29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43,
117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106,
33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27,
27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146]$
stemplot(data);
0|77
1|2388
2|357777778899
3|011112345677789
4|001222233344456788
5|23788
6|138
7|1
9|69
10|4555567999
11|13333444555666677778899
12|00112234445556777788
13|1239
14|16 |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Split the string under DE on changing characters,
;;; and store the result at HL.
split: ldax d ; Load character from string
spcopy: mov m,a ; Store in output
cpi '$' ; CP/M string terminator
rz ; Stop when the end is reached
mov b,a ; Store previous character in B
inx d ; Increment input pointer
inx h ; Increment output pointer
ldax d ; Get next character
cmp b ; Same as previous character?
jz spcopy ; Then just copy it
cpi '$' ; Otherwise, if it is the en
jz spcopy ; Then just copy it as well
mvi m,',' ; Otherwise, add a comma and a space
inx h
mvi m,' '
inx h
jmp spcopy
;;; Demo code
demo: lxi d,string
lxi h,out
call split ; Split the string
lxi d,out
mvi c,9 ; And print it using CP/M
jmp 5
string: db 'gHHH5YY++///',5Ch,'$'
out: equ $ |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
jmp demo
;;; Split the string at DS:SI on changing characters,
;;; and store the result at ES:DI.
split: lodsb ; Load character
.copy: stosb ; Store in output
cmp al,'$' ; Done yet?
je .out ; If so, stop.
mov ah,al ; Store previous character
lodsb ; Get next character
cmp al,ah ; Same character?
je .copy ; Then just copy it
cmp al,'$' ; End of string?
je .copy ; Then just copy it too
mov dl,al
mov ax,', ' ; Otherwise, add a comma and a space
stosw
mov al,dl
jmp .copy
.out: ret
;;; Demo code
demo: mov si,string
mov di,buf
call split ; Split the string
mov dx,buf
mov ah,9
int 21h ; And print the result using DOS
ret
section .data
string: db 'gHHH5YY++///\$'
section .bss
buf: resb 32 |
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.
| #Kotlin | Kotlin | // version 1.1.0
val sbs = mutableListOf(1, 1)
fun sternBrocot(n: Int, fromStart: Boolean = true) {
if (n < 4 || (n % 2 != 0)) throw IllegalArgumentException("n must be >= 4 and even")
var consider = if (fromStart) 1 else n / 2 - 1
while (true) {
val sum = sbs[consider] + sbs[consider - 1]
sbs.add(sum)
sbs.add(sbs[consider])
if (sbs.size == n) break
consider++
}
}
fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
fun main(args: Array<String>) {
var n = 16 // needs to be even to ensure 'considered' number is added
println("First 15 members of the Stern-Brocot sequence")
sternBrocot(n)
println(sbs.take(15))
val firstFind = IntArray(11) // all zero by default
firstFind[0] = -1 // needs to be non-zero for subsequent test
for ((i, v) in sbs.withIndex())
if (v <= 10 && firstFind[v] == 0) firstFind[v] = i + 1
loop@ while (true) {
n += 2
sternBrocot(n, false)
val vv = sbs.takeLast(2)
var m = n - 1
for (v in vv) {
if (v <= 10 && firstFind[v] == 0) firstFind[v] = m
if (firstFind.all { it != 0 }) break@loop
m++
}
}
println("\nThe numbers 1 to 10 first appear at the following indices:")
for (i in 1..10) println("${"%2d".format(i)} -> ${firstFind[i]}")
print("\n100 first appears at index ")
while (true) {
n += 2
sternBrocot(n, false)
val vv = sbs.takeLast(2)
if (vv[0] == 100) {
println(n - 1); break
}
if (vv[1] == 100) {
println(n); break
}
}
print("\nThe GCDs of each pair of the series up to the 1000th member are ")
for (p in 0..998 step 2) {
if (gcd(sbs[p], sbs[p + 1]) != 1) {
println("not all one")
return
}
}
println("all one")
} |
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.
| #VBA | VBA | var func2 = Fn.new {
Fiber.abort("Forced error.")
}
var func1 = Fn.new {
func2.call()
}
func1.call() |
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.
| #Wren | Wren | var func2 = Fn.new {
Fiber.abort("Forced error.")
}
var func1 = Fn.new {
func2.call()
}
func1.call() |
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.
| #zkl | zkl | fcn f{println("F");vm.stackTrace().println()} fcn g{println("G")}
f();g(); |
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();
}
}
| #REXX | REXX | step_up: do while \step(); call step_up
end
return |
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();
}
}
| #Ring | Ring |
stepup()
func stepup
n = 0
while n < 1
if stp() n=n+1 else n= n-1 ok
see n + nl
end
func stp
return 0
|
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Ruby | Ruby | def step_up
start_position = $position
step until ($position == start_position + 1)
end
# assumptions about the step function:
# - it maintains the current position of the robot "as a side effect"
# - the robot is equally likely to step back as to step up
def step
if rand < 0.5
$position -= 1
p "fall (#$position)" if $DEBUG
return false
else
$position += 1
p "rise (#$position)" if $DEBUG
return true
end
end
$position = 0
step_up |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ada | Ada | generic
type Element_Type is private;
package Generic_Stack is
type Stack is private;
procedure Push (Item : Element_Type; Onto : in out Stack);
procedure Pop (Item : out Element_Type; From : in out Stack);
function Create return Stack;
Stack_Empty_Error : exception;
private
type Node;
type Stack is access Node;
type Node is record
Element : Element_Type;
Next : Stack := null;
end record;
end Generic_Stack; |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Needs["DatabaseLink`"];
connectDb[dbUser_, dbPass_, dbUrl_] :=
OpenSQLConnection[JDBC["mysql", dbUrl], "Username" -> dbUser,
"Password" -> dbPass];
createUser::nameTaken = "The username '`1`' is already taken.";
createUser[dbUser_, dbPass_, dbUrl_, user_, pass_] :=
Module[{db = connectDb[dbUser, dbPass, dbUrl],
salt = RandomChoice[Range[32, 127], 16]},
If[MemberQ[SQLSelect[db, "users", {"username"}], {user}],
Message[createUser::nameTaken, user]; Return[]];
SQLInsert[db,
"users", {"username", "pass_salt", "pass_md5"}, {user,
SQLBinary[salt],
SQLBinary[
IntegerDigits[Hash[FromCharacterCode[salt] <> pass, "MD5"], 256,
16]]}]; CloseSQLConnection[db];];
authenticateUser[dbUser_, dbPass_, dbUrl_, user_, pass_] :=
Module[{db = connectDb[dbUser, dbPass, dbUrl], rtn},
rtn = MemberQ[SQLSelect[db, "users", {"username"}], {user}] &&
Module[{data =
SQLSelect[db, "users", {"username", "pass_salt", "pass_md5"},
SQLColumn["username"] == user][[1]]},
Hash[FromCharacterCode[data[[2, 1]]] <> pass, "MD5"] ==
FromDigits[data[[3, 1]], 256]]; CloseSQLConnection[db]; rtn]; |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Nim | Nim | import db_mysql, nimcrypto, md5, strutils
proc connectDb(user, password: string): DbConn =
## Connect to the database "user_db" and create
## the table "users" if it doesn’t exist yet.
result = open("localhost", user, password, "user_db")
result.exec(sql"""CREATE TABLE IF NOT EXISTS users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
pass_md5 tinyblob NOT NULL)""")
proc createUser(db: DbConn; username, password: string) =
## Create a new user in the table "users".
## The password salt and the password MD5 are managed as strings
## but stored in tinyblobs as required.
var passSalt = newString(16)
if randomBytes(passSalt) != 16:
raise newException(ValueError, "unable to build a salt.")
var passMd5 = newString(16)
for i, b in toMD5(passSalt & password): passMd5[i] = chr(b)
if db.tryExec(sql"INSERT INTO users (username, pass_salt, pass_md5) VALUES (?, ?, ?)",
username, passSalt, passMd5):
echo "User $1 created." % username
else:
echo "Could not create user $1." % username
proc authenticateUser(db: DbConn; user, password: string): bool =
## Try to authenticate the user.
## The authentication fails if the user doesn’t exist in "users" table or if the
## password doesn’t match with the salt and password MD5 retrieved from the table.
let row = db.getRow(sql"SELECT pass_salt, pass_md5 FROM users WHERE username = ?", user)
if row[0].len != 0:
let digest = toMd5(row[0] & password)
for i in 0..15:
if digest[i] != byte(row[1][i]): return
result = true
proc clean(db: DbConn) =
## Remove all users from "users" table.
db.exec(sql"DELETE FROM user_db.users")
when isMainModule:
proc authResult(status: bool): string =
if status: "Succeeded" else: "Failed"
# Connect to database and create user "Alice".
let db = connectDb("admin", "admin_password")
db.createUser("Alice", "Alice_password")
# Try to authenticate Alice...
# ... with a wrong password...
var result = db.authenticateUser("Alice", "another_password").authResult()
echo result, " to authenticate Alice with a wrong password."
# ... then with the right password.
result = db.authenticateUser("Alice", "Alice_password").authResult()
echo result, " to authenticate Alice with the right password."
# Clean-up and close.
db.clean()
db.close() |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Objeck | Objeck | use ODBC;
use Encryption;
class SqlTest {
@conn : Connection;
function : Main(args : String[]) ~ Nil {
SqlTest->New()->Run();
}
New() {
@conn := Connection->New("test", "root", "helloworld");
}
method : Run() ~ Nil {
CreateUser("objeck", "beer");
AuthenticateUser("objeck", "beer");
leaving {
@conn->Close();
};
}
method : AuthenticateUser(username : String, password : String) ~ Nil {
status := false;
ps : ParameterStatement;
result : ResultSet;
if(@conn->IsOpen()) {
sql := "SELECT pass_salt, pass_md5 FROM users WHERE username = ?";
ps := @conn->CreateParameterStatement(sql);
ps->SetVarchar(1, username);
result := ps->Select();
if(result <> Nil & result->Next()) {
salt_buffer := Byte->New[16];
result->GetBlob(1, salt_buffer);
salt := "";
for(i := 0; i < 16; i+=1;) {
salt->Append(salt_buffer[i]);
};
db_password_buffer := Byte->New[16];
result->GetBlob(2, db_password_buffer);
password->Append(salt);
user_password_buffer := Hash->MD5(password->ToByteArray());
IO.Console->Print("user: authenticated=")->PrintLine(IsEqual(db_password_buffer, user_password_buffer));
};
};
leaving {
if(ps <> Nil) {
ps->Close();
};
if(ps <> Nil) {
ps->Close();
};
};
}
method : CreateUser(username : String, password : String) ~ Nil {
salt := "";
for(i := 0; i < 16; i+=1;) { salt->Append((Float->Random() * 100)->As(Int)); };
salt := salt->SubString(16);
password->Append(salt);
md5_password := Hash->MD5(password->ToByteArray());
ps : ParameterStatement;
if(@conn->IsOpen()) {
sql := "INSERT INTO users(username, pass_salt, pass_md5) VALUES (?, ?, ?)";
ps := @conn->CreateParameterStatement(sql);
ps->SetVarchar(1, username);
ps->SetBytes(2, salt->ToByteArray());
ps->SetBytes(3, md5_password);
IO.Console->Print("adding user: username=")->Print(username)
->Print(", salt=")->Print(salt)
->Print(", status=")->PrintLine(ps->Update());
};
leaving {
if(ps <> Nil) {
ps->Close();
};
};
}
method : IsEqual(left : Byte[], right : Byte[]) ~ Bool {
if(left->Size() <> right->Size()) {
return false;
};
each(i : left) {
if(left[i] <> right[i]) {
return false;
};
};
return true;
}
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #BQN | BQN | ∘‿5⥊ ((⊢⋆3˙)((¬∊)/⊢)⊢⋆2˙) ↕34 |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #C | C | #include <stdio.h>
#include <math.h>
int main() {
int n = 1, count = 0, sq, cr;
for ( ; count < 30; ++n) {
sq = n * n;
cr = (int)cbrt((double)sq);
if (cr * cr * cr != sq) {
count++;
printf("%d\n", sq);
}
else {
printf("%d is square and cube\n", sq);
}
}
return 0;
} |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"strings"
)
func main() {
sample(100)
sample(1000)
sample(10000)
}
func sample(n int) {
// generate data
d := make([]float64, n)
for i := range d {
d[i] = rand.Float64()
}
// show mean, standard deviation
var sum, ssq float64
for _, s := range d {
sum += s
ssq += s * s
}
fmt.Println(n, "numbers")
m := sum / float64(n)
fmt.Println("Mean: ", m)
fmt.Println("Stddev:", math.Sqrt(ssq/float64(n)-m*m))
// show histogram
h := make([]int, 10)
for _, s := range d {
h[int(s*10)]++
}
for _, c := range h {
fmt.Println(strings.Repeat("*", c*205/int(n)))
}
fmt.Println()
} |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | squareFree[n_Integer] := DeleteCases[Last /@ FactorInteger[n], 1] === {};
findSquareFree[n__] := Select[Range[n], squareFree];
findSquareFree[45]
findSquareFree[10^9, 10^9 + 145]
Length[findSquareFree[10^6]] |
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
| #Nanoquery | Nanoquery | def is_square_free(n)
if n < 2^2
return true
end
for root in range(2, int(sqrt(n)))
if (n % (root ^ 2)) = 0
return false
end
end
return true
end
def square_free(low, high, show_values)
print format("%d-%d: ", low, high)
leng = len(str(low)) + len(str(high)) + 3
count = 0
for i in range(low, high)
if is_square_free(i)
count += 1
if show_values
if leng > 110
println
leng = 0
end
print format("%d ", i)
leng += len(str(i)) + 1
end
end
end
print format("count=%d\n\n", count)
end
square_free(1, 145, true)
square_free(10^12, 10^12 + 145, true)
square_free(1, 100, false)
square_free(1, 1000, false)
square_free(1, 10000, false)
square_free(1, 100000, false)
square_free(1, 1000000, false) |
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.
| #Nim | Nim | import tables
import math
import strutils
import algorithm
type
StemLeafPlot = ref object
leafDigits: int
multiplier: int
plot: TableRef[int, seq[int]]
proc `$`(s: seq[int]): string =
result = ""
for item in s:
result &= $item & " "
proc `$`(self: StemLeafPlot): string =
result = ""
var keys: seq[int] = @[]
for stem, _ in self.plot:
keys.add(stem)
for printedStem in keys.min..keys.max:
result &= align($printedStem & " | ", ($keys.max).len + 4)
if printedStem in keys:
self.plot[printedStem].sort(system.cmp[int])
result &= $self.plot[printedStem]
result &= "\n"
proc parse(self: StemLeafPlot, value: int): tuple[stem, leaf: int] =
(value div self.multiplier, abs(value mod self.multiplier))
proc init[T](self: StemLeafPlot, leafDigits: int, data: openArray[T]) =
self.leafDigits = leafDigits
self.multiplier = 10 ^ leafDigits
self.plot = newTable[int, seq[int]]()
for value in data:
let (stem, leaf) = self.parse(value)
if stem notin self.plot:
self.plot[stem] = @[leaf]
else:
self.plot[stem].add(leaf)
var taskData = @[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]
var negativeData = @[-24, -12, -3, 4, 6, 6, 17, 25, 57]
echo "Using the Task's Test Data"
var taskPlot = StemLeafPlot()
taskPlot.init(1, taskData)
echo taskPlot
echo "Test with Negative Stem"
var negativePlot = StemLeafPlot()
negativePlot.init(1, negativeData)
echo negativePlot |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program splitcar64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szCarriageReturn: .asciz "\n"
szString1: .asciz "gHHH5YY++///\\"
/* IMPORTANT REMARK for compiler as
The way to get special characters into a string is to escape these characters: precede them
with a backslash ‘\’ character. For example ‘\\’ represents one backslash: the first \ is
an escape which tells as to interpret the second character literally as a backslash (which
prevents as from recognizing the second \ as an escape character).
*/
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sBuffer: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszString1 // input string address
ldr x1,qAdrsBuffer // output buffer address
bl split
ldr x0,qAdrsBuffer
bl affichageMess // display message
ldr x0,qAdrszCarriageReturn
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszString1: .quad szString1
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsBuffer: .quad sBuffer
/******************************************************************/
/* generate value */
/******************************************************************/
/* x0 contains the address of input string */
/* x1 contains the address of output buffer */
split:
stp x1,lr,[sp,-16]! // save registers
mov x4,0 // indice loop input string
mov x5,0 // indice buffer
ldrb w2,[x0,x4] // read first char in reg x2
cbz x2,4f // if null -> end
strb w2,[x1,x5] // store char in buffer
add x5,x5,1 // increment location buffer
1:
ldrb w3,[x0,x4] //read char[x4] in reg x3
cbz x3,4f // if null end
cmp x2,x3 // compare two characters
bne 2f
strb w3,[x1,x5] // = -> store char in buffer
b 3f // loop
2:
mov x2,',' // else store comma in buffer
strb w2,[x1,x5] // store char in buffer
add x5,x5,1
mov x2,' ' // and store space in buffer
strb w2,[x1,x5]
add x5,x5,1
strb w3,[x1,x5] // and store input char in buffer
mov x2,x3 // and maj x2 with new char
3:
add x5,x5,1 // increment indices
add x4,x4,1
b 1b // and loop
4:
strb w3,[x1,x5] // store zero final in buffer
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Action.21 | Action! | PROC Split(CHAR ARRAY s)
BYTE i
CHAR curr,last
i=1 last=s(1)
Put('")
WHILE i<=s(0)
DO
curr=s(i)
IF curr#last THEN
Print(", ")
FI
Put(curr)
last=curr
i==+1
OD
Put('")
RETURN
PROC Test(CHAR ARRAY s)
PrintF("Input: ""%S""%E",s)
Print("Split: ") Split(s)
PutE() PutE()
RETURN
PROC Main()
Test("gHHH5YY++///\")
Test("gHHH 5++,,,///\")
RETURN |
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.
| #Lua | Lua | -- Task 1
function sternBrocot (n)
local sbList, pos, c = {1, 1}, 2
repeat
c = sbList[pos]
table.insert(sbList, c + sbList[pos - 1])
table.insert(sbList, c)
pos = pos + 1
until #sbList >= n
return sbList
end
-- Return index in table 't' of first value matching 'v'
function findFirst (t, v)
for key, value in pairs(t) do
if v then
if value == v then return key end
else
if value ~= 0 then return key end
end
end
return nil
end
-- Return greatest common divisor of 'x' and 'y'
function gcd (x, y)
if y == 0 then
return math.abs(x)
else
return gcd(y, x % y)
end
end
-- Check GCD of adjacent values in 't' up to 1000 is always 1
function task5 (t)
for pos = 1, 1000 do
if gcd(t[pos], t[pos + 1]) ~= 1 then return "FAIL" end
end
return "PASS"
end
-- Main procedure
local sb = sternBrocot(10000)
io.write("Task 2: ")
for n = 1, 15 do io.write(sb[n] .. " ") end
print("\n\nTask 3:")
for i = 1, 10 do print("\t" .. i, findFirst(sb, i)) end
print("\nTask 4: " .. findFirst(sb, 100))
print("\nTask 5: " .. task5(sb)) |
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();
}
}
| #Run_BASIC | Run BASIC |
result = stepUp()
Function stepUp()
While Not(stepp())
result = stepUp()
Wend
End Function
Function stepp()
stepp = int((Rnd(1) * 2))
print "Robot stepped "+word$("up down",stepp+1)
End Function
|
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a boolean flag: true on success, false on failure.
Write a function "step_up" that climbs one step up [from the initial position] (by repeating "step" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make "step_up"? Can you avoid using variables (even immutable ones) and numbers?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
Base case (if the step() call returns true): it stepped up one step. QED
Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| #Rust | Rust | fn 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();
}
}
| #SAS | SAS |
%macro step();
%sysfunc(round(%sysfunc(ranuni(0))))
%mend step;
|
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked #
END CO
MODE OBJNEXTLINK = STRUCT(
REF OBJNEXTLINK next,
OBJVALUE value # ... etc. required #
);
PROC obj nextlink new = REF OBJNEXTLINK:
HEAP OBJNEXTLINK;
PROC obj nextlink free = (REF OBJNEXTLINK free)VOID:
next OF free := obj stack empty # give the garbage collector a BIG hint # |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Perl | Perl | use DBI;
# returns a database handle configured to throw an exception on query errors
sub connect_db {
my ($dbname, $host, $user, $pass) = @_;
my $db = DBI->connect("dbi:mysql:$dbname:$host", $user, $pass)
or die $DBI::errstr;
$db->{RaiseError} = 1;
$db
}
# if the user was successfully created, returns its user id.
# if the name was already in use, returns undef.
sub create_user {
my ($db, $user, $pass) = @_;
my $salt = pack "C*", map {int rand 256} 1..16;
$db->do("INSERT IGNORE INTO users (username, pass_salt, pass_md5)
VALUES (?, ?, unhex(md5(concat(pass_salt, ?))))",
undef, $user, $salt, $pass)
and $db->{mysql_insertid} or undef
}
# if the user is authentic, returns its user id. otherwise returns undef.
sub authenticate_user {
my ($db, $user, $pass) = @_;
my $userid = $db->selectrow_array("SELECT userid FROM users WHERE
username=? AND pass_md5=unhex(md5(concat(pass_salt, ?)))",
undef, $user, $pass);
$userid
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #C.23 | C# | using System;
using System.Collections.Generic;
using static System.Console;
using static System.Linq.Enumerable;
public static class SquareButNotCube
{
public static void Main() {
var squares = from i in Integers() select i * i;
var cubes = from i in Integers() select i * i * i;
foreach (var x in Merge().Take(33)) {
WriteLine(x.isCube ? x.n + " (also cube)" : x.n + "");
}
IEnumerable<int> Integers() {
for (int i = 1; ;i++) yield return i;
}
IEnumerable<(int n, bool isCube)> Merge() {
using (var s = squares.GetEnumerator())
using (var c = cubes.GetEnumerator()) {
s.MoveNext();
c.MoveNext();
while (true) {
if (s.Current < c.Current) {
yield return (s.Current, false);
s.MoveNext();
} else if (s.Current == c.Current) {
yield return (s.Current, true);
s.MoveNext();
c.MoveNext();
} else {
c.MoveNext();
}
}
}
}
}
} |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Haskell | Haskell | import Data.Foldable (foldl') --'
import System.Random (randomRs, newStdGen)
import Control.Monad (zipWithM_)
import System.Environment (getArgs)
intervals :: [(Double, Double)]
intervals = map conv [0 .. 9]
where
xs = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
conv s =
let [h, l] = take 2 $ drop s xs
in (h, l)
count :: [Double] -> [Int]
count rands = map (\iv -> foldl'' (loop iv) 0 rands) intervals
where
loop :: (Double, Double) -> Int -> Double -> Int
loop (lo, hi) n x
| lo <= x && x < hi = n + 1
| otherwise = n
-- ^ fuses length and filter within (lo,hi)
data Pair a b =
Pair !a
!b
-- accumulate sum and length in one fold
sumLen :: [Double] -> Pair Double Double
sumLen = fion2 . foldl'' (\(Pair s l) x -> Pair (s + x) (l + 1)) (Pair 0.0 0)
where
fion2 :: Pair Double Int -> Pair Double Double
fion2 (Pair s l) = Pair s (fromIntegral l)
-- safe division on pairs
divl :: Pair Double Double -> Double
divl (Pair _ 0.0) = 0.0
divl (Pair s l) = s / l
-- sumLen and divl are separate for stddev below
mean :: [Double] -> Double
mean = divl . sumLen
stddev :: [Double] -> Double
stddev xs = sqrt $ foldl'' (\s x -> s + (x - m) ^ 2) 0 xs / l
where
p@(Pair s l) = sumLen xs
m = divl p
main = do
nr <- read . head <$> getArgs
-- or in code, e.g. let nr = 1000
rands <- take nr . randomRs (0.0, 1.0) <$> newStdGen
putStrLn $ "The mean is " ++ show (mean rands) ++ " !"
putStrLn $ "The standard deviation is " ++ show (stddev rands) ++ " !"
zipWithM_
(\iv fq -> putStrLn $ ivstr iv ++ ": " ++ fqstr fq)
intervals
(count rands)
where
fqstr i =
replicate
(if i > 50
then div i (div i 50)
else i)
'*'
ivstr (lo, hi) = show lo ++ " - " ++ show hi
-- To avoid Wiki formatting issue
foldl'' = foldl' |
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
| #Nim | Nim | import math, strutils
proc sieve(limit: Natural): seq[int] =
result = @[2]
var c = newSeq[bool](limit + 1) # Composite = true.
# No need to process even numbers > 2.
var p = 3
while true:
let p2 = p * p
if p2 > limit: break
for i in countup(p2, limit, 2 * p):
c[i] = true
while true:
inc p, 2
if not c[p]: break
for i in countup(3, limit, 2):
if not c[i]: result.add i
proc squareFree(fromVal, toVal: Natural): seq[int] =
let limit = int(sqrt(toVal.toFloat))
let primes = sieve(limit)
for i in fromVal..toVal:
block check:
for p in primes:
let p2 = p * p
if p2 > i: break
if i mod p2 == 0:
break check # Not square free.
result.add i
when isMainModule:
const Trillion = 1_000_000_000_000
echo "Square-free integers from 1 to 145:"
var sf = squareFree(1, 145)
for i, val in sf:
if i > 0 and i mod 20 == 0:
echo()
stdout.write ($val).align(4)
echo()
echo "\nSquare-free integers from $1 to $2:\n".format(Trillion, Trillion + 145)
sf = squareFree(Trillion, Trillion + 145)
for i, val in sf:
if i > 0 and i mod 5 == 0:
echo()
stdout.write ($val).align(14)
echo()
echo "\nNumber of square-free integers:\n"
for n in [100, 1_000, 10_000, 100_000, 1_000_000]:
echo " from $1 to $2 = $3".format(1, n, squareFree(1, n).len) |
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.
| #OCaml | OCaml | let unique li =
let rec aux acc = function
| [] -> (List.rev acc)
| x::xs ->
if List.mem x acc
then aux acc xs
else aux (x::acc) xs
in
aux [] li |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada |
with Ada.Text_IO;
procedure Split is
procedure Print_Tokens (s : String) is
i, j : Integer := s'First;
begin
loop
while j<=s'Last and then s(j)=s(i) loop j := j + 1; end loop;
if i/=s'first then Ada.Text_IO.Put (", "); end if;
Ada.Text_IO.Put (s(i..j-1));
i := j;
exit when j>s'last;
end loop;
end Print_Tokens;
begin
Print_Tokens ("gHHH5YY+++");
end split;
|
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
1, 1, 2
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1
Consider the next member of the series, (the third member i.e. 2)
GOTO 3
─── Expanding another loop we get: ───
Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
1, 1, 2, 1, 3
Append the considered member of the sequence to the end of the sequence:
1, 1, 2, 1, 3, 2
Consider the next member of the series, (the fourth member i.e. 1)
The task is to
Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)
Show the (1-based) index of where the numbers 1-to-10 first appears in the sequence.
Show the (1-based) index of where the number 100 first appears in the sequence.
Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
Related tasks
Fusc sequence.
Continued fraction/Arithmetic
Ref
Infinite Fractions - Numberphile (Video).
Trees, Teeth, and Time: The mathematics of clock making.
A002487 The On-Line Encyclopedia of Integer Sequences.
| #MAD | MAD | NORMAL MODE IS INTEGER
VECTOR VALUES FRST15 = $20HFIRST 15 NUMBERS ARE*$
VECTOR VALUES FRSTAT = $6HFIRST ,I3,S1,11HAPPEARS AT ,I4*$
VECTOR VALUES NUMBER = $I4*$
DIMENSION STERN(1200)
STERN(1) = 1
STERN(2) = 1
R GENERATE FIRST 1200 MEMBERS OF THE STERN-BROCOT SEQUENCE
THROUGH GENSEQ, FOR I = 1, 1, I .GE. 600
STERN(I*2-1) = STERN(I) + STERN(I-1)
GENSEQ STERN(I*2) = STERN(I)
R PRINT FIRST 15 VALUES OF STERN-BROCOT SEQUENCE
PRINT FORMAT FRST15
THROUGH P15, FOR I = 1, 1, I .G. 15
P15 PRINT ON LINE FORMAT NUMBER, STERN(I)
R PRINT FIRST OCCURRENCE OF 1..10
THROUGH FRST10, FOR I = 1, 1, I .G. 10
FRST10 PRINT FORMAT FRSTAT, I, FIRST.(I)
PRINT FORMAT FRSTAT, 100, FIRST.(100)
R SEARCH FOR FIRST OCCURRENCE OF N IN SEQUENCE
INTERNAL FUNCTION(N)
ENTRY TO FIRST.
THROUGH SCAN, FOR K = 1, 1, I .G. 1200
SCAN WHENEVER N .E. STERN(K), FUNCTION RETURN K
END OF FUNCTION
END OF PROGRAM |
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();
}
}
| #Scala | Scala | def stepUp { while (! step) 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();
}
}
| #Scheme | Scheme | (define (step-up n-steps)
(cond ((zero? n-steps) 'done)
((step) (step-up (- n-steps 1)))
(else (step-up (+ n-steps 1))))) |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ALGOL_W | ALGOL W | begin
% define a Stack type that will hold StringStackElements %
% and the StringStackElement type %
% we would need separate types for other element types %
record StringStack ( reference(StringStackElement) top );
record StringStackElement ( string(8) element
; reference(StringStackElement) next
);
% adds e to the end of the StringStack s %
procedure pushString ( reference(StringStack) value s
; string(8) value e
) ;
top(s) := StringStackElement( e, top(s) );
% removes and returns the top element from the StringStack s %
% asserts the Stack is not empty, which will stop the %
% program if it is %
string(8) procedure popString ( reference(StringStack) value s ) ;
begin
string(8) v;
assert( not isEmptyStringStack( s ) );
v := element(top(s));
top(s):= next(top(s));
v
end popStringStack ;
% returns the top element of the StringStack s %
% asserts the Stack is not empty, which will stop the %
% program if it is %
string(8) procedure peekStringStack ( reference(StringStack) value s ) ;
begin
assert( not isEmptyStringStack( s ) );
element(top(s))
end popStringStack ;
% returns true if the StringStack s is empty, false otherwise %
logical procedure isEmptyStringStack ( reference(StringStack) value s ) ; top(s) = null;
begin % test the StringStack operations %
reference(StringStack) s;
s := StringStack( null );
pushString( s, "up" );
pushString( s, "down" );
pushString( s, "strange" );
pushString( s, "charm" );
while not isEmptyStringStack( s ) do write( popString( s )
, if isEmptyStringStack( s ) then "(empty)"
else peekStringStack( s )
)
end
end. |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Phix | Phix | -- demo\rosetta\SQL-based_authentication.exw
without js -- (file i/o)
include pSQLite.e
include md5.exw
sqlite3_stmt pAddUser = NULL
procedure add_user(sqlite3 db, string name, pw)
if pAddUser=NULL then
pAddUser = sqlite3_prepare(db,"INSERT INTO users (username,pass_salt,pass_md5) VALUES(:name, :salt, :md5);")
end if
string salt = sq_rand(repeat(#FF,16)),
md5s = md5(salt&pw)
sqlite3_bind_text(pAddUser,":name", name)
sqlite3_bind_text(pAddUser,":salt", salt)
sqlite3_bind_text(pAddUser,":md5", md5s)
{} = sqlite3_step(pAddUser) -- (nb: ignores any errors.)
sqlite3_reset(pAddUser)
end procedure
sqlite3_stmt pAuthUser = NULL
function authenticate_user(sqlite3 db, string name, pw)
if pAuthUser=NULL then
pAuthUser = sqlite3_prepare(db,"SELECT pass_salt, pass_md5 FROM users WHERE username = :name;")
end if
sqlite3_bind_text(pAuthUser,":name", name)
integer res = sqlite3_step(pAuthUser)
if res!=SQLITE_ROW then
res = false -- (no such user)
else
string salt = sqlite3_column_text(pAuthUser,1)
string pass_md5 = sqlite3_column_text(pAuthUser,2)
res = (pass_md5==md5(salt&pw))
end if
sqlite3_reset(pAuthUser)
return res
end function
constant create_cmd = """
CREATE TABLE IF NOT EXISTS users(
userid INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(32) UNIQUE NOT NULL,
pass_salt tinyblob,
-- a string of 16 random bytes
pass_md5 tinyblob);
-- binary MD5 hash of pass_salt concatenated with the password
"""
procedure main()
sequence sqlversion = sqlite3_libversion(true)
if sqlversion<{3,3,0} then
crash("a newer sqlite.dll/so is required (for IF NOT EXISTS)")
end if
sqlite3 db = sqlite3_open("users.sqlite")
integer res = sqlite3_exec(db,create_cmd)
if res!=SQLITE_OK then ?9/0 end if
sqlite3_set_fatal_id(SQLITE3_NON_FATAL) -- (else trying to re-add user crashes)
add_user(db,"user","password")
printf(1,"user with correct password:%t\n",authenticate_user(db, "user", "password"))
printf(1,"user with incorrect password:%t\n",authenticate_user(db, "user", "wrong"))
if pAddUser!=NULL then
if sqlite3_finalize(pAddUser)!=SQLITE_OK then ?9/0 end if
end if
if pAuthUser!=NULL then
if sqlite3_finalize(pAuthUser)!=SQLITE_OK then ?9/0 end if
end if
sqlite3_close(db)
?"done"
{} = wait_key()
end procedure
main()
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #C.2B.2B | C++ | #include <iostream>
#include <cmath>
int main() {
int n = 1;
int count = 0;
int sq;
int cr;
for (; count < 30; ++n) {
sq = n * n;
cr = cbrt(sq);
if (cr * cr * cr != sq) {
count++;
std::cout << sq << '\n';
} else {
std::cout << sq << " is square and cube\n";
}
}
return 0;
} |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Hy | Hy | (import
[numpy.random [random]]
[numpy [mean std]]
[matplotlib.pyplot :as plt])
(for [n [100 1000 10000]]
(setv v (random n))
(print "Mean:" (mean v) "SD:" (std v)))
(plt.hist (random 1000))
(plt.show) |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
W := 50 # avg width for histogram bar
B := 10 # histogram bins
if *A = 0 then put(A,100) # 100 if none specified
while N := get(A) do { # once per argument
write("\nN=",N)
N := 0 < integer(N) | next # skip if invalid
stddev() # reset
m := 0.
H := list(B,0) # Histogram of
every i := 1 to N do { # calc running ...
s := stddev(r := ?0) # ... std dev
m +:= r/N # ... mean
H[integer(*H*r)+1] +:= 1 # ... histogram
}
write("mean=",m)
write("stddev=",s)
every i := 1 to *H do # show histogram
write(right(real(i)/*H,5)," : ",repl("*",integer(*H*50./N*H[i])))
}
end |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #OCaml | OCaml |
let squarefree (number: int) : bool =
let max = Float.of_int number |> sqrt |> Float.to_int |> (fun x -> x + 2) in
let rec inner i number2 =
if i == max
then true
else if number2 mod (i*i) == 0
then false
else inner (i+1) number2
in inner 2 number
;;
let list_squarefree_integers (x, y) =
let rec inner start finish output =
if start == finish
then output
else if squarefree start
then inner (start+1) finish (start :: output)
else inner (start+1) finish output
in inner x y []
;;
let print_squarefree_integers (x, y) =
let squarefrees_unrev = list_squarefree_integers (x, y) in
let squarefrees = List.rev squarefrees_unrev in
let rec inner sfs i count =
match sfs with
[] -> count
| h::t -> (if (i+1) mod 5 == 0 then (Printf.printf "%d\n" h) else (Printf.printf "%d " h); inner t (i+1) (count+1);)
in Printf.printf "\n\nTotal count of square-free numbers between %d and %d: %d\n" x y (inner squarefrees 0 0)
;;
let () =
print_squarefree_integers (1, 146);
print_squarefree_integers (1000000000000, 1000000000146)
;;
|
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.
| #Perl | Perl | my @data = sort {$a <=> $b} qw( 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 );
my $columns = @data;
my $laststem = undef;
for my $value (@data) {
my $stem = int($value / 10);
my $leaf = $value % 10;
while (not defined $laststem or $stem > $laststem) {
if (not defined $laststem) {
$laststem = $stem - 1;
} else {
print " \n";
}
$laststem++;
printf "%3d |", $laststem;
}
print " $leaf";
}
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | BEGIN
# returns s with ", " added between each change of character #
PROC split on characters = ( STRING s )STRING:
IF s = "" THEN
# empty string #
""
ELSE
# allow for 3 times as many characters as in the string #
# this would handle a string of unique characters #
[ 3 * ( ( UPB s - LWB s ) + 1 ) ]CHAR result;
INT r pos := LWB result;
INT s pos := LWB s;
CHAR s char := s[ LWB s ];
FOR s pos FROM LWB s TO UPB s DO
IF s char /= s[ s pos ] THEN
# change of character - insert ", " #
result[ r pos ] := ",";
result[ r pos + 1 ] := " ";
r pos +:= 2;
s char := s[ s pos ]
FI;
result[ r pos ] := s[ s pos ];
r pos +:= 1
OD;
# return the used portion of the result #
result[ 1 : r pos - 1 ]
FI ; # split on characters #
print( ( split on characters( "gHHH5YY++///\" ), newline ) )
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | sb = {1, 1};
Do[
sb = sb~Join~{Total@sb[[i - 1 ;; i]], sb[[i]]}
,
{i, 2, 1000}
]
Take[sb, 15]
Flatten[FirstPosition[sb, #] & /@ Range[10]]
First@FirstPosition[sb, 100]
AllTrue[Partition[Take[sb, 1000], 2, 1], Apply[GCD] /* EqualTo[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();
}
}
| #Seed7 | Seed7 | const proc: step_up is func
begin
while not doStep do
step_up;
end while;
end func; |
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();
}
}
| #Sidef | Sidef | func 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();
}
}
| #Smalltalk | Smalltalk | Smalltalk at: #stepUp put: 0.
stepUp := [ [ step value ] whileFalse: [ stepUp value ] ]. |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Applesoft_BASIC | Applesoft BASIC | 100 DIM STACK$(1000)
110 DATA "(2*A)","PI","","TO BE OR","NOT TO BE"
120 FOR I = 1 TO 5
130 READ ELEMENT$
140 GOSUB 500_PUSH
150 NEXT
200 GOSUB 400 POP AND PRINT
210 GOSUB 300_EMPTY AND PRINT
220 FOR I = 1 TO 4
230 GOSUB 400 POP AND PRINT
240 NEXT
250 GOSUB 300_EMPTY AND PRINT
260 END
300 GOSUB 700_EMPTY
310 PRINT "STACK IS ";
320 IF NOT EMPTY THEN PRINT "NOT ";
330 PRINT "EMPTY"
340 RETURN
400 GOSUB 600 POP
410 PRINT ELEMENT$
420 RETURN
500 REM
510 REM PUSH
520 REM
530 LET STACK$(SP) = ELEMENT$
540 LET SP = SP + 1
550 RETURN
600 REM
610 REM POP
620 REM
630 IF SP THEN SP = SP - 1
640 LET ELEMENT$ = STACK$(SP)
650 LET STACK$(SP) = ""
660 RETURN
700 REM
710 REM EMPTY
720 REM
730 LET EMPTY = SP = 0
740 RETURN
|
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #PHP | PHP |
function connect_db($database, $db_user, $db_password, $host = 'localhost', $port = NULL, $die = false) {
// Returns a MySQL link identifier (handle) on success
// Returns false or dies() on error depending on the setting of parameter $die
// Parameter $die configures error handling, setting it any non-false value will die() on error
// Parameters $host, $port and $die have sensible defaults and are not usually required
if(!$db_handle = @mysql_connect($host.($port ? ':'.$port : ''), $db_user, $db_password)) {
if($die)
die("Can't connect to MySQL server:\r\n".mysql_error());
else
return false;
}
if(!@mysql_select_db($database, $db_handle)) {
if($die)
die("Can't select database '$database':\r\n".mysql_error());
else
return false;
}
return $db_handle;
}
function create_user($username, $password, $db_handle) {
// Returns the record ID on success or false on failure
// Username limit is 32 characters (part of spec)
if(strlen($username) > 32)
return false;
// Salt limited to ASCII 32 thru 254 (not part of spec)
$salt = '';
do {
$salt .= chr(mt_rand(32, 254));
} while(strlen($salt) < 16);
// Create pass_md5
$pass_md5 = md5($salt.$password);
// Make it all binary safe
$username = mysql_real_escape_string($username);
$salt = mysql_real_escape_string($salt);
// Try to insert it into the table - Return false on failure
if(!@mysql_query("INSERT INTO users (username,pass_salt,pass_md5) VALUES('$username','$salt','$pass_md5')", $db_handle))
return false;
// Return the record ID
return mysql_insert_id($db_handle);
}
function authenticate_user($username, $password, $db_handle) {
// Checks a username/password combination against the database
// Returns false on failure or the record ID on success
// Make the username parmeter binary-safe
$safe_username = mysql_real_escape_string($username);
// Grab the record (if it exists) - Return false on failure
if(!$result = @mysql_query("SELECT * FROM users WHERE username='$safe_username'", $db_handle))
return false;
// Grab the row
$row = @mysql_fetch_assoc($result);
// Check the password and return false if incorrect
if(md5($row['pass_salt'].$password) != $row['pass_md5'])
return false;
// Return the record ID
return $row['userid'];
}
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #11l | 11l | os:(‘espeak 'Hello world!'’) |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Clojure | Clojure | (def squares (map #(* % %) (drop 1 (range))))
(def square-cubes (map #(int (. Math pow % 6)) (drop 1 (range))))
(def squares-not-cubes (filter #(not (= % (first (drop-while (fn [n] (< n %)) square-cubes)))) squares))
(println "Squares but not cubes:")
(println (take 30 squares-not-cubes))
(println "Both squares and cubes:")
(println (take 15 square-cubes))
|
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #J | J | require 'stats'
(mean,stddev) 1000 ?@$ 0
0.484669 0.287482
(mean,stddev) 10000 ?@$ 0
0.503642 0.290777
(mean,stddev) 100000 ?@$ 0
0.499677 0.288726 |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Java | Java | import static java.lang.Math.pow;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.joining;
import static java.util.stream.IntStream.range;
public class Test {
static double[] meanStdDev(double[] numbers) {
if (numbers.length == 0)
return new double[]{0.0, 0.0};
double sx = 0.0, sxx = 0.0;
long n = 0;
for (double x : numbers) {
sx += x;
sxx += pow(x, 2);
n++;
}
return new double[]{sx / n, pow((n * sxx - pow(sx, 2)), 0.5) / n};
}
static String replicate(int n, String s) {
return range(0, n + 1).mapToObj(i -> s).collect(joining());
}
static void showHistogram01(double[] numbers) {
final int maxWidth = 50;
long[] bins = new long[10];
for (double x : numbers)
bins[(int) (x * bins.length)]++;
double maxFreq = stream(bins).max().getAsLong();
for (int i = 0; i < bins.length; i++)
System.out.printf(" %3.1f: %s%n", i / (double) bins.length,
replicate((int) (bins[i] / maxFreq * maxWidth), "*"));
System.out.println();
}
public static void main(String[] a) {
Locale.setDefault(Locale.US);
for (int p = 1; p < 7; p++) {
double[] n = range(0, (int) pow(10, p))
.mapToDouble(i -> Math.random()).toArray();
System.out.println((int)pow(10, p) + " numbers:");
double[] res = meanStdDev(n);
System.out.printf(" Mean: %8.6f, SD: %8.6f%n", res[0], res[1]);
showHistogram01(n);
}
}
} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
1 ───► 145 (inclusive)
1 trillion ───► 1 trillion + 145 (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
1 ───► one hundred (inclusive)
1 ───► one thousand (inclusive)
1 ───► ten thousand (inclusive)
1 ───► one hundred thousand (inclusive)
1 ───► one million (inclusive)
See also
the Wikipedia entry: square-free integer
| #Pascal | Pascal | program SquareFree;
{$IFDEF FPC}
{$MODE DELPHI}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
const
//needs 1e10 Byte = 10 Gb maybe someone got 128 Gb :-) nearly linear time
BigLimit = 10*1000*1000*1000;
TRILLION = 1000*1000*1000*1000;
primeLmt = trunc(sqrt(TRILLION+150));
var
primes : array of byte;
sieve : array of byte;
procedure initPrimes;
var
i,lmt,dp :NativeInt;
Begin
setlength(primes,80000);
setlength(sieve,primeLmt);
sieve[0] := 1;
sieve[1] := 1;
i := 2;
repeat
IF sieve[i] = 0 then
Begin
lmt:= i*i;
while lmt<primeLmt do
Begin
sieve[lmt] := 1;
inc(lmt,i);
end;
end;
inc(i);
until i*i>=primeLmt;
//extract difference of primes
i := 0;
lmt := 0;
dp := 0;
repeat
IF sieve[i] = 0 then
Begin
primes[lmt] := dp;
dp := 0;
inc(lmt);
end;
inc(dp);
inc(i);
until i >primeLmt;
setlength(sieve,0);
setlength(Primes,lmt+1);
end;
procedure SieveSquares;
//mark all powers >=2 of prime => all powers = 2 is sufficient
var
pSieve : pByte;
i,sq,k,prime : NativeInt;
Begin
pSieve := @sieve[0];
prime := 0;
For i := 0 to High(primes) do
Begin
prime := prime+primes[i];
sq := prime*prime;
k := sq;
if sq > BigLimit then
break;
repeat
pSieve[k] := 1;
inc(k,sq);
until k> BigLimit;
end;
end;
procedure Count_x10;
var
pSieve : pByte;
i,lmt,cnt: NativeInt;
begin
writeln(' square free count');
writeln('[1 to limit]');
pSieve := @sieve[0];
lmt := 10;
i := 1;
cnt := 0;
repeat
while i <= lmt do
Begin
inc(cnt,ORD(pSieve[i] = 0));
inc(i);
end;
writeln(lmt:12,' ',cnt:12);
IF lmt >= BigLimit then
BREAK;
lmt := lmt*10;
IF lmt >BigLimit then
lmt := BigLimit;
until false;
end;
function TestSquarefree(N:Uint64):boolean;
var
i,prime,sq : NativeUint;
Begin
prime := 0;
result := false;
For i := 0 to High(primes) do
Begin
prime := prime+primes[i];
sq := sqr(prime);
IF sq> N then
BREAK;
IF N MOD sq = 0 then
EXIT;
end;
result := true;
end;
var
i,k : NativeInt;
Begin
InitPrimes;
setlength(sieve,BigLimit+1);
SieveSquares;
writeln('Square free numbers from 1 to 145');
k := 80 div 4;
For i := 1 to 145 do
If sieve[i] = 0 then
Begin
write(i:4);
dec(k);
IF k = 0 then
Begin
writeln;
k := 80 div 4;
end;
end;
writeln;writeln;
writeln('Square free numbers from ',TRILLION,' to ',TRILLION+145);
k := 4;
For i := TRILLION to TRILLION+145 do
Begin
if TestSquarefree(i) then
Begin
write(i:20);
dec(k);
IF k = 0 then
Begin
writeln;
k := 4;
end;
end;
end;
writeln;writeln;
Count_x10;
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.
| #Phix | Phix | with javascript_semantics
procedure leaf_plot(sequence s)
s = sort(deep_copy(s))
sequence stem = repeat({},floor(s[$]/10)+1)
for i=1 to length(s) do
integer j = floor(s[i]/10)+1
stem[j] = deep_copy(stem[j]) & 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/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ANSI_BASIC | ANSI BASIC | REM >split
DECLARE EXTERNAL FUNCTION FN_split$
PRINT FN_split$( "gHHH5YY++///\" )
END
EXTERNAL FUNCTION FN_split$( s$ )
LET c$ = s$(1:1)
LET split$ = ""
FOR i = 1 TO LEN(s$)
LET d$ = s$(i:i)
IF d$ <> c$ THEN
LET split$ = split$ & ", "
LET c$ = d$
END IF
LET split$ = split$ & d$
NEXT i
LET FN_split$ = split$
END FUNCTION |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #APL | APL | split ← 2↓∘∊(⊂', '),¨(⊢≠¯1⌽⊢)⊂⊢ |
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.
| #Modula-2 | Modula-2 | MODULE SternBrocot;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
CONST Amount = 1200;
VAR stern: ARRAY [1..Amount] OF CARDINAL;
i: CARDINAL;
PROCEDURE GCD(a,b: CARDINAL): CARDINAL;
VAR c: CARDINAL;
BEGIN
WHILE b # 0 DO
c := a MOD b;
a := b;
b := c;
END;
RETURN a;
END GCD;
PROCEDURE Generate;
VAR i: CARDINAL;
BEGIN
stern[1] := 1;
stern[2] := 1;
FOR i := 2 TO Amount DIV 2 DO
stern[i*2 - 1] := stern[i] + stern[i-1];
stern[i*2] := stern[i];
END;
END Generate;
PROCEDURE FindFirst(n: CARDINAL): CARDINAL;
VAR i: CARDINAL;
BEGIN
FOR i := 1 TO Amount DO
IF stern[i] = n THEN
RETURN i;
END;
END;
END FindFirst;
PROCEDURE ShowFirst(n: CARDINAL);
BEGIN
WriteString("First");
WriteCard(n,4);
WriteString(" at ");
WriteCard(FindFirst(n), 4);
WriteLn;
END ShowFirst;
BEGIN
Generate;
WriteString("First 15 numbers:");
FOR i := 1 TO 15 DO
WriteCard(stern[i], 2);
END;
WriteLn;
FOR i := 1 TO 10 DO
ShowFirst(i);
END;
ShowFirst(100);
WriteLn;
FOR i := 2 TO Amount DO
IF GCD(stern[i-1], stern[i]) # 1 THEN
WriteString("GCD of adjacent elements not 1 at: ");
WriteCard(i-1, 4);
WriteLn;
HALT;
END;
END;
WriteString("The GCD of every pair of adjacent elements is 1.");
WriteLn;
END SternBrocot. |
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();
}
}
| #Standard_ML | Standard ML |
(*
* val step : unit -> bool
* This is a stub for a function which returns true if successfully climb a step or false otherwise.
*)
fun step() = true
(*
* val step_up : unit -> bool
*)
fun step_up() = step() orelse (step_up() andalso 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();
}
}
| #Swift | Swift | func step_up() {
while !step() {
step_up()
}
} |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #ARM_Assembly | ARM Assembly | STMFD sp!,{r0-r12,lr} ;push r0 thru r12 and the link register
LDMFD sp!,{r0-r12,pc} ;pop r0 thru r12, and the value that was in the link register is put into the program counter.
;This acts as a pop and return command all-in-one. (Most programs use bx lr to return.) |
http://rosettacode.org/wiki/SQL-based_authentication | SQL-based authentication | This task has three parts:
Connect to a MySQL database (connect_db)
Create user/password records in the following table (create_user)
Authenticate login requests against the table (authenticate_user)
This is the table definition:
CREATE TABLE users (
userid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE KEY NOT NULL,
pass_salt tinyblob NOT NULL,
-- a string of 16 random bytes
pass_md5 tinyblob NOT NULL
-- binary MD5 hash of pass_salt concatenated with the password
);
(pass_salt and pass_md5 would be binary(16) values, but MySQL versions before 5.0.15 strip trailing spaces when selecting them.)
| #Python | Python | import mysql.connector
import hashlib
import sys
import random
DB_HOST = "localhost"
DB_USER = "devel"
DB_PASS = "devel"
DB_NAME = "test"
def connect_db():
''' Try to connect DB and return DB instance, if not, return False '''
try:
return mysql.connector.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME)
except:
return False
def create_user(username, passwd):
''' if user was successfully created, returns its ID; returns None on error '''
db = connect_db()
if not db:
print "Can't connect MySQL!"
return None
cursor = db.cursor()
salt = randomValue(16)
passwd_md5 = hashlib.md5(salt+passwd).hexdigest()
# If username already taken, inform it
try:
cursor.execute("INSERT INTO users (`username`, `pass_salt`, `pass_md5`) VALUES (%s, %s, %s)", (username, salt, passwd_md5))
cursor.execute("SELECT userid FROM users WHERE username=%s", (username,) )
id = cursor.fetchone()
db.commit()
cursor.close()
db.close()
return id[0]
except:
print 'Username was already taken. Please select another'
return None
def authenticate_user(username, passwd):
db = connect_db()
if not db:
print "Can't connect MySQL!"
return False
cursor = db.cursor()
cursor.execute("SELECT pass_salt, pass_md5 FROM users WHERE username=%s", (username,))
row = cursor.fetchone()
cursor.close()
db.close()
if row is None: # username not found
return False
salt = row[0]
correct_md5 = row[1]
tried_md5 = hashlib.md5(salt+passwd).hexdigest()
return correct_md5 == tried_md5
def randomValue(length):
''' Creates random value with given length'''
salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
return ''.join(random.choice(salt_chars) for x in range(length))
if __name__ == '__main__':
user = randomValue(10)
passwd = randomValue(16)
new_user_id = create_user(user, passwd)
if new_user_id is None:
print 'Failed to create user %s' % user
sys.exit(1)
auth = authenticate_user(user, passwd)
if auth:
print 'User %s authenticated successfully' % user
else:
print 'User %s failed' % user
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #AmigaBASIC | AmigaBASIC | text$=TRANSLATE$("This is an example of speech synthesis.")
SAY text$ |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #AppleScript | AppleScript |
say "This is an example of speech synthesis"
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #AutoHotkey | AutoHotkey | talk := ComObjCreate("sapi.spvoice")
talk.Speak("This is an example of speech synthesis.") |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #AutoIt | AutoIt | $voice = ObjCreate("SAPI.SpVoice")
$voice.Speak("This is an example of speech synthesis.") |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #CLU | CLU | square_not_cube = iter () yields (int)
cube_root: int := 1
square_root: int := 1
while true do
while cube_root ** 3 < square_root ** 2 do
cube_root := cube_root + 1
end
if square_root ** 2 ~= cube_root ** 3 then
yield(square_root ** 2)
end
square_root := square_root + 1
end
end square_not_cube
start_up = proc ()
amount = 30
po: stream := stream$primary_output()
n: int := 0
for i: int in square_not_cube() do
stream$putright(po, int$unparse(i), 5)
n := n + 1
if n // 10 = 0 then stream$putl(po, "") end
if n = amount then break end
end
end start_up |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #jq | jq | # Usage: prng N width
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w "$2" | head -n "$1"
} |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯
≡
1
n
∑
i
x
i
{\displaystyle {\bar {x}}\equiv {1 \over n}\sum _{i}x_{i}}
, while the stddev is
σ
≡
1
n
∑
i
(
x
i
−
x
¯
)
2
{\displaystyle \sigma \equiv {\sqrt {{1 \over n}\sum _{i}\left(x_{i}-{\bar {x}}\right)^{2}}}}
.
When examining a large quantity of data, one often uses a histogram, which shows the counts of data samples falling into a prechosen set of intervals (or bins).
When plotted, often as bar graphs, it visually indicates how often each data value occurs.
Task Using your language's random number routine, generate real numbers in the range of [0, 1]. It doesn't matter if you chose to use open or closed range.
Create 100 of such numbers (i.e. sample size 100) and calculate their mean and stddev.
Do so for sample size of 1,000 and 10,000, maybe even higher if you feel like.
Show a histogram of any of these sets.
Do you notice some patterns about the standard deviation?
Extra Sometimes so much data need to be processed that it's impossible to keep all of them at once. Can you calculate the mean, stddev and histogram of a trillion numbers? (You don't really need to do a trillion numbers, just show how it can be done.)
Hint
For a finite population with equal probabilities at all points, one can derive:
(
x
−
x
¯
)
2
¯
=
x
2
¯
−
x
¯
2
{\displaystyle {\overline {(x-{\overline {x}})^{2}}}={\overline {x^{2}}}-{\overline {x}}^{2}}
Or, more verbosely:
1
N
∑
i
=
1
N
(
x
i
−
x
¯
)
2
=
1
N
(
∑
i
=
1
N
x
i
2
)
−
x
¯
2
.
{\displaystyle {\frac {1}{N}}\sum _{i=1}^{N}(x_{i}-{\overline {x}})^{2}={\frac {1}{N}}\left(\sum _{i=1}^{N}x_{i}^{2}\right)-{\overline {x}}^{2}.}
See also
Statistics/Normal distribution
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Jsish | Jsish | #!/usr/bin/env jsish
"use strict";
function statisticsBasic(args:array|string=void, conf:object=void) {
var options = { // Rosetta Code, Statistics/Basic
rootdir :'', // Root directory.
samples : 0 // Set sample size from options
};
var self = { };
parseOpts(self, options, conf);
function generateStats(n:number):object {
var i, sum = 0, sum2 = 0;
var hist = new Array(10);
hist.fill(0);
for (i = 0; i < n; i++) {
var r = Math.random();
sum += r;
sum2 += r*r;
hist[Math.floor((r*10))] += 1;
}
var mean = sum/n;
var stddev = Math.sqrt((sum2 / n) - mean*mean);
var obj = {n:n, sum:sum, mean:mean, stddev:stddev};
return {n:n, sum:sum, mean:mean, stddev:stddev, hist:hist};
}
function reportStats(summary:object):void {
printf("Samples: %d, mean: %f, stddev: %f\n", summary.n, summary.mean, summary.stddev);
var max = Math.max.apply(summary, summary.hist);
for (var i = 0; i < 10; i++) {
printf("%3.1f+ %-70s %5d\n", i * 0.1, 'X'.repeat(70 * summary.hist[i] / max), summary.hist[i]);
}
return;
}
function main() {
LogTest('Starting', args);
switch (typeof(args)) {
case 'string': args = [args]; break;
case 'array': break;
default: args = [];
}
if (self.rootdir === '')
self.rootdir=Info.scriptDir();
Math.srand(0);
if (self.samples > 0) reportStats(generateStats(self.samples));
else if (args[0] && parseInt(args[0])) reportStats(generateStats(parseInt(args[0])));
else for (var n of [100, 1000, 10000]) reportStats(generateStats(n));
debugger;
LogDebug('Done');
return 0;
}
return main();
}
provide(statisticsBasic, 1);
if (isMain()) {
if (!Interp.conf('unitTest'))
return runModule(statisticsBasic);
;' statisticsBasic unit-test';
; statisticsBasic();
}
/*
=!EXPECTSTART!=
' statisticsBasic unit-test'
statisticsBasic() ==> Samples: 100, mean: 0.534517, stddev: 0.287124
0.0+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 8
0.1+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 11
0.2+ XXXXXXXXXXXXXXXXXXXXXXXXXX 6
0.3+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 10
0.4+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 10
0.5+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 11
0.6+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 8
0.7+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 16
0.8+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 7
0.9+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 13
Samples: 1000, mean: 0.490335, stddev: 0.286562
0.0+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 98
0.1+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 122
0.2+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 85
0.3+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 106
0.4+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 105
0.5+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 101
0.6+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 93
0.7+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 106
0.8+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 98
0.9+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 86
Samples: 10000, mean: 0.499492, stddev: 0.287689
0.0+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 969
0.1+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 992
0.2+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 1067
0.3+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 1011
0.4+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 973
0.5+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 1031
0.6+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 971
0.7+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 999
0.8+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 991
0.9+ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 996
0
=!EXPECTEND!=
*/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.