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/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... | #Lua | Lua |
function step_up()
while not step() do step_up() end
end
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
mov si,1 ; Square counter
mov di,si ; Current square
mov bp,si ; Cube counter
mov bx,si ; Current cube
xor cx,cx ; Counter
loop: cmp di,bx ; Square > cube?
jbe check
inc bp ; Calculate next cube
mov ax,bp
mul bp
mul bp
mov bx,ax
jmp loop
check: je next ; Square != c... |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, ‘On a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.’
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients ... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
use ntheory <is_prime gcd forcomb vecprod>;
my @multiplier;
my @p = <3 5 7 11>;
forcomb { push @multiplier, vecprod @p[@_] } scalar @p;
sub sff {
my($N) = shift;
return 1 if is_prime $N; # if n is prime
return sqrt $N if sqrt($N) == int sqrt $... |
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
¯... | #C.23 | C# | using System;
using MathNet.Numerics.Statistics;
class Program
{
static void Run(int sampleSize)
{
double[] X = new double[sampleSize];
var r = new Random();
for (int i = 0; i < sampleSize; i++)
X[i] = r.NextDouble();
const int numBuckets = 10;
var histogr... |
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... | #FreeBASIC | FreeBASIC | ' version 06-07-2018
' compile with: fbc -s console
Const As ULongInt trillion = 1000000000000ull
Const As ULong max = Sqr(trillion + 145)
Dim As UByte list(), sieve()
Dim As ULong prime()
ReDim list(max), prime(max\12), sieve(max)
Dim As ULong a, b, c, i, k, stop_ = Sqr(max)
For i = 4 To max Step 2 ' prime s... |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the... | #REXX | REXX | /*REXX program (state name puzzle) rearranges two state's names ──► two new states. */
!='Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia,',
'Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, ',... |
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 |... | #Scala | Scala | var d = "Hello" // Mutables are discouraged //> d : String = Hello
d += ", World!" // var contains a totally new re-instantiationed String
val s = "Hello" // Immutables are recommended //> s : String = Hello
val s1 = s + s //> s1 : String = HelloHello
val f2 = () =>... |
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 |... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var string: str is "12345678";
begin
str &:= "9!";
writeln(str);
end func; |
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 ... | #Ruby | Ruby | # Class to implement a Normal distribution, generated from a Uniform distribution.
# Uses the Marsaglia polar method.
class NormalFromUniform
# Initialize an instance.
def initialize()
@next = nil
end
# Generate and return the next Normal distribution value.
def rand()
if @next
retval, @next =... |
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 11... | #jq | jq | def stem_and_leaf:
# align-right:
def right: tostring | (4-length) * " " + .;
sort
| .[0] as $min
| .[length-1] as $max
| "\($min/10|floor|right) | " as $stem
| reduce .[] as $d
# state: [ stem, string ]
( [ 0, $stem ];
.[0] as $stem
| if ($d/10) | floor == $stem
... |
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 prece... | #Go | Go | package main
import (
"fmt"
"sternbrocot"
)
func main() {
// Task 1, using the conventional sort of generator that generates
// terms endlessly.
g := sb.Generator()
// Task 2, demonstrating the generator.
fmt.Println("First 15:")
for i := 1; i <= 15; i++ {
fmt.Printf("%2d... |
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.... | #PHP | PHP | <?php
class StackTraceDemo {
static function inner() {
debug_print_backtrace();
}
static function middle() {
self::inner();
}
static function outer() {
self::middle();
}
}
StackTraceDemo::outer();
?> |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.... | #PicoLisp | PicoLisp | (off "Stack")
(de $$ "Prg"
(let "Stack" (cons (cons (car "Prg") (env)) "Stack") # Build stack frame
(set "Stack"
(delq (asoq '"Stack" (car "Stack")) # Remove self-created entries
(delq (asoq '"Prg" (car "Stack"))
(car "Stack") ) ) )
(run (cdr "Prg")) ) ) # Run bod... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | StepUp[] := If[!Step[], StepUp[]; 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... | #MATLAB | MATLAB | function step_up()
while ~step()
step_up();
end |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #Nim | Nim | proc stepUp = (while not step(): stepUp()) |
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 ba... | #11l | 11l | [Int] stack
L(i) 1..10
stack.append(i)
L 10
print(stack.pop()) |
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.
| #Action.21 | Action! | BYTE FUNC IsCube(INT n)
INT i,c
i=1
DO
c=i*i*i
IF c=n THEN
RETURN (1)
FI
i==+1
UNTIL c>n
OD
RETURN (0)
PROC Main()
INT n,sq,count
PrintE("First 30 squares but not cubes:")
n=1 count=0
WHILE count<30
DO
sq=n*n
IF IsCube(sq)=0 THEN
PrintF("%I ",sq)
count... |
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Square_But_Not_Cube is
function Is_Cube (N : in Positive) return Boolean is
Cube : Positive;
begin
for I in Positive loop
Cube := I**3;
if Cube = N then return True;
elsif Cube > N then return False;
end if;
end loop;
... |
http://rosettacode.org/wiki/Square_form_factorization | Square form factorization | Task.
Daniel Shanks's Square Form Factorization (SquFoF).
Invented around 1975, ‘On a 32-bit computer, SquFoF is the clear champion factoring algorithm
for numbers between 1010 and 1018, and will likely remain so.’
An integral binary quadratic form is a polynomial
f(x,y) = ax2 + bxy + cy2
with integer coefficients ... | #Phix | Phix | --requires(64) -- (decided to limit 32-bit explicitly instead)
constant MxN = power(2,iff(machine_bits()=32?53:63)),
m = {1, 3, 5, 7, 11}
function squfof(atom N)
-- square form factorization
integer h, a=0, b, c, u=0, v, w, rN, q, r, t
if remainder(N,2)==0 then return 2 end if
h = floor(s... |
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
¯... | #C.2B.2B | C++ | #include <iostream>
#include <random>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <cmath>
void printStars ( int number ) {
if ( number > 0 ) {
for ( int i = 0 ; i < number + 1 ; i++ )
std::cout << '*' ;
}
std::cout << '\n' ;
}
int main( int argc , char *argv[] ) {
const ... |
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... | #Go | Go | package main
import (
"fmt"
"math"
)
func sieve(limit uint64) []uint64 {
primes := []uint64{2}
c := make([]bool, limit+1) // composite = true
// no need to process even numbers > 2
p := uint64(3)
for {
p2 := p * p
if p2 > limit {
break
}
for i ... |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the... | #Ruby | Ruby | require 'set'
# 26 prime numbers
Primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
States = [
"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho",
... |
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 |... | #Sidef | Sidef | var str = 'Foo';
str += 'bar';
say str; |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #SNOBOL4 | SNOBOL4 | s = "Hello"
s = s ", World!"
OUTPUT = s
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 |... | #Stata | Stata | sca s="Ars Longa"
sca s=s+" Vita Brevis"
di s
Ars Longa Vita Brevis |
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 ... | #Run_BASIC | Run BASIC |
s = 100000
h$ = "============================================================="
h$ = h$ + h$
dim ndis(s)
' mean and standard deviation.
mx = -9999
mn = 9999
sum = 0
sumSqr = 0
for i = 1 to s ' find minimum and maximum
ms = rnd(1)
ss = rnd(1)
nd = (-2 * log(ms))^0.5 * cos(2 *3.14159265 * ss) ' normal distribution... |
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 ... | #Rust | Rust | //! Rust rosetta example for normal distribution
use math::{histogram::Histogram, traits::ToIterator};
use rand;
use rand_distr::{Distribution, Normal};
/// Returns the mean of the provided samples
///
/// ## Arguments
/// * data -- reference to float32 array
fn mean(data: &[f32]) -> Option<f32> {
let sum: f32 = ... |
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 11... | #Julia | Julia |
function stemleaf{T<:Real}(a::Array{T,1}, leafsize=1)
ls = 10^int(log10(leafsize))
(stem, leaf) = divrem(sort(int(a/ls)), 10)
leaf[sign(stem) .== -1] *= -1
negzero = leaf .< 0
if any(negzero)
leaf[negzero] *= -1
nz = @sprintf "%10s | " "-0"
nz *= join(map(string, leaf[negze... |
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 prece... | #Haskell | Haskell | import Data.List (elemIndex)
sb :: [Int]
sb = 1 : 1 : f (tail sb) sb
where
f (a : aa) (b : bb) = a + b : a : f aa bb
main :: IO ()
main = do
print $ take 15 sb
print
[ (i, 1 + (\(Just i) -> i) (elemIndex i sb))
| i <- [1 .. 10] <> [100]
]
print $
all (\(a, b) -> 1 == gcd a b) $
t... |
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.... | #PL.2FI | PL/I |
/* The SNAP option in the ON statement is sufficient to obtain */
/* a traceback. The SYSTEM option specifies that standard */
/* system action is to occur, which resume execution after the */
/* SIGNAL statement. */
on condition(traceback) snap system;
...
signal condit... |
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.... | #PureBasic | PureBasic | Procedure Three()
a=7
ShowCallstack()
CallDebugger
EndProcedure
Procedure Two()
a=4
Three()
EndProcedure
Procedure One()
a=2
Two()
EndProcedure
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.... | #Python | Python | import traceback
def f(): return g()
def g(): traceback.print_stack()
f() |
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... | #OCaml | OCaml | let rec step_up() =
while not(step()) do
step_up()
done
;; |
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... | #Oz | Oz | proc {StepUp}
if {Not {Step}} then
{StepUp} %% make up for the fall
{StepUp} %% repeat original attempt
end
end |
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 ba... | #6502_Assembly | 6502 Assembly | PHA |
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.
| #ALGOL_68 | ALGOL 68 | BEGIN
# list the first 30 numbers that are squares but not cubes and also #
# show the numbers that are both squares and cubes #
INT count := 0;
INT c := 1;
INT c3 := 1;
FOR s WHILE count < 30 DO
INT sq = s * s;
WHILE c3 < sq DO
c +:= 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
¯... | #CoffeeScript | CoffeeScript |
generate_statistics = (n) ->
hist = {}
update_hist = (r) ->
hist[Math.floor 10*r] ||= 0
hist[Math.floor 10*r] += 1
sum = 0
sum_squares = 0.0
for i in [1..n]
r = Math.random()
sum += r
sum_squares += r*r
update_hist r
mean = sum / n
stddev = Math.sqrt((sum_squares / n) - mea... |
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... | #Haskell | Haskell | import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (factorise)
import Text.Printf (printf)
-- True iff the argument is a square-free number.
isSquareFree :: Integer -> Bool
isSquareFree = all ((== 1) . snd) . factorise
-- All square-free numbers in the range [lo, hi].
squareFrees :: Integer -> Intege... |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the... | #Scala | Scala | object StateNamePuzzle extends App {
// Logic:
def disjointPairs(pairs: Seq[Set[String]]) =
for (a <- pairs; b <- pairs; if a.intersect(b).isEmpty) yield Set(a,b)
def anagramPairs(words: Seq[String]) =
(for (a <- words; b <- words; if a != b) yield Set(a, b)) // all pairs
.groupBy(_.mkString.toLower... |
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 |... | #Swift | Swift | var s = "foo" // "foo"
s += "bar" // "foobar"
print(s) // "foobar"
s.appendContentsOf("baz") // "foobarbaz"
print(s) // "foobarbaz" |
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 |... | #Tcl | Tcl | set s "he"
set s "${s}llo wo"; # The braces distinguish varname from text to concatenate
append s "rld"
puts $s |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a ... | #SAS | SAS | data test;
n=100000;
twopi=2*constant('pi');
do i=1 to n;
u=ranuni(0);
v=ranuni(0);
r=sqrt(-2*log(u));
x=r*cos(twopi*v);
y=r*sin(twopi*v);
z=rannor(0);
output;
end;
keep x y z;
proc means mean stddev;
proc univariate;
histogram /normal;
run;
/*
Variable Mean Std Dev
-------------------... |
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 11... | #Kotlin | Kotlin | // version 1.1.2
fun leafPlot(x: IntArray) {
x.sort()
var i = x[0] / 10 - 1
for (j in 0 until x.size) {
val d = x[j] / 10
while (d > i) print("%s%3d |".format(if (j != 0) "\n" else "", ++i))
print(" ${x[j] % 10}")
}
println()
}
fun main(args: Array<String>) {
val data... |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its prece... | #J | J | sternbrocot=:1 :0
ind=. 0
seq=. 1 1
while. -. u seq do.
ind=. ind+1
seq=. seq, +/\. seq {~ _1 0 +ind
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.... | #Quackery | Quackery | > quackery
Welcome to Quackery.
Enter "leave" to leave the shell.
Building extensions.
/O> echoreturn
...
{[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 0}
Stack empty.
/O> [ cr echoreturn
... cr echostack
... dup 2 < if done
... dup 1 - swap 2 -
... recurse swap recurse + ] ... |
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.... | #R | R | foo <- function()
{
bar <- function()
{
sys.calls()
}
bar()
}
foo() |
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... | #PARI.2FGP | PARI/GP | 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... | #Pascal | Pascal | procedure stepUp;
begin
while not step do
stepUp;
end; |
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 ba... | #68000_Assembly | 68000 Assembly | LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once!
MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, with pre-decrement |
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.
| #ALGOL-M | ALGOL-M | begin
integer function square(x);
integer x;
square := x * x;
integer function cube(x);
integer x;
cube := x * x * x;
integer c, s, seen;
seen := 0;
while seen < 30 do
begin
while cube(c) < square(s) do
c := c + 1;
if square(s) <> cube(c) then
begin
if (seen/5 <> (seen-1)/5) then write(... |
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.
| #APL | APL | (×⍨∘⍳ ~ (⊢×⊢×⊢)∘⍳) 33 |
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
¯... | #D | D | import std.stdio, std.algorithm, std.array, std.typecons,
std.range, std.exception;
auto meanStdDev(R)(R numbers) /*nothrow*/ @safe /*@nogc*/ {
if (numbers.empty)
return tuple(0.0L, 0.0L);
real sx = 0.0, sxx = 0.0;
ulong n;
foreach (x; numbers) {
sx += x;
sxx += x ^^ 2... |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between... | #J | J | isSqrFree=: (#@~. = #)@q: NB. are there no duplicates in the prime factors of a number?
filter=: adverb def ' #~ u' NB. filter right arg using verb to left
countSqrFree=: +/@:isSqrFree
thru=: <. + i.@(+ *)@-~ NB. helper verb |
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... | #Java | Java | import java.util.ArrayList;
import java.util.List;
public class SquareFree
{
private static List<Long> sieve(long limit) {
List<Long> primes = new ArrayList<Long>();
primes.add(2L);
boolean[] c = new boolean[(int)limit + 1]; // composite = true
// no need to process even numbers > ... |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the... | #Tcl | Tcl | package require Tcl 8.5
# Gödel number generator
proc goedel s {
set primes {
2 3 5 7 11 13 17 19 23 29 31 37 41
43 47 53 59 61 67 71 73 79 83 89 97 101
}
set n 1
foreach c [split [string toupper $s] ""] {
if {![string is alpha $c]} continue
set n [expr {$n * [lindex $primes [expr {[scan $c %c] - 65... |
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 |... | #Transd | Transd | #lang transd
MainModule: {
_start: (λ
(with s1 "aaa" s2 "bbb" s3 "ccc"
(+= s1 s2 s3)
(textout s1))
)
} |
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 |... | #Ursa | Ursa | decl string str
set str "hello "
# append "world" to str
set str (+ str "world")
# outputs "hello world"
out str endl console |
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 ... | #Sidef | Sidef | define τ = Num.tau
func normdist (m, σ) {
var r = sqrt(-2 * 1.rand.log)
var Θ = (τ * 1.rand)
r * Θ.cos * σ + m
}
var size = 100_000
var mean = 50
var stddev = 4
var dataset = size.of { normdist(mean, stddev) }
var m = (dataset.sum / size)
say ("m: #{m}")
var σ = sqrt(dataset »**» 2 -> sum / size - m... |
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 11... | #Lua | Lua | 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,... |
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 prece... | #Java | Java | import java.math.BigInteger;
import java.util.LinkedList;
public class SternBrocot {
static LinkedList<Integer> sequence = new LinkedList<Integer>(){{
add(1); add(1);
}};
private static void genSeq(int n){
for(int conIdx = 1; sequence.size() < n; conIdx++){
int consider = sequence.get(conIdx);
int pre ... |
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.... | #Racket | Racket |
#lang racket
;; To see these calls we do two things: mutate the binding to prevent
;; Racket from inlining the value; use a (void) call at the end so the
;; calls are not tail calls (which will otherwise not show on the
;; stack).
(define foo #f)
(set! foo (λ() (bar) (void)))
(define bar #f)
(set! bar (λ() (show-st... |
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.... | #Raku | Raku | sub g { say Backtrace.new.concise }
sub f { g }
sub MAIN { f } |
http://rosettacode.org/wiki/Stack_traces | Stack traces | Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers.
Task
Print out (in a manner considered suitable for the platform) the current call stack.... | #Raven | Raven | [1 2 3 4] 42 { 'a' 1 'b' 2 'c' 3 } 34.1234 ( -1 -2 -3 ) "The quick brown fox" FILE dump |
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... | #Perl | Perl | 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... | #Phix | Phix | procedure step_up()
while not step() do step_up() end while
end procedure
|
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... | #PicoLisp | PicoLisp | (de stepUp ()
(until (step1) # ('step1', because 'step' is a system function)
(stepUp) ) ) |
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 ba... | #8086_Assembly | 8086 Assembly | push ax ;push ax onto the stack
pop ax ; pop the top two bytes of the stack into ax |
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(... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <time.h>
#include <mysql.h>
#include <openssl/md5.h>
void end_with_db(void);
MYSQL *mysql = NULL; // global...
bool connect_db(const char *host, const char *user, const char *pwd,
const char *db, unsigned int port)
{
if... |
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.
| #AppleScript | AppleScript | on run
script listing
on |λ|(x)
set sqr to x * x
set strSquare to sqr as text
if isCube(sqr) then
strSquare & " (also cube)"
else
strSquare
end if
end |λ|
end script
unlines(map(listing, ¬
... |
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
¯... | #Dart | Dart | /* Import math library to get:
* 1) Square root function : Math.sqrt(x)
* 2) Power function : Math.pow(base, exponent)
* 3) Random number generator : Math.Random()
*/
import 'dart:math' as Math show sqrt, pow, Random;
// Returns average/mean of a list of numbers
num mean(List<num> l) => l.redu... |
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... | #jq | jq | def is_square_free: . as $n | all( squares; divides($n) | not);
|
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the... | #Wren | Wren | import "/str" for Str
import "/sort" for Sort
import "/fmt" for Fmt
var solve = Fn.new { |states|
var dict = {}
for (state in states) {
var key = Str.lower(state).replace(" ", "")
if (!dict[key]) dict[key] = state
}
var keys = dict.keys.toList
Sort.quick(keys)
var solutions = [... |
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 |... | #Vala | Vala | void main() {
string x = "foo";
x += "bar\n";
print(x);
} |
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 |... | #VBA | VBA | Function StringAppend()
Dim s As String
s = "foo"
s = s & "bar"
Debug.Print s
End Function |
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 |... | #VBScript | VBScript | s = "Rosetta"
s = s & " Code"
WScript.StdOut.Write s |
http://rosettacode.org/wiki/Statistics/Normal_distribution | Statistics/Normal distribution | The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator.
The task
Take a uniform random number generator and create a ... | #Stata | Stata | clear all
set obs 100000
gen u=runiform()
gen v=runiform()
gen r=sqrt(-2*log(u))
gen x=r*cos(2*_pi*v)
gen y=r*sin(2*_pi*v)
gen z=rnormal()
sum x y z
Variable | Obs Mean Std. Dev. Min Max
-------------+---------------------------------------------------------
x | 100,000... |
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 ... | #Tcl | Tcl | package require Tcl 8.5
# Uses the Box-Muller transform to compute a pair of normal random numbers
proc tcl::mathfunc::nrand {mean stddev} {
variable savednormalrandom
if {[info exists savednormalrandom]} {
return [expr {$savednormalrandom*$stddev + $mean}][unset savednormalrandom]
}
set r [expr {sqrt(... |
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 11... | #Maple | Maple | StemPlot := proc( datatable::{rtable,list,algebraic} )
local i, j, k, tf, LeafStemTable, LeafStemIndices;
k:=0;
LeafStemTable := ListTools:-Categorize( (x,y) -> iquo(x, 10) = iquo(y, 10), sort(datatable));
if LeafStemTable = NULL then
error "Empty List";
elif nops( [ LeafStemTable ] )... |
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 prece... | #JavaScript | JavaScript | (() => {
'use strict';
const main = () => {
// sternBrocot :: Generator [Int]
const sternBrocot = () => {
const go = xs => {
const x = snd(xs);
return tail(append(xs, [fst(xs) + x, x]));
};
return fmapGen(head, iterate(go, [... |
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.... | #REXX | REXX | /* call stack */
say 'Call A'
call A '123'
say result
exit 0
A:
say 'Call B'
call B '456'
say result
return ARG(1)
B:
say 'Call C'
call C '789'
say result
return ARG(1)
C:
call callstack
return ARG(1)
callstack: procedure
getcallstack(cs.)
say 'Dump call stack with' cs.0 'items'
do i = 1 to cs.0
parse var c... |
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.... | #Ruby | Ruby | def outer(a,b,c)
middle a+b, b+c
end
def middle(d,e)
inner d+e
end
def inner(f)
puts caller(0)
puts "continuing... my arg is #{f}"
end
outer 2,3,5 |
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... | #PowerShell | PowerShell | function StepUp
{
If ( -not ( Step ) )
{
StepUp
StepUp
}
}
# Step simulator for testing
function Step
{
If ( Get-Random 0,1 )
{
$Success = $True
Write-Verbose "Up one step"
}
Else
{
$Success = $False
Write... |
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... | #Prolog | Prolog | step_up :- \+ step, step_up, step_up. |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #PureBasic | PureBasic | Procedure step_up()
Protected i
Repeat: If _step(): i + 1: Else: i - 1: EndIf: Until i = 1
EndProcedure |
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 ba... | #ABAP | ABAP |
report z_stack.
interface stack.
methods:
push
importing
new_element type any
returning
value(new_stack) type ref to stack,
pop
exporting
top_element type any
returning
value(new_stack) type ref to stack,
empty
returning
... |
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(... | #C.23 | C# | using System.Security.Cryptography;
using System.Text;
namespace rosettaMySQL
{
class Hasher
{
private static string _BytesToHex(byte[] input)
{
var strBuilder = new StringBuilder();
foreach (byte _byte in input)
{
strBuilder.Append(_byte.ToS... |
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(... | #Go | Go | package main
import (
"bytes"
"crypto/md5"
"crypto/rand"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func connectDB() (*sql.DB, error) {
return sql.Open("mysql", "rosetta:code@/rc")
}
func createUser(db *sql.DB, user, pwd string) error {
salt := make([]byte, 16)
... |
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.
| #Arturo | Arturo | squares: map 1..100 => [&^2]
cubes: map 1..100 => [&^3]
print "Square but not cube:"
print first.n:30 select squares => [not? in? & cubes]
print "Square and cube:"
print first.n:3 select squares => [in? & cubes] |
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.
| #AutoHotkey | AutoHotkey | cube := [], counter:=0
while counter<30 {
cube[(n := A_Index)**3] := true
if !cube[n**2]
counter++, res .= n**2 " "
else
res .= "[" n**2 "] "
}
MsgBox % Trim(res, " ") |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯... | #Elixir | Elixir | defmodule Statistics do
def basic(n) do
{sum, sum2, hist} = generate(n)
mean = sum / n
stddev = :math.sqrt(sum2 / n - mean*mean)
IO.puts "size: #{n}"
IO.puts "mean: #{mean}"
IO.puts "stddev: #{stddev}"
Enum.each(0..9, fn i ->
:io.fwrite "~.1f:~s~n", [0.1*i, String.duplicate("="... |
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
¯... | #Factor | Factor | USING: assocs formatting grouping io kernel literals math
math.functions math.order math.statistics prettyprint random
sequences sequences.deep sequences.repeating ;
IN: rosetta-code.statistics-basic
CONSTANT: granularity
$[ 11 iota [ 10 /f ] map 2 clump ]
: mean/std ( seq -- a b )
[ mean ] [ population-std... |
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... | #Julia | Julia | using Primes
const maxrootprime = Int64(floor(sqrt(1000000000145)))
const sqprimes = map(x -> x * x, primes(2, maxrootprime))
possdivisorsfor(n) = vcat(filter(x -> x <= n / 2, sqprimes), n in sqprimes ? n : [])
issquarefree(n) = all(x -> floor(n / x) != n / x, possdivisorsfor(n))
function squarefreebetween(mn, mx)
... |
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... | #Kotlin | Kotlin | // Version 1.2.50
import kotlin.math.sqrt
fun sieve(limit: Long): List<Long> {
val primes = mutableListOf(2L)
val c = BooleanArray(limit.toInt() + 1) // composite = true
// no need to process even numbers > 2
var p = 3
while (true) {
val p2 = p * p
if (p2 > limit) break
f... |
http://rosettacode.org/wiki/State_name_puzzle | State name puzzle | Background
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit.
The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the... | #zkl | zkl | #<<< // here doc
states:=("Alabama, Alaska, Arizona, Arkansas,
California, Colorado, Connecticut, Delaware, Florida,
Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas,
Kentucky, Louisiana, Maine, Maryland, Massachusetts,
Michigan, Minnesota, Mississippi, Missouri, Montana,
Nebraska, Nevada, New Ha... |
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 |... | #Vlang | Vlang | mut s:= 'foo'
s += 'bar'
println(s)
foo := 'foo'
bar := 'bar'
foobar := '$foo$bar'
println(foobar) |
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 |... | #Wart | Wart | s <- "12345678"
s <- (s + "9!") |
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 |... | #Wren | Wren | var s = "Hello, "
s = s + "world!"
System.print(s) |
http://rosettacode.org/wiki/String_append | String append |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |... | #XPL0 | XPL0 | include xpllib;
char A, B, C(80);
[A:= "Hello, ";
B:= "world!";
StrCopy(C, A);
StrCat(C, B);
Text(0, C);
] |
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 ... | #VBA | VBA | Public Sub standard_normal()
Dim s() As Variant, bins(71) As Single
ReDim s(20000)
For i = 1 To 20000
s(i) = WorksheetFunction.Norm_S_Inv(Rnd())
Next i
For i = -35 To 35
bins(i + 36) = i / 10
Next i
Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.