task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between... | #Perl | Perl | use ntheory qw/is_square_free moebius/;
sub square_free_count {
my ($n) = @_;
my $count = 0;
foreach my $k (1 .. sqrt($n)) {
$count += moebius($k) * int($n / $k**2);
}
return $count;
}
print "Square─free numbers between 1 and 145:\n";
print join(' ', grep { is_square_free($_) } 1 .. 145)... |
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... | #PicoLisp | PicoLisp | (de *Data
12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36
29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119
58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127
29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43
117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38... |
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.
Fo... | #AppleScript | AppleScript | intercalate(", ", ¬
map(curry(intercalate)'s |λ|(""), ¬
group("gHHH5YY++///\\")))
--> "g, HHH, 5, YY, ++, ///, \\"
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- curry :: (Script|Handler) -> Script
on curry(f)
script
on |λ|(a)
script
... |
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... | #Nim | Nim | import math, strformat, strutils
iterator sternBrocot(): (int, int) =
## Yield index and value of the terms of the sequence.
var sequence: seq[int]
sequence.add 1
sequence.add 1
var index = 1
yield (1, 1)
yield (2, 1)
while true:
sequence.add sequence[index] + sequence[index - 1]
yield (sequen... |
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... | #Tcl | Tcl | set level 41
set prob 0.5001
proc step {} {
global level prob steps
incr steps
if {rand() < $prob} {
incr level 1
return 1
} else {
incr level -1
return 0
}
} |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #TI-83_BASIC | TI-83 BASIC | If rand>.5:Then
0→C
Disp "FALL"
If A=1:Then
D-1→D
Disp D
End
Else
1→C
Disp "CLIMB"
If A=1:Then
D+1→D
Disp D
End
End
If B=1
Pause |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #Wren | Wren | import "random" for Random
import "/fmt" for Conv
var rand = Random.new(1268) // generates short repeatable sequence
var position = 0
var step = Fn.new {
var r = Conv.itob(rand.int(2))
if (r) {
position = position + 1
System.print("Climbed up to %(position)")
} else {
position = ... |
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... | #Arturo | Arturo | Stack: $[]-> []
pushTo: function [st val]-> 'st ++ val
popStack: function [st] [
result: last st
remove 'st .index (size st)-1
return result
]
emptyStack: function [st]-> empty 'st
printStack: function [st]-> print st
st: new Stack
pushTo st "one"
pushTo st "two"
pushTo st "three"
printStac... |
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(... | #Racket | Racket | #lang racket
(require db file/md5)
(define-logger authentication)
(current-logger authentication-logger)
(define DB-HOST "localhost")
(define DB-USER "devel")
(define DB-PASS "devel")
(define DB-NAME "test")
(define (connect-db)
(mysql-connect
#:user DB-USER
#:database DB-NAME
#:password DB-PASS))
... |
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(... | #Raku | Raku |
use v6;
use DBIish;
multi connect_db(:$dbname, :$host, :$user, :$pass) {
my $db = DBIish.connect("mysql",host => $host, database =>$dbname, user =>$user, password =>$pass, :RaiseError)
or die "ERROR: {DBIish.errstr}.";
$db;
}
multi create_user(:$db, :$user, :$pass) {
#https://stackoverflow.com/que... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #BASIC256 | BASIC256 | say "Goodbye, World for the " + 123456 + "th time."
say "This is an example of speech synthesis." |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Batch_File | Batch File | @set @dummy=0 /*
::Batch File section
@echo off
cscript //e:jscript //nologo "%~f0" "%~1"
exit /b
::*/
//The JScript section
var objVoice = new ActiveXObject("SAPI.SpVoice");
objVoice.speak(WScript.Arguments(0)); |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #BBC_BASIC | BBC BASIC | SPF_ASYNC = 1
ON ERROR SYS `CoUninitialize` : PRINT 'REPORT$ : END
ON CLOSE SYS `CoUninitialize` : QUIT
SYS "LoadLibrary","OLE32.DLL" TO O%
SYS "GetProcAddress",O%,"CoInitialize" TO `CoInitialize`
SYS "GetProcAddress",O%,"CoUninitialize" TO `CoUninitialize`
SYS "GetProcAddres... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #C | C | #include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void talk(const char *s)
{
pid_t pid;
int status;
pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
execlp("espeak", "espeak", s, (void*)0);
perror("espeak");
_exit(1);
}
waitpid(pid, &status... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. SQUARE-NOT-CUBE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 COMPUTATION.
02 SQ-ROOT PIC 9999 COMP VALUE 1.
02 CUBE-ROOT PIC 9999 COMP VALUE 1.
02 SQUARE PIC 9999 COMP VALUE 1.
02 C... |
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
¯... | #Julia | Julia | using Printf
function hist(numbers)
maxwidth = 50
h = fill(0, 10)
for n in numbers
h[ceil(Int, 10n)] += 1
end
mx = maximum(h)
for (n, i) in enumerate(h)
@printf("%3.1f: %s\n", n / 10, "+" ^ floor(Int, i / mx * maxwidth))
end
end
for i in 1:6
n = rand(10 ^ i)
print... |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯... | #Klong | Klong |
.l("nstat.kg")
bar::{x{x;.d("*")}:*0;.p("")}
hist10::{[s];#'=s@<s::_x*10}
plot::{[s];.p("");.p("n = ",$x);
(!10){.d(x%10);.d(" ");bar(y)}'_(100%x)*(hist10(s::{x;.rn()}'!x));
.p("mean = ",$mu(s));.p("sd = ",$sd(s))}
plot(100)
plot(1000)
plot(10000)
|
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between... | #Phix | Phix | with javascript_semantics
function square_frees(atom start, finish)
sequence res = {}
integer maxprime = get_maxprime(finish)
while start<=finish do
if square_free(start,maxprime) then
res &= start
end if
start += 1
end while
return res
end function
procedure sh... |
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... | #PowerShell | PowerShell |
$Set = -split '12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 ... |
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.
Fo... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program splitcar.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/***********************... |
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... | #Oforth | Oforth | : stern(n)
| l i |
ListBuffer new dup add(1) dup add(1) dup ->l
n 1- 2 / loop: i [ l at(i) l at(i 1+) tuck + l add l add ]
n 2 mod ifFalse: [ dup removeLast drop ] dup freeze ;
stern(10000) Constant new: Sterns |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #XPL0 | XPL0 | proc Step_up; \Iterative version
int I;
[I:= 0;
while I<1 do
if Step then I:= I+1
else I:= I-1;
];
proc Step_up; \Recursive version
while not Step do Step_up; |
http://rosettacode.org/wiki/Stair-climbing_puzzle | Stair-climbing puzzle | From Chung-Chieh Shan (LtU):
Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a... | #zkl | zkl | fcn step{ } // add code to return Bool
fcn stepUp{ while(not step()){ self.fcn() } } |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #11l | 11l | L
L(rod) ‘\|/-’
print(rod, end' "\r")
sleep(0.25) |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The ba... | #ATS | ATS | (* Stacks implemented as linked lists. *)
(* A nonlinear stack type of size n, which is good for when you are
using a garbage collector or can let the memory leak. *)
typedef stack_t (t : t@ype+, n : int) = list (t, n)
typedef stack_t (t : t@ype+) = [n : int] stack_t (t, n)
(* A linear stack type of size n, whic... |
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(... | #Raven | Raven | 'mysql://root@localhost/test' open as mysql
'abcdefghijklmnopqrstuvwxyz0123456789' as $salt_chars
# return userid for success and FALSE for failure.
define create_user use $user, $pass
group 16 each as i
$salt_chars choose chr
join as $pass_salt
"%($pass_salt)s%($pass)s" md5 as $pass_md5
$us... |
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(... | #Ruby | Ruby | require 'mysql2'
require 'securerandom'
require 'digest'
def connect_db(host, port = nil, username, password, db)
Mysql2::Client.new(
host: host,
port: port,
username: username,
password: password,
database: db
)
end
def create_user(client, username, password)
salt = SecureRandom.random_by... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #C.23 | C# | using SpeechLib;
namespace Speaking_Computer
{
public class Program
{
private static void Main()
{
var voice = new SpVoice();
voice.Speak("This is an example of speech synthesis.");
}
}
} |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Clojure | Clojure | (use 'speech-synthesis.say)
(say "This is an example of speech synthesis.") |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #FreeBASIC | FreeBASIC | ''This works on Windows. Does anyone know how it would be done in Linux?
Sub speak(texto As String)
Dim As String frase
frase ="mshta vbscript:Execute(""CreateObject(""""SAPI.SpVoice"""").Speak("""""+texto+""""")(window.close)"")"
Print texto
Shell frase
End Sub
speak "Vamos a contar " + str(123456... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Comal | Comal | 0010 ZONE 5
0020 cube_n#:=0;square_n#:=0;seen#:=0
0030 WHILE seen#<30 DO
0040 WHILE cube_n#^3<square_n#^2 DO cube_n#:+1
0050 IF cube_n#^3<>square_n#^2 THEN
0060 PRINT square_n#^2,
0070 seen#:+1
0080 IF seen# MOD 5=0 THEN PRINT
0090 ENDIF
0100 square_n#:+1
0110 ENDWHILE
0120 END |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Commodore_BASIC | Commodore BASIC | 100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES
110 PRINT "SQUARES BUT NOT CUBES:"
120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND
130 SR = 1: REM CURRENT SQUARE ROOT
140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE
150 REM BEGIN LOOP
160 : IF N >= 30 THEN 230
170 : SQ = SR * SR
180 : IF SQ > CU THEN CR = CR + 1: ... |
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
¯... | #Kotlin | Kotlin | // version 1.1.2
val rand = java.util.Random()
fun basicStats(sampleSize: Int) {
if (sampleSize < 1) return
val r = DoubleArray(sampleSize)
val h = IntArray(10) // all zero by default
/*
Generate 'sampleSize' random numbers in the interval [0, 1)
and calculate in which box they will fa... |
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... | #Python | Python |
import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ): # Create a custom prime sieve
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == Sq... |
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... | #PureBasic | PureBasic | If OpenConsole()
Dim MyList(120)
Define i, j, StemMax, StemMin
Restore MyData ; Get the address of MyData, e.g. the data to print as a Stem-and-leaf plot
For a=0 To 120
Read.i MyList(a) ; Read the data into the used Array
If MyList(a)>StemMax
StemMax=MyList(a) ; Find the largest St... |
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.
Fo... | #Arturo | Arturo | parts: [] current: ""
loop split {gHHH5YY++///\} 'ch [
if? or? empty? current
contains? current ch -> 'current ++ ch
else [
'parts ++ current
current: new ch
]
]
'parts ++ current
print parts |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #AutoHotkey | AutoHotkey | Split_Change(str){
for i, v in StrSplit(str)
res .= (v=prev) ? v : (res?", " :"") v , prev := v
return res
} |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its prece... | #PARI.2FGP | PARI/GP |
\\ Stern-Brocot sequence
\\ 5/27/16 aev
SternBrocot(n)={
my(L=List([1,1]),k=2); if(n<3,return(L));
for(i=2,n, listput(L,L[i]+L[i-1]); if(k++>=n, break); listput(L,L[i]);if(k++>=n, break));
return(Vec(L));
}
\\ Find the first item in any list starting with sind index (return 0 or index).
\\ 9/11/2015 aev
findinlist(li... |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #Action.21 | Action! | PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC Main()
CHAR ARRAY spin="|/-\"
BYTE i,
CH=$02FC, ;Internal hardware value for last key pressed
CRSINH=$02F0 ;Controls visibility of cursor
Print("Press any key to exit...")
CRSINH=1 ;hide cursor
i=1
... |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #Ada | Ada | with Ada.Text_IO;
procedure Spinning_Rod is
use Ada.Text_IO;
type Index_Type is mod 4;
Rod : constant array (Index_Type) of Character := ('|', '/', '-', '\');
Index : Index_Type := 0;
Char : Character;
Avail : Boolean;
begin
Put (ASCII.ESC & "[?25l"); -- Hide the cursor
loop
... |
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... | #AutoHotkey | AutoHotkey | msgbox % stack("push", 4)
msgbox % stack("push", 5)
msgbox % stack("peek")
msgbox % stack("pop")
msgbox % stack("peek")
msgbox % stack("empty")
msgbox % stack("pop")
msgbox % stack("empty")
return
stack(command, value = 0)
{
static
if !pointer
pointer = 10000
if (command = "push")
{
_p%pointer% := value
... |
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(... | #Sidef | Sidef | require('DBI')
# returns a database handle configured to throw an exception on query errors
func connect_db(dbname, host, user, pass) {
var db = %s<DBI>.connect("dbi:mysql:#{dbname}:#{host}", user, pass)
db || die (global DBI::errstr)
db{:RaiseError} = 1
db
}
# if the user was successfully created... |
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(... | #Tcl | Tcl | package require tdbc
proc connect_db {handleName dbname host user pass} {
package require tdbc::mysql
tdbc::mysql::connection create $handleName -user $user -passwd $pass \
-host $host -database $dbname
return $handleName
}
# A simple helper to keep code shorter
proc r64k {} {
expr int(65536... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #GlovePIE | GlovePIE | if var.number=0 then
var.number=1
say("This is an example of speech synthesis.")
endif |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Go | Go | package main
import (
"go/build"
"log"
"path/filepath"
"github.com/unixpickle/gospeech"
"github.com/unixpickle/wav"
)
const pkgPath = "github.com/unixpickle/gospeech"
const input = "This is an example of speech synthesis."
func main() {
p, err := build.Import(pkgPath, ".", build.FindOnly... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Groovy | Groovy | 'say "This is an example of speech synthesis."'.execute() |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Common_Lisp | Common Lisp | (defun cubep (n)
(loop for i from 1
for c = (* i i i)
while (<= c n)
when (= c n) do (return t)
finally (return nil)))
(defparameter squares (let ((n 0)) (lambda () (incf n) (* n n))))
(destructuring-bind (noncubes cubes)
(loop for s = (funcall squares) then (funcall square... |
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
¯... | #Lasso | Lasso | define stat1(a) => {
if(#a->size) => {
local(mean = (with n in #a sum #n) / #a->size)
local(sdev = math_pow(((with n in #a sum Math_Pow((#n - #mean),2)) / #a->size),0.5))
return (:#sdev, #mean)
else
return (:0,0)
}
}
define stat2(a) => {
if(#a->size) => {
local(sx = 0, sxx = 0)
with x in #a do => {
#... |
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
¯... | #Liberty_BASIC | Liberty BASIC |
call sample 100
call sample 1000
call sample 10000
end
sub sample n
dim dat( n)
for i =1 to n
dat( i) =rnd( 1)
next i
'// show mean, standard deviation
sum =0
sSq =0
for i =1 to n
sum =sum +dat( i)
sSq =sSq +dat( i)^2
next i
print n; " data terms... |
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... | #Racket | Racket | #lang racket
(define (not-square-free-set-for-range range-min (range-max (add1 range-min)))
(for*/set ((i2 (sequence-map sqr (in-range 2 (add1 (integer-sqrt range-max)))))
(i2.x (in-range (* i2 (quotient range-min i2))
(* i2 (add1 (quotient range-max i2)))
... |
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... | #Raku | Raku | # Prime factorization routines
sub prime-factors ( Int $n where * > 0 ) {
return $n if $n.is-prime;
return [] if $n == 1;
my $factor = find-factor( $n );
flat prime-factors( $factor ), prime-factors( $n div $factor );
}
sub find-factor ( Int $n, $constant = 1 ) {
return 2 unless $n +& 1;
if (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... | #Python | Python | from collections import namedtuple
from pprint import pprint as pp
from math import floor
Stem = namedtuple('Stem', 'data, leafdigits')
data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37,
48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35,
113, 122... |
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.
Fo... | #AWK | AWK |
# syntax: GAWK -f SPLIT_A_CHARACTER_STRING_BASED_ON_CHANGE_OF_CHARACTER.AWK
BEGIN {
str = "gHHH5YY++///\\"
printf("old: %s\n",str)
printf("new: %s\n",split_on_change(str))
exit(0)
}
function split_on_change(str, c,i,new_str) {
new_str = substr(str,1,1)
for (i=2; i<=length(str); i++) {
c... |
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.
Fo... | #BaCon | BaCon | txt$ = "gHHH5YY++///\\"
c$ = LEFT$(txt$, 1)
FOR x = 1 TO LEN(txt$)
d$ = MID$(txt$, x, 1)
IF d$ <> c$ THEN
PRINT ", ";
c$ = d$
END IF
PRINT d$;
NEXT |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its prece... | #Pascal | Pascal | program StrnBrCt;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
const
MaxCnt = 10835282;{ seq[i] < 65536 = high(Word) }
//MaxCnt = 500*1000*1000;{ 2Gbyte -> real 0.85 s user 0.31 }
type
tSeqdata = word;//cardinal LongWord
pSeqdata = pWord;//pcardinal pLongWord
tseq = array of tSeqdata;
function SternBrocotCreate(si... |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #ALGOL_68 | ALGOL 68 | FOR i TO 1 000 DO # increase/decrease the TO value for a longer/shorter animation #
FOR d TO 2 000 000 DO SKIP OD; # adjust to change the spin rate #
print( ( CASE 1 + i MOD 4 IN "/", "-", "\", "|" ESAC, REPR 8 ) )
OD |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The ba... | #AWK | AWK | function deque(arr) {
arr["start"] = 0
arr["end"] = 0
}
function dequelen(arr) {
return arr["end"] - arr["start"]
}
function empty(arr) {
return dequelen(arr) == 0
}
function push(arr, elem) {
arr[++arr["end"]] = elem
}
function pop(arr) {
if (empty(arr)) {
return
}
retur... |
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(... | #Wren | Wren | import "./sql" for Sql, Connection
import "./crypto" for Md5
var addUser = Fn.new { |db, name, pw|
var sql = "INSERT OR IGNORE INTO users (username,pass_salt,pass_md5) VALUES(?, ?, ?)"
var stmt = db.prepare(sql)
var salt = Sql.randomness(16)
var md5s = Md5.digest(salt + pw)
stmt.bindText(1, name)
... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Haskell | Haskell |
import System.Process (callProcess) -- From “process” library
say text = callProcess "espeak" ["--", text]
main = say "This is an example of speech synthesis."
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #JavaScript | JavaScript |
var utterance = new SpeechSynthesisUtterance("This is an example of speech synthesis.");
window.speechSynthesis.speak(utterance);
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Julia | Julia |
julia> a = "hello world"
"hello world"
julia> run(`espeak $a`)
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Cowgol | Cowgol | include "cowgol.coh";
var cube: uint16 := 1;
var ncube: uint16 := 1;
var sqr: uint16 := 1;
var nsqr: uint16 := 1;
var seen: uint8 := 0;
while seen < 30 loop
sqr := nsqr * nsqr;
while sqr > cube loop
ncube := ncube + 1;
cube := ncube * ncube * ncube;
end loop;
if sqr != cube then
... |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #D | D | import std.algorithm;
import std.range;
import std.stdio;
auto squareGen() {
struct Gen {
private int add = 3;
private int curr = 1;
bool empty() {
return curr < 0;
}
auto front() {
return curr;
}
void popFront() {
c... |
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
¯... | #Lua | Lua |
math.randomseed(os.time())
function randList (n) -- Build table of size n
local numbers = {}
for i = 1, n do
table.insert(numbers, math.random()) -- range correct by default
end
return numbers
end
function mean (t) -- Find mean average of values in table t
local sum = 0
for k, v in pairs(t) do
sum = s... |
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... | #REXX | REXX | /*REXX program displays square─free numbers (integers > 1) up to a specified limit. */
numeric digits 20 /*be able to handle larger numbers. */
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 1 ... |
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... | #R | R |
x <- c(12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36,
29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109,
23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113,
121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, ... |
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... | #Racket | Racket |
#lang racket
(define (show-stem+leaf data)
(define xs (sort data <))
(for ([stem (add1 (floor (/ (last xs) 10)))])
(printf "~a|" (~a #:width 2 #:align 'right stem))
(for ([i xs])
(define-values [q r] (quotient/remainder i 10))
(when (= q stem) (printf " ~a" r)))
(newline)))
(show-stem+leaf... |
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.
Fo... | #BASIC256 | BASIC256 | function split$(instring$)
if length(instring$) < 2 then return instring$
ret$ = left(instring$,1)
for i = 2 to length(instring$)
if mid(instring$,i,1) <> mid(instring$, i-1, 1) then ret$ += ", "
ret$ += mid(instring$, i, 1)
next i
return ret$
end function
print split$("gHHH5YY++///\") |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
Fo... | #BBC_BASIC | BBC BASIC | REM >split
PRINT FN_split( "gHHH5YY++///\" )
END
DEF FN_split( s$ )
LOCAL c$, split$, d$, i%
c$ = LEFT$( s$, 1 )
split$ = ""
FOR i% = 1 TO LEN s$
LET d$ = MID$( s$, i%, 1 )
IF d$ <> c$ THEN
split$ += ", "
c$ = d$
ENDIF
split$ += d$
NEXT
= split$ |
http://rosettacode.org/wiki/Stern-Brocot_sequence | Stern-Brocot sequence | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence.
The first and second members of the sequence are both 1:
1, 1
Start by considering the second member of the sequence
Sum the considered member of the sequence and its prece... | #Perl | Perl | use strict;
use warnings;
sub stern_brocot {
my @list = (1, 1);
sub {
push @list, $list[0] + $list[1], $list[1];
shift @list;
}
}
{
my $generator = stern_brocot;
print join ' ', map &$generator, 1 .. 15;
print "\n";
}
for (1 .. 10, 100) {
my $index = 1;
my $generator = stern_bro... |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #AWK | AWK |
# syntax: GAWK -f SPINNING_ROD_ANIMATION_TEXT.AWK
@load "time"
BEGIN {
while (1) {
printf(" %s\r",substr("|/-\\",x++%4+1,1))
sleep(.25)
}
exit(0)
}
|
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #BaCon | BaCon | WHILE TRUE
PRINT CR$, TOKEN$("🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘", x);
x = IIF(x>7, 1, x+1)
SLEEP 250
WEND |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The ba... | #Axe | Axe | 0→S
Lbl PUSH
r₁→{L₁+S}ʳ
S+2→S
Return
Lbl POP
S-2→S
{L₁+S}ʳ
Return
Lbl EMPTY
S≤≤0
Return |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Kotlin | Kotlin | // Kotlin Native v0.6.2
import kotlinx.cinterop.*
import platform.posix.*
fun talk(s: String) {
val pid = fork()
if (pid < 0) {
perror("fork")
exit(1)
}
if (pid == 0) {
execlp("espeak", "espeak", s, null)
perror("espeak")
_exit(1)
}
memScoped {
val ... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Liberty_BASIC | Liberty BASIC |
nomainwin
run "C:\Program Files\eSpeak\command_line\espeak "; chr$( 34); "This is an example of speech synthesis."; chr$( 34)
end
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Locomotive_Basic | Locomotive Basic | |say,"This is an example of speech synthesis." |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #dc | dc |
[n = # of non-cube squares found; we stop when it hits 30]sz
[b = # found that are both squares and cubes]sz
0 d sn sb
[c = current cube, s = current square,
r = current cube root, q = current square root,
f = "first" flag, to control comma delimiting]sz
1 d sc d ss d sq d sr sf
[M = main loop]sz
[
lq d... |
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
¯... | #Maple | Maple | with(Statistics):
X_100 := Sample( Uniform(0,1), 100 );
Mean( X_100 );
StandardDeviation( X_100 );
Histogram( X_100 ); |
http://rosettacode.org/wiki/Statistics/Basic | Statistics/Basic | Statistics is all about large groups of numbers.
When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev).
If you have set of data
x
i
{\displaystyle x_{i}}
where
i
=
1
,
2
,
…
,
n
{\displaystyle i=1,2,\ldots ,n\,\!}
, the mean is
x
¯... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Sample[n_]:= (Print[#//Length," numbers, Mean : ",#//Mean,", StandardDeviation : ",#//StandardDeviation ];
BarChart[BinCounts[#,{0,1,.1}], Axes->False, BarOrigin->Left])&[(RandomReal[1,#])&[ n ]]
Sample/@{100,1 000,10 000,1 000 000} |
http://rosettacode.org/wiki/Square-free_integers | Square-free integers | Task
Write a function to test if a number is square-free.
A square-free is an integer which is divisible by no perfect square other
than 1 (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between... | #Ruby | Ruby | require "prime"
class Integer
def square_free?
prime_division.none?{|pr, exp| exp > 1}
end
end
puts (1..145).select(&:square_free?).each_slice(20).map{|a| a.join(" ")}
puts
m = 10**12
puts (m..m+145).select(&:square_free?).each_slice(6).map{|a| a.join(" ")}
puts
markers = [100, 1000, 10_000, 100_000, 1_... |
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... | #Raku | Raku | my @data = <
12 127 28 42 39 113 42 18 44 118 44
37 113 124 37 48 127 36 29 31 125 139
131 115 105 132 104 123 35 113 122 42 117
119 58 109 23 105 63 27 44 105 99 41
128 121 116 125 32 61 37 127 29 113 121
58 114 126 53 114 96 25 109 7 31 141
46 13 27 43... |
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.
Fo... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *split(char *str);
int main(int argc,char **argv)
{
char input[13]="gHHH5YY++///\\";
printf("%s\n",split(input));
}
char *split(char *str)
{
char last=*str,*result=malloc(3*strlen(str)),*counter=result;
for (char *c=str;*c;c++) {
if (*c!=last) {
s... |
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... | #Phix | Phix | sequence sb = {1,1}
integer c = 2
function stern_brocot(integer n)
while length(sb)<n do
sb &= sb[c]+sb[c-1] & sb[c]
c += 1
end while
return sb[1..n]
end function
sequence s = stern_brocot(15)
puts(1,"first 15:")
?s
integer n = 16, k
sequence idx = tagset(10)
for i=1 to length(idx) do
... |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #Bash | Bash | while : ; do
for rod in \| / - \\ ; do printf ' %s\r' $rod; sleep 0.25; done
done |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #C | C | #include <stdio.h>
#include <time.h>
int main() {
int i, j, ms = 250;
const char *a = "|/-\\";
time_t start, now;
struct timespec delay;
delay.tv_sec = 0;
delay.tv_nsec = ms * 1000000L;
printf("\033[?25l"); // hide the cursor
time(&start);
while(1) {
for (i = 0; i < 4;... |
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... | #Babel | Babel | main :
{ (1 2 3) foo set -- foo = (1 2 3)
4 foo push -- foo = (1 2 3 4)
0 foo unshift -- foo = (0 1 2 3 4)
foo pop -- foo = (0 1 2 3)
foo shift -- foo = (1 2 3)
check_foo
{ foo pop } 4 times -- Pops too many times, but this is OK and Babel ... |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #M2000_Interpreter | M2000 Interpreter |
Module UsingStatementSpeech {
Volume 100
Speech "This is an example of speech synthesis."
}
UsingStatementSpeech
|
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Speak["This is an example of speech synthesis."] |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #Nim | Nim | import osproc
discard execCmd("espeak 'Hello world!'") |
http://rosettacode.org/wiki/Speech_synthesis | Speech synthesis | Render the text This is an example of speech synthesis as speech.
Related task
using a speech engine to highlight words
| #PARI.2FGP | PARI/GP | speak(txt,opt="")=extern(concat(["espeak ",opt," \"",txt,"\""])); |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Delphi | Delphi |
program Square_but_not_cube;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math;
begin
var count := 0;
var n := 1;
while count < 30 do
begin
var sq := n * n;
var cr := Trunc(Power(sq, 1 / 3));
if cr * cr * cr <> sq then
begin
inc(count);
writeln(sq);
end
else
... |
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
¯... | #MATLAB_.2F_Octave | MATLAB / Octave | % Initialize
N = 0; S=0; S2 = 0;
binlist = 0:.1:1;
h = zeros(1,length(binlist)); % initialize histogram
% read data and perform computation
while (1)
% read next sample x
if (no_data_available) break; end;
N = N + 1;
S = S + x;
S2= S2+ x*x;
ix= sum(x < binlist)... |
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
¯... | #MiniScript | MiniScript | Stats = {}
Stats.count = 0
Stats.sum = 0
Stats.sumOfSquares = 0
Stats.histo = null
Stats.add = function(x)
self.count = self.count + 1
self.sum = self.sum + x
self.sumOfSquares = self.sumOfSquares + x*x
bin = floor(x*10)
if not self.histo then self.histo = [0]*10
self.histo[bin] = self.histo[b... |
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... | #Rust | Rust | fn square_free(mut n: usize) -> bool {
if n & 3 == 0 {
return false;
}
let mut p: usize = 3;
while p * p <= n {
let mut count = 0;
while n % p == 0 {
count += 1;
if count > 1 {
return false;
}
n /= p;
}
... |
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... | #Scala | Scala | import spire.math.SafeLong
import spire.implicits._
import scala.annotation.tailrec
object SquareFreeNums {
def main(args: Array[String]): Unit = {
println(
s"""|1 - 145:
|${formatTable(sqrFree.takeWhile(_ <= 145).toVector, 10)}
|
|1T - 1T+145:
|${formatTable(sqrF... |
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... | #REXX | REXX | /*REXX program displays a stem and leaf plot of any non-negative numbers [can include 0]*/
parse arg @ /* [↓] Not specified? Then use default*/
if @='' then @=12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139,
131 115 105 132 104 123 35 113 122 42 117 11... |
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.
Fo... | #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
string s = @"gHHH5YY++///\";
Console.WriteLine(s.RunLengthSplit().Delimit(", "));
}
public static class Extensions
{
public static IEnumerable<string> RunLengthSplit(this string source) {
using (var enumera... |
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... | #PicoLisp | PicoLisp | (de nmbr (N)
(let (A 1 B 0)
(while (gt0 N)
(if (bit? 1 N)
(inc 'B A)
(inc 'A B) )
(setq N (>> 1 N)) )
B ) )
(let Lst (mapcar nmbr (range 1 2000))
(println 'First-15: (head 15 Lst))
(for N 10
(println 'First N 'found 'at: (index N Lst)) )
(printl... |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #C_Shell | C Shell | while 1
foreach rod ('|' '/' '-' '\')
printf ' %s\r' $rod; sleep 0.25
end
end |
http://rosettacode.org/wiki/Spinning_rod_animation/Text | Spinning rod animation/Text | Task
An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | SPINROD
; spin 10 times with quarter-second wait
for i = 1:1:10 {
for j = 1:1:4 {
set x = $case(j,1:"|",2:"/",3:"-",:"\")
; $char(8) backspaces on the terminal
write $char(8)_x
hang 0.25
}
}
quit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.