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/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Fortran | Fortran | ! Works with gfortran but needs the option
! -assume realloc_lhs
! when compiled with Intel Fortran.
program gauss
implicit none
integer, parameter :: p = 16 ! quadruple precision
integer :: n = 10, k
real(kind=p), allocatable :: r(:,:)
real(kind=p) :: z, a, b, exact
do n = 1,20
a = -3; b = 3
r = gaussquad(n)
z = (b-a)/2*dot_product(r(2,:),exp((a+b)/2+r(1,:)*(b-a)/2))
exact = exp(3.0_p)-exp(-3.0_p)
print "(i0,1x,g0,1x,g10.2)",n, z, z-exact
end do
contains
function gaussquad(n) result(r)
integer :: n
real(kind=p), parameter :: pi = 4*atan(1._p)
real(kind=p) :: r(2, n), x, f, df, dx
integer :: i, iter
real(kind = p), allocatable :: p0(:), p1(:), tmp(:)
p0 = [1._p]
p1 = [1._p, 0._p]
do k = 2, n
tmp = ((2*k-1)*[p1,0._p]-(k-1)*[0._p, 0._p,p0])/k
p0 = p1; p1 = tmp
end do
do i = 1, n
x = cos(pi*(i-0.25_p)/(n+0.5_p))
do iter = 1, 10
f = p1(1); df = 0._p
do k = 2, size(p1)
df = f + x*df
f = p1(k) + x * f
end do
dx = f / df
x = x - dx
if (abs(dx)<10*epsilon(dx)) exit
end do
r(1,i) = x
r(2,i) = 2/((1-x**2)*df**2)
end do
end function
end program
|
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Julia | Julia |
abstract type Hello end
struct HelloWorld <: Hello
name::String
HelloWorld(s) = new(s)
end
struct HelloTime <: Hello
name::String
tnew::DateTime
HelloTime(s) = new(s, now())
end
sayhello(hlo) = println("Hello to this world, $(hlo.name)!")
sayhello(hlo::HelloTime) = println("It is now $(now()). Hello from back in $(hlo.tnew), $(hlo.name)!")
h1 = HelloWorld("world")
h2 = HelloTime("new world")
sayhello(h1)
sayhello(h2)
fh = open("objects.dat", "w")
serialize(fh, h1)
serialize(fh,h2)
close(fh)
sleep(10)
fh = open("objects.dat", "r")
hh1 = deserialize(fh)
hh2 = deserialize(fh)
close(fh)
sayhello(hh1)
sayhello(hh2)
|
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Kotlin | Kotlin | // version 1.2.0
import java.io.*
open class Entity(val name: String = "Entity"): Serializable {
override fun toString() = name
companion object {
val serialVersionUID = 3504465751164822571L
}
}
class Person(name: String = "Brian"): Entity(name), Serializable {
companion object {
val serialVersionUID = -9170445713373959735L
}
}
fun main(args: Array<String>) {
val instance1 = Person()
println(instance1)
val instance2 = Entity()
println(instance2)
// serialize
try {
val out = ObjectOutputStream(FileOutputStream("objects.dat"))
out.writeObject(instance1)
out.writeObject(instance2)
out.close()
println("Serialized...")
}
catch (e: IOException) {
println("Error occurred whilst serializing")
System.exit(1)
}
// deserialize
try {
val inp = ObjectInputStream(FileInputStream("objects.dat"))
val readObject1 = inp.readObject()
val readObject2 = inp.readObject()
inp.close()
println("Deserialized...")
println(readObject1)
println(readObject2)
}
catch (e: IOException) {
println("Error occurred whilst deserializing")
System.exit(1)
}
catch (e: ClassNotFoundException) {
println("Unknown class for deserialized object")
System.exit(1)
}
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <iostream>
const char *CREATURES[] = { "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse" };
const char *COMMENTS[] = {
"I don't know why she swallowed that fly.\nPerhaps she'll die\n",
"That wiggled and jiggled and tickled inside her",
"How absurd, to swallow a bird",
"Imagine that. She swallowed a cat",
"What a hog to swallow a dog",
"She just opened her throat and swallowed that goat",
"I don't know how she swallowed that cow",
"She's dead of course"
};
int main() {
auto max = sizeof(CREATURES) / sizeof(char*);
for (size_t i = 0; i < max; ++i) {
std::cout << "There was an old lady who swallowed a " << CREATURES[i] << '\n';
std::cout << COMMENTS[i] << '\n';
for (int j = i; j > 0 && i < max - 1; --j) {
std::cout << "She swallowed the " << CREATURES[j] << " to catch the " << CREATURES[j - 1] << '\n';
if (j == 1)
std::cout << COMMENTS[j - 1] << '\n';
}
}
return 0;
} |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[units, ConvertRussianQuantities]
units = {"RussianVershoks", "RussianArshins", "RussianSazhens", "RussianVerstas", "Centimeters", "Meters", "Kilometers"};
ConvertRussianQuantities[q_Quantity] := UnitConvert[q, #] & /@ Select[units, QuantityUnit[q] != # &]
ConvertRussianQuantities[Quantity[1, "Vershoks"]]
ConvertRussianQuantities[Quantity[1, "Arshins"]] |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | П7 1 0 0 * П8 1 ВП 5 /
П9 ИП7 1 0 6 7 / П0 5 0
0 * ПC 3 * ПA 1 6 * ПB
С/П ПB 1 6 / ПA 3 / ПC 5
0 0 / П0 1 0 6 7 / БП
00 |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Lingo | Lingo | global gOpenGL -- RavOpenGL xtra instance
global GL -- OpenGL constants
on startMovie
-- Load the OpenGL script xtra
gOpenGL = xtra("RavOpenGL").new()
-- Load GL DLL
gOpenGL.RavLoadGL("", "")
-- Function omitted in demo code: loads OpenGL constants into namespace GL
loadGLConstants()
-- Window settings
w = 640
h = 480
_movie.stage.title = "Triangle"
_movie.stage.rect = rect(0, 0, w, h)
_movie.centerStage = TRUE
-- Create OpenGL display sprite
m = new(#RavOpenGLDisplay)
_movie.puppetSprite(1, TRUE)
sprite(1).rect = rect(0, 0, w, h)
sprite(1).member = m
_movie.updateStage()
-- Create the OpenGL buffer
mainBufferID = gOpenGL.RavCreateBuffer(w, h, 32, 32)
-- Set the sharing mode between script and sprite xtras
dcID = gOpenGL.RavGetBufferProp(mainBufferID, #ravGC)
sprite(1).RavShareBuffer(dcID, #true)
gOpenGL.glViewport(0, 0, w, h)
gOpenGL.glMatrixMode(GL.PROJECTION)
gOpenGL.glLoadIdentity()
gOpenGL.glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)
gOpenGL.glMatrixMode(GL.MODELVIEW)
gOpenGL.glClearColor(0.3, 0.3, 0.3, 0.0)
gOpenGL.glClear(GL.COLOR_BUFFER_BIT + GL.DEPTH_BUFFER_BIT)
gOpenGL.glShadeModel(GL.SMOOTH)
gOpenGL.glLoadIdentity()
gOpenGL.glTranslatef(-15.0, -15.0, 0.0)
gOpenGL.glBegin(GL.TRIANGLES)
gOpenGL.glColor3f(1.0, 0.0, 0.0)
gOpenGL.glVertex2f(0.0, 0.0)
gOpenGL.glColor3f(0.0, 1.0, 0.0)
gOpenGL.glVertex2f(30.0, 0.0)
gOpenGL.glColor3f(0.0, 0.0, 1.0)
gOpenGL.glVertex2f(0.0, 30.0)
gOpenGL.glEnd()
gOpenGL.glFlush()
-- Show the window
_movie.stage.visible = TRUE
end |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Lua | Lua | local gl = require "luagl"
local iup = require "iuplua"
require "iupluagl"
local function paint()
gl.ClearColor(0.3,0.3,0.3,0.0)
gl.Clear"COLOR_BUFFER_BIT,DEPTH_BUFFER_BIT"
gl.ShadeModel"SMOOTH"
gl.LoadIdentity()
gl.Translate(-15.0, -15.0, 0.0)
gl.Begin"TRIANGLES"
gl.Color(1.0, 0.0, 0.0)
gl.Vertex(0.0, 0.0)
gl.Color(0.0, 1.0, 0.0)
gl.Vertex(30.0, 0.0)
gl.Color(0.0, 0.0, 1.0)
gl.Vertex(0.0, 30.0)
gl.End()
gl.Flush()
end
local function reshape(width, height)
gl.Viewport(0, 0, width, height)
gl.MatrixMode"PROJECTION"
gl.LoadIdentity()
gl.Ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)
gl.MatrixMode"MODELVIEW"
end
local glc = iup.glcanvas{rastersize="640x480"}
function glc:action() paint() end
function glc:resize_cb(w,h) reshape(w,h) end
function glc:map_cb() iup.GLMakeCurrent(self) end
local dlg = iup.dialog{title="Triangle", shrink="yes"; glc}
dlg:show()
iup.MainLoop()
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Fortran | Fortran |
!> read lines one at a time and randomly choose one
!! using a Reservoir Sampling algorithm:
!! http://www.rosettacode.org/wiki/One_of_n_lines_in_a_file
program reservoir_sample
use, intrinsic :: iso_fortran_env, only : dp=>real64
implicit none
character(len=256) :: line
integer :: lun, n, i, count(10)
call random_seed()
!! create test file
open(file='_data.txt',newunit=lun)
do i=1,10
write(lun,'(*(g0))')'test line ',i
enddo
!! run once and show result
call one_of_n(line,n)
write(*,'(i10,":",a)')n,trim(line)
!! run 1 000 000, times on ten-line test file
count=0
do i=1,1000000
call one_of_n(line,n)
if(n.gt.0.and.n.le.10)then
count(n)=count(n)+1
else
write(*,*)'<ERROR>'
endif
enddo
write(*,*)count
write(*,*)count-100000
contains
subroutine one_of_n(line,n)
character(len=256),intent(out) :: line
integer,intent(out) :: n
real(kind=dp) :: rand_val
integer :: ios, ilines
line=''
ios=0
ilines=1
n=0
rewind(lun)
do
call random_number(rand_val)
if( rand_val < 1.0d0/(ilines) )then
read(lun,'(a)',iostat=ios)line
if(ios/=0)exit
n=ilines
else
read(lun,'(a)',iostat=ios)
if(ios/=0)exit
endif
ilines=ilines+1
enddo
end subroutine one_of_n
end program reservoir_sample
} |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #zkl | zkl | fcn disOrder(sm,sn){
M:=sm.split(" ");
N:=sn.split(" "); nc:=Walker.cycle(Utils.Helpers.listUnique(N));
dn:=Dictionary(); N.pump(Void,'wrap(w){ dn[w] = dn.find(w,0) + 1; });
M.pump(String,'wrap(w){
if (Void==(n:=dn.find(w))) return(w); // not replaced
if (n) { dn[w]=n-1; nc.next(); } // swaps left--
else { nc.next(); w } // exhausted
}, String.fp(" ") )[1,*] // remove leading blank
} |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Objective-C | Objective-C | typedef enum { kOrdNone, kOrdLex, kOrdByAddress, kOrdNumeric } SortOrder;
@interface MyArray : NSObject {}
// . . .
@end
@implementation MyArray
- (void)sort {
[self sortWithOrdering:kOrdLex onColumn:0 reversed:NO];
}
- (void)sortWithOrdering:(SortOrder)ord {
[self sortWithOrdering:ord onColumn:0 reversed:NO];
}
- (void)sortWithOrdering:(SortOrder)ord onColumn:(int)col {
[self sortWithOrdering:ord onColumn:col reversed:NO];
}
- (void)sortWithOrdering:(SortOrder)ord onColumn:(int)col reversed:(BOOL)rev {
// . . . Actual sort goes here . . .
}
@end |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Joy | Joy |
DEFINE order ==
[equal] [false]
[[[[size] dip size <=] [[<=] mapr2 true [and] fold]] [i] map i and]
ifte.
|
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #jq | jq |
[1,2,3] < [1,2,3,4] # => true
[1,2,3] < [1,2,4] # => true
[1,2,3] < [1,2,3] # => false |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #JavaScript | JavaScript | var fs = require('fs'), print = require('sys').print;
fs.readFile('./unixdict.txt', 'ascii', function (err, data) {
var is_ordered = function(word){return word.split('').sort().join('') === word;},
ordered_words = data.split('\n').filter(is_ordered).sort(function(a, b){return a.length - b.length}).reverse(),
longest = [], curr = len = ordered_words[0].length, lcv = 0;
while (curr === len){
longest.push(ordered_words[lcv]);
curr = ordered_words[++lcv].length;
};
print(longest.sort().join(', ') + '\n');
}); |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PL.2FM | PL/M | 100H:
/* CHECK EXACT PALINDROME ASSUMING $-TERMINATED STRING */
PALINDROME: PROCEDURE(PTR) BYTE;
DECLARE (PTR, FRONT, BACK) ADDRESS, STR BASED PTR BYTE;
/* FIND END */
FRONT, BACK = 0;
DO WHILE STR(BACK) <> '$';
BACK = BACK + 1;
END;
BACK = BACK - 1;
/* CHECK MATCH */
DO WHILE (FRONT < BACK) AND (STR(FRONT) = STR(BACK));
FRONT = FRONT + 1;
BACK = BACK - 1;
END;
RETURN FRONT >= BACK;
END PALINDROME;
/* CHECK INEXACT PALINDROME: FILTER OUT NON-LETTERS AND NUMBERS */
INEXACT$PALINDROME: PROCEDURE(PTR) BYTE;
/* 256 BYTES OUGHT TO BE ENOUGH FOR EVERYONE */
DECLARE (PTR, OPTR) ADDRESS;
DECLARE FILTER (256) BYTE;
DECLARE (IN BASED PTR, OUT BASED OPTR) BYTE;
OPTR = .FILTER;
DO WHILE IN <> '$';
OUT = IN OR 32;
/* LOWERCASE CHARACTERS ARE NOT IN THE PL/M CHARSET,
BUT WE CAN JUST WRITE THE ASCII VALUES AS NUMBERS */
IF (OUT >= '0' AND OUT <= '9')
OR (OUT >= 97 AND OUT <= 122) THEN
OPTR = OPTR + 1;
PTR = PTR + 1;
END;
OUT = '$';
RETURN PALINDROME(.FILTER);
END INEXACT$PALINDROME;
/* CP/M BDOS CALLS */
BDOS: PROCEDURE(FUNC, ARG);
DECLARE FUNC BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PRINT: PROCEDURE(STRING);
DECLARE STRING ADDRESS;
CALL BDOS(9, STRING);
END PRINT;
/* TEST SOME STRINGS */
DECLARE STRINGS (8) ADDRESS;
STRINGS(0) = .'ROTOR$';
STRINGS(1) = .'RACECAR$';
STRINGS(2) = .'LEVEL$';
STRINGS(3) = .'REDDER$';
STRINGS(4) = .'RACECAR$';
STRINGS(5) = .'A MAN, A PLAN, A CANAL: PANAMA$';
STRINGS(6) = .'EGAD, A BASE TONE DENOTES A BAD AGE.$';
STRINGS(7) = .'ROSETTA$';
DECLARE N BYTE;
DO N = 0 TO LAST(STRINGS);
CALL PRINT(STRINGS(N));
CALL PRINT(.': $');
IF PALINDROME(STRINGS(N)) THEN
CALL PRINT(.'EXACT$');
ELSE IF INEXACT$PALINDROME(STRINGS(N)) THEN
CALL PRINT(.'INEXACT$');
ELSE
CALL PRINT(.'NOT A PALINDROME$');
CALL PRINT(.(13,10,'$'));
END;
CALL BDOS(0,0);
EOF |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #Factor | Factor | USING: accessors arrays fry kernel locals math math.functions
multi-methods parser prettyprint prettyprint.custom sequences ;
RENAME: GENERIC: multi-methods => MM-GENERIC:
FROM: syntax => M: ;
IN: imprecise
TUPLE: imprecise
{ value float read-only }
{ sigma float read-only } ;
C: <imprecise> imprecise
: >imprecise< ( imprecise -- value sigma )
[ value>> ] [ sigma>> ] bi ;
! Define a custom syntax for imprecise numbers.
<< SYNTAX: I{ \ } [ first2 <imprecise> ] parse-literal ; >>
M: imprecise pprint-delims drop \ I{ \ } ;
M: imprecise >pprint-sequence >imprecise< 2array ;
M: imprecise pprint* pprint-object ;
<PRIVATE
! Error functions
: f+-i ( float imprecise quot -- imprecise )
[ >imprecise< ] dip dip <imprecise> ; inline
: i+-i ( imprecise1 imprecise2 quot -- imprecise )
'[ [ value>> ] bi@ @ ]
[ [ sigma>> sq ] bi@ + sqrt <imprecise> ] 2bi ; inline
: f*/i ( float imprecise quot -- imprecise )
[ >imprecise< overd ] dip [ * abs ] 2bi* <imprecise> ;
inline
:: i*/i ( a b quot -- imprecise )
a b [ >imprecise< ] bi@ :> ( vala siga valb sigb )
vala valb quot call :> val
val sq siga sq * vala sq /f sigb sq + valb sq /f sqrt :> sig
val sig <imprecise> ; inline
PRIVATE>
MM-GENERIC: ~+ ( obj1 obj2 -- imprecise ) foldable flushable
METHOD: ~+ { float imprecise } [ + ] f+-i ;
METHOD: ~+ { imprecise float } swap ~+ ;
METHOD: ~+ { imprecise imprecise } [ + ] i+-i ;
MM-GENERIC: ~- ( obj1 obj2 -- imprecise ) foldable flushable
METHOD: ~- { float imprecise } [ - ] f+-i ;
METHOD: ~- { imprecise float } swap [ swap - ] f+-i ;
METHOD: ~- { imprecise imprecise } [ - ] i+-i ;
MM-GENERIC: ~* ( obj1 obj2 -- imprecise ) foldable flushable
METHOD: ~* { float imprecise } [ * ] f*/i ;
METHOD: ~* { imprecise float } swap ~* ;
METHOD: ~* { imprecise imprecise } [ * ] i*/i ;
MM-GENERIC: ~/ ( obj1 obj2 -- imprecise ) foldable flushable
METHOD: ~/ { float imprecise } [ /f ] f*/i ;
METHOD: ~/ { imprecise float } swap [ swap /f ] f*/i ;
METHOD: ~/ { imprecise imprecise } [ /f ] i*/i ;
:: ~^ ( a x -- imprecise )
a >imprecise< :> ( vala siga )
vala x ^ >rect drop :> val
val x * siga vala /f * abs :> sig
val sig <imprecise> ; foldable flushable
<PRIVATE
: imprecise-demo ( -- )
I{ 100 1.1 } I{ 200 2.2 } ~- 2. ~^
I{ 50 1.2 } I{ 100 2.3 } ~- 2. ~^ ~+ 0.5 ~^ . ;
PRIVATE>
MAIN: imprecise-demo |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #Fortran | Fortran | PROGRAM CALCULATE !A distance, with error propagation.
REAL X1, Y1, X2, Y2 !The co-ordinates.
REAL X1E,Y1E,X2E,Y2E !Their standard deviation.
DATA X1, Y1 ,X2, Y2 /100., 50., 200.,100./ !Specified
DATA X1E,Y1E,X2E,Y2E/ 1.1, 1.2, 2.2, 2.3/ !Values.
REAL DX,DY,D2,D,DXE,DYE,E !Assistants.
CHARACTER*1 C !I'm stuck with code page 437 instead of 850.
PARAMETER (C = CHAR(241)) !Thus ± does not yield this glyph on a "console" screen. CHAR(241) does.
REAL SD !This is an arithmetic statement function.
SD(X,P,S) = P*ABS(X)**(P - 1)*S !SD for X**P where SD of X is S
WRITE (6,1) X1,C,X1E,Y1,C,Y1E, !Reveal the points
1 X2,C,X2E,Y2,C,Y2E !Though one could have used an array...
1 FORMAT ("Euclidean distance between two points:"/ !A heading.
1 ("(",F5.1,A1,F3.1,",",F5.1,A1,F3.1,")")) !Thus, One point per line.
DX = (X1 - X2) !X difference.
DXE = SQRT(X1E**2 + X2E**2) !SD for DX, a simple difference.
DY = (Y1 - Y2) !Y difference.
DYE = SQRT(Y1E**2 + Y2E**2) !SD for DY, (Y1 - Y2)
D2 = DX**2 + DY**2 !The distance, squared.
DXE = SD(DX,2,DXE) !SD for DX**2
DYE = SD(DY,2,DYE) !SD for DY**2
E = SQRT(DXE**2 + DYE**2) !SD for their sum
D = SQRT(D2) !The distance!
E = SD(D2,0.5,E) !SD after the SQRT.
WRITE (6,2) D,C,E !Ahh, the relief.
2 FORMAT ("Distance",F6.1,A1,F4.2) !Sizes to fit the example.
END !Enough. |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #F.23 | F# | open System
open System.Text.RegularExpressions
let mutable Inp = Console.In
let Out c = printf "%c" c; (if c = '.' then Environment.Exit 0)
let In() = Inp.Read() |> Convert.ToChar
let (|WordCharacter|OtherCharacter|) c =
if Regex.IsMatch(c.ToString(),"[a-zA-Z]") then
WordCharacter
else
OtherCharacter
let rec forward () =
let c = In()
let rec backward () : char =
let c = In()
match c with
| WordCharacter ->
let s = backward() in Out c; s
| OtherCharacter -> c
Out c
match c with
| WordCharacter -> forward()
| OtherCharacter -> backward()
[<EntryPoint>]
let main argv =
if argv.Length > 0 then Inp <- new System.IO.StringReader(argv.[0])
let rec loop () = forward() |> Out; loop()
loop()
0 |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Ada | Ada |
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Numerics.Discrete_Random;
procedure NumberReverse is
subtype RandRange is Integer range 1..9;
type NumArrayType is array (Integer range 1..9) of Integer;
package RandNumbers is new Ada.Numerics.Discrete_Random(RandRange);
use RandNumbers;
G : Generator;
procedure FillArray (A : in out NumArrayType) is
Temp : RandRange;
begin
A := (others => 0);
for I in 1..9 loop
Temp := Random(G);
while A(Temp) /= 0 loop
Temp := Random(G);
end loop;
A(Temp) := I;
end loop;
end FillArray;
procedure Put(A : in NumArrayType) is
begin
for I in 1..9 loop
Put(A(I), 0);
Put(" ");
end loop;
end Put;
procedure Prompt (Index : out Integer) is
begin
New_Line;
Put("How many numbers would you like to reverse: ");
Get(Index);
end Prompt;
procedure ReverseArray(Arr : in out NumArrayType;
Index : in Integer) is
Temp : RandRange;
begin
for I in 1..Index/2 loop
Temp := Arr(I);
Arr(I) := Arr(Index + 1 - I);
Arr(Index + 1 - I) := Temp;
end loop;
end ReverseArray;
Sorted : constant NumArrayType := (1,2,3,4,5,6,7,8,9);
Arr : NumArrayType;
Index : Integer;
Count : Integer := 0;
begin
Reset(G);
loop
FillArray(Arr);
exit when Sorted /= Arr;
end loop;
loop
Put(Arr);
Prompt(Index);
Count := Count + 1;
ReverseArray(Arr, Index);
exit when Sorted = Arr;
end loop;
Put(Arr);
New_Line;
Put("Congratulations! You win. It took " &
Integer'Image(Count) & " tries.");
end NumberReverse;
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Action.21 | Action! | TYPE Object=[
BYTE byteData
INT intData
CARD cardData]
PROC IsNull(Object POINTER ptr)
IF ptr=0 THEN
PrintE("Object is null")
ELSE
PrintE("Object is not null")
FI
RETURN
PROC Main()
Object a
Object POINTER ptr1=a,ptr2=0
IsNull(ptr1)
IsNull(ptr2)
RETURN |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #ActionScript | ActionScript | if (object == null)
trace("object is null"); |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
::THE MAIN THING
call :one-dca __###__##_#_##_###__######_###_#####_#__##_____#_#_#######__
pause>nul
exit /b
::/THE MAIN THING
::THE PROCESSOR
:one-dca
echo.&set numchars=0&set proc=%1
::COUNT THE NUMBER OF CHARS
set bef=%proc:_=_,%
set bef=%bef:#=#,%
set bef=%bef:~0,-1%
for %%x in (%bef%) do set /a numchars+=1
set /a endchar=%numchars%-1
:nextgen
echo. ^| %proc% ^|
set currnum=0
set newgen=
:editeachchar
set neigh=0
set /a testnum2=%currnum%+1
set /a testnum1=%currnum%-1
if %currnum%==%endchar% (
set testchar=!proc:~%testnum1%,1!
if !testchar!==# (set neigh=1)
) else (
if %currnum%==0 (
set testchar=%proc:~1,1%
if !testchar!==# (set neigh=1)
) else (
set testchar1=!proc:~%testnum1%,1!
set testchar2=!proc:~%testnum2%,1!
if !testchar1!==# (set /a neigh+=1)
if !testchar2!==# (set /a neigh+=1)
)
)
if %neigh%==0 (set newgen=%newgen%_)
if %neigh%==1 (
set testchar=!proc:~%currnum%,1!
set newgen=%newgen%!testchar!
)
if %neigh%==2 (
set testchar=!proc:~%currnum%,1!
if !testchar!==# (set newgen=%newgen%_) else (set newgen=%newgen%#)
)
if %currnum%==%endchar% (goto :cond) else (set /a currnum+=1&goto :editeachchar)
:cond
if %proc%==%newgen% (echo.&echo ...The sample is now stable.&goto :EOF)
set proc=%newgen%
goto :nextgen
::/THE (LLLLLLOOOOOOOOOOOOONNNNNNNNGGGGGG.....) PROCESSOR |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #BASIC | BASIC | FUNCTION leftRect(a, b, n)
h = (b - a) / n
sum = 0
FOR x = a TO b - h STEP h
sum = sum + h * (f(x))
NEXT x
leftRect = sum
END FUNCTION
FUNCTION rightRect(a, b, n)
h = (b - a) / n
sum = 0
FOR x = a + h TO b STEP h
sum = sum + h * (f(x))
NEXT x
rightRect = sum
END FUNCTION
FUNCTION midRect(a, b, n)
h = (b - a) / n
sum = 0
FOR x = a + h / 2 TO b - h / 2 STEP h
sum = sum + h * (f(x))
NEXT x
midRect = sum
END FUNCTION
FUNCTION trap(a, b, n)
h = (b - a) / n
sum = f(a) + f(b)
FOR i = 1 TO n-1
sum = sum + 2 * f((a + i * h))
NEXT i
trap = h / 2 * sum
END FUNCTION
FUNCTION simpson(a, b, n)
h = (b - a) / n
sum1 = 0
sum2 = 0
FOR i = 0 TO n-1
sum1 = sum1 + f(a + h * i + h / 2)
NEXT i
FOR i = 1 TO n - 1
sum2 = sum2 + f(a + h * i)
NEXT i
simpson = h / 6 * (f(a) + f(b) + 4 * sum1 + 2 * sum2)
END FUNCTION |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Cowgol | Cowgol | include "cowgol.coh";
# return the change in height of a number
sub height(n: uint32): (h: int8) is
h := 0;
var dgt := (n % 10) as uint8;
var prev: uint8;
n := n / 10;
while n > 0 loop
prev := dgt;
dgt := (n % 10) as uint8;
n := n / 10;
if prev < dgt then
h := h + 1;
elseif prev > dgt then
h := h - 1;
end if;
end loop;
end sub;
var number: uint32 := 0;
var seen: uint32 := 0;
var col: uint8 := 10;
print("The first 200 numbers are:");
print_nl();
while seen < 10000000 loop
loop
number := number + 1;
if height(number) == 0 then break; end if;
end loop;
seen := seen + 1;
if seen <= 200 then
print_i32(number);
col := col - 1;
if col != 0 then
print_char('\t');
else
print_char('\n');
col := 10;
end if;
end if;
end loop;
print_nl();
print("The 10,000,000th number is: ");
print_i32(number);
print_nl(); |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #F.23 | F# |
// A296712. Nigel Galloway: October 9th., 2020
let fN g=let rec fN Ψ n g=match n,Ψ with (0,0)->true |(0,_)->false |_->let i=n%10 in fN (Ψ + (compare i g)) (n/10) i in fN 0 g (g%10)
let A296712=seq{1..2147483647}|>Seq.filter fN
A296712|>Seq.take 200|>Seq.iter(printf "%d "); printfn"\n"
[999999;9999999;99999999]|>List.iter(fun n->printfn "The %dth element is %d" (n+1) (Seq.item n A296712))
|
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Factor | Factor | USING: grouping io kernel lists lists.lazy math math.extras
prettyprint tools.memory.private ;
: rises-and-falls-equal? ( n -- ? )
0 swap 10 /mod swap
[ 10 /mod rot over - sgn rotd + spin ] until-zero drop 0 = ;
: OEIS:A296712 ( -- list )
1 lfrom [ rises-and-falls-equal? ] lfilter ;
! Task
"The first 200 numbers in OEIS:A296712 are:" print
200 OEIS:A296712 ltake list>array 20 group simple-table. nl
"The 10 millionth number in OEIS:A296712 is " write
9,999,999 OEIS:A296712 lnth commas print |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Go | Go | package main
import (
"fmt"
"math"
)
// cFunc for continuous function. A type definition for convenience.
type cFunc func(float64) float64
func main() {
fmt.Println("integral:", glq(math.Exp, -3, 3, 5))
}
// glq integrates f from a to b by Guass-Legendre quadrature using n nodes.
// For the task, it also shows the intermediate values determining the nodes:
// the n roots of the order n Legendre polynomal and the corresponding n
// weights used for the integration.
func glq(f cFunc, a, b float64, n int) float64 {
x, w := glqNodes(n, f)
show := func(label string, vs []float64) {
fmt.Printf("%8s: ", label)
for _, v := range vs {
fmt.Printf("%8.5f ", v)
}
fmt.Println()
}
show("nodes", x)
show("weights", w)
var sum float64
bma2 := (b - a) * .5
bpa2 := (b + a) * .5
for i, xi := range x {
sum += w[i] * f(bma2*xi+bpa2)
}
return bma2 * sum
}
// glqNodes computes both nodes and weights for a Gauss-Legendre
// Quadrature integration. Parameters are n, the number of nodes
// to compute and f, a continuous function to integrate. Return
// values have len n.
func glqNodes(n int, f cFunc) (node []float64, weight []float64) {
p := legendrePoly(n)
pn := p[n]
n64 := float64(n)
dn := func(x float64) float64 {
return (x*pn(x) - p[n-1](x)) * n64 / (x*x - 1)
}
node = make([]float64, n)
for i := range node {
x0 := math.Cos(math.Pi * (float64(i+1) - .25) / (n64 + .5))
node[i] = newtonRaphson(pn, dn, x0)
}
weight = make([]float64, n)
for i, x := range node {
dnx := dn(x)
weight[i] = 2 / ((1 - x*x) * dnx * dnx)
}
return
}
// legendrePoly constructs functions that implement Lengendre polynomials.
// This is done by function composition by recurrence relation (Bonnet's.)
// For given n, n+1 functions are returned, computing P0 through Pn.
func legendrePoly(n int) []cFunc {
r := make([]cFunc, n+1)
r[0] = func(float64) float64 { return 1 }
r[1] = func(x float64) float64 { return x }
for i := 2; i <= n; i++ {
i2m1 := float64(i*2 - 1)
im1 := float64(i - 1)
rm1 := r[i-1]
rm2 := r[i-2]
invi := 1 / float64(i)
r[i] = func(x float64) float64 {
return (i2m1*x*rm1(x) - im1*rm2(x)) * invi
}
}
return r
}
// newtonRaphson is general purpose, although totally primitive, simply
// panicking after a fixed number of iterations without convergence to
// a fixed error. Parameter f must be a continuous function,
// df its derivative, x0 an initial guess.
func newtonRaphson(f, df cFunc, x0 float64) float64 {
for i := 0; i < 30; i++ {
x1 := x0 - f(x0)/df(x0)
if math.Abs(x1-x0) <= math.Abs(x0*1e-15) {
return x1
}
x0 = x1
}
panic("no convergence")
} |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Neko | Neko | /* Object serialization, in Neko */
var file_open = $loader.loadprim("std@file_open", 2)
var file_write = $loader.loadprim("std@file_write", 4)
var file_read = $loader.loadprim("std@file_read", 4)
var file_close = $loader.loadprim("std@file_close", 1)
var serialize = $loader.loadprim("std@serialize", 1)
var unserialize = $loader.loadprim("std@unserialize", 2)
/* Inheritance by prototype */
proto = $new(null)
proto.print = function () { $print(this, "\n") }
obj = $new(null)
obj.msg = "Hello"
obj.dest = $array("Town", "Country", "World")
$objsetproto(obj, proto)
$print("Original:\n")
obj.print()
/* Serialize the object */
var thing = serialize(obj)
var len = $ssize(thing)
/* To disk */
var f = file_open("object-serialization.bin", "w")
file_write(f, thing, 0, len)
file_close(f)
/* Load the binary data into a new string space */
f = file_open("object-serialization.bin", "r")
var buff = $smake(len)
file_read(f, buff, 0, len)
file_close(f)
/* Unserialize the object into a new variable */
var other = unserialize(buff, $loader)
$print("deserialized:\n")
other.print() |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Nim | Nim | import marshal, streams
type
Base = object of RootObj
name: string
Descendant = object of Base
proc newBase(): Base = Base(name: "base")
proc newDescendant(): Descendant = Descendant(name: "descend")
proc print(obj: Base) =
echo(obj.name)
var
base = newBase()
descendant = newDescendant()
print(base)
print(descendant)
var strm = newFileStream("objects.dat", fmWrite)
store(strm, (base, descendant))
strm.close()
var t: (Base, Descendant)
load(newFileStream("objects.dat", fmRead), t)
print(t[0])
print(t[1])
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #CLU | CLU | old_lady = cluster is swallow
rep = null
own animals: array[string] := array[string]$[
"fly", "spider", "bird", "cat",
"dog", "goat", "cow", "horse"
]
own lines: array[string] := array[string]$[
"I don't know why she swallowed that fly.\nPerhaps she'll die.\n",
"That wiggled and jiggled and tickled inside her",
"How absurd to swallow a bird",
"Imagine that, she swallowed a cat!",
"What a hog to swallow a dog",
"She just opened her throat and swallowed that goat",
"I don't know how she swallowed that cow",
"She's dead, of course."
]
verse = proc (s: stream, n: int)
stream$putl(s, "There was an old lady who swallowed a " || animals[n])
stream$putl(s, lines[n])
if n=8 then return end
for i: int in int$from_to_by(n, 2, -1) do
stream$putl(s, "She swallowed the " || animals[i]
|| " to catch the " || animals[i-1])
if i <= 3 then stream$putl(s, lines[i-1]) end
end
end verse
swallow = proc (s: stream)
for i: int in int$from_to(1, 8) do
verse(s, i)
end
end swallow
end old_lady
start_up = proc ()
old_lady$swallow(stream$primary_output())
end start_up |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. OLD-LADY.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 LYRICS.
03 THERE-WAS PIC X(38) VALUE
"There was an old lady who swallowed a ".
03 SHE-SWALLOWED PIC X(18) VALUE "She swallowed the ".
03 TO-CATCH PIC X(14) VALUE " to catch the ".
01 ANIMALS.
03 FLY.
05 NAME PIC X(6) VALUE "fly".
05 VERSE PIC X(60) VALUE
"I don't know why she swallowed a fly. Perhaps she'll die.".
03 SPIDER.
05 NAME PIC X(6) VALUE "spider".
05 VERSE PIC X(60) VALUE
"That wiggled and jiggled and tickled inside her.".
03 BIRD.
05 NAME PIC X(6) VALUE "bird".
05 VERSE PIC X(60) VALUE
"How absurd, to swallow a bird.".
03 CAT.
05 NAME PIC X(6) VALUE "cat".
05 VERSE PIC X(60) VALUE
"Imagine that, she swallowed a cat.".
03 DOG.
05 NAME PIC X(6) VALUE "dog".
05 VERSE PIC X(60) VALUE
"What a hog, to swallow a dog.".
03 GOAT.
05 NAME PIC X(6) VALUE "goat".
05 VERSE PIC X(60) VALUE
"She just opened her throat and swallowed that goat.".
03 COW.
05 NAME PIC X(6) VALUE "cow".
05 VERSE PIC X(60) VALUE
"I don't know how she swallowed that cow.".
03 HORSE.
05 NAME PIC X(6) VALUE "horse".
05 VERSE PIC X(60) VALUE
"She's dead, of course.".
01 ANIMAL-ARRAY REDEFINES ANIMALS.
03 ANIMAL OCCURS 8 TIMES.
05 NAME PIC X(6).
05 VERSE PIC X(60).
01 MISC.
03 LINE-OUT PIC X(80).
03 A-IDX PIC 9(2).
03 S-IDX PIC 9(2).
PROCEDURE DIVISION.
MAIN SECTION.
PERFORM DO-ANIMAL
VARYING A-IDX FROM 1 BY 1 UNTIL A-IDX > 8.
STOP RUN.
DO-ANIMAL SECTION.
MOVE SPACES TO LINE-OUT.
STRING
THERE-WAS DELIMITED BY SIZE,
NAME OF ANIMAL(A-IDX) DELIMITED BY SPACE,
","
INTO LINE-OUT
END-STRING.
DISPLAY LINE-OUT.
IF A-IDX > 1 THEN
DISPLAY VERSE OF ANIMAL(A-IDX)
END-IF.
IF A-IDX = 8 THEN
EXIT SECTION
END-IF.
PERFORM DO-SWALLOW
VARYING S-IDX FROM A-IDX BY -1 UNTIL S-IDX = 1.
DISPLAY VERSE OF ANIMAL(1).
DISPLAY SPACES.
DO-SWALLOW SECTION.
MOVE SPACES TO LINE-OUT.
STRING
SHE-SWALLOWED DELIMITED BY SIZE,
NAME OF ANIMAL(S-IDX) DELIMITED BY SPACE,
TO-CATCH DELIMITED BY SIZE,
NAME OF ANIMAL(S-IDX - 1) DELIMITED BY SPACE
INTO LINE-OUT
END-STRING.
DISPLAY LINE-OUT.
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Nim | Nim | import os, strutils, sequtils, tables
const Unit2Mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254,
"fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254,
"meter": 1.0, "milia": 7467.6, "piad": 0.1778,
"sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,
"versta": 1066.8}.toOrderedTable
if paramCount() != 2:
raise newException(ValueError, "need two arguments: number then units.")
let value = try: parseFloat(paramStr(1))
except ValueError:
raise newException(ValueError, "first argument must be a (float) number.")
let unit = paramStr(2)
if unit notin Unit2Mult:
raise newException(ValueError,
"only know the following units: " & toSeq(Unit2Mult.keys).join(" "))
echo value, ' ', unit, " to:"
for (key, mult) in Unit2Mult.pairs:
echo key.align(10), ": ", formatFloat(value * Unit2Mult[unit] / mult, ffDecimal, 5) |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Perl | Perl | sub convert {
my($magnitude, $unit) = @_;
my %factor = (
tochka => 0.000254,
liniya => 0.00254,
diuym => 0.0254,
vershok => 0.04445,
piad => 0.1778,
fut => 0.3048,
arshin => 0.7112,
sazhen => 2.1336,
versta => 1066.8,
milia => 7467.6,
centimeter => 0.01,
meter => 1.0,
kilometer => 1000.0,
);
my $base= $magnitude * $factor{$unit};
my $result .= "$magnitude $unit to:\n";
for (sort { $factor{$a} <=> $factor{$b} } keys %factor) {
$result .= sprintf "%10s: %s\n", $_, sigdig($base / $factor{$_}, 5) unless $_ eq $unit
}
return $result;
}
sub sigdig {
my($num,$sig) = @_;
return $num unless $num =~ /\./;
$num =~ /([1-9]\d*\.?\d*)/;
my $prefix = $`;
my $match = $&;
$sig++ if $match =~ /\./;
my $digits = substr $match, 0, $sig;
my $nextd = substr $match, $sig, 1;
$digits =~ s/(.)$/{1+$1}/e if $nextd > 5;
return $prefix . $digits;
}
print convert(1,'meter'), "\n\n";
print convert(1,'milia'), "\n"; |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Style[Graphics3D[{Polygon[{{-1, 0, 0}, {1, 0, 0}, {0, Sqrt[3], 0.5}},
VertexColors -> {Red, Green, Blue}]}, Boxed -> False],
RenderingOptions -> {"3DRenderingEngine" -> "OpenGL"}] |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #MAXScript | MAXScript | newMesh = mesh numVerts:3 numFaces:1
setMesh newMesh vertices:#([-100, -100, 0], [100, -100, 0], [-100, 100, 0]) faces:#([1, 2, 3])
defaultVCFaces newMesh
setVertColor newMesh 1 red
setVertColor newMesh 2 green
setVertColor newMesh 3 blue
setCVertMode newMesh true
update newMesh
viewport.setType #view_top
max tool maximize
viewport.SetRenderLevel #smoothhighlights |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #FreeBASIC | FreeBASIC | Declare Function one_of_n (n As Long) As Long
Dim As Long L0, c, elegido(1 To 10)
Function one_of_n (n As Long) As Long
'asume que la primera línea es 1
Dim As Long L1, opcion
For L1 = 1 To n
If Int(Rnd * L1) = 0 Then opcion = L1
Next L1
one_of_n = opcion
End Function
Randomize Timer
For L0 = 1 To 1000000
c = one_of_n(10)
elegido(c) += 1
Next L0
For L0 = 1 To 10
Print Using "##. #######"; L0; elegido(L0)
Next L0
Sleep |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #OCaml | OCaml | let sort_table ?(ordering = compare) ?(column = 0) ?(reverse = false) table =
let cmp x y = ordering (List.nth x column) (List.nth y column) * (if reverse then -1 else 1) in
List.sort cmp table |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Julia | Julia | function islexless(a::AbstractArray{<:Real}, b::AbstractArray{<:Real})
for (x, y) in zip(a, b)
if x == y continue end
return x < y
end
return length(a) < length(b)
end
using Primes, Combinatorics
tests = [[1, 2, 3], primes(10), 0:2:6, [-Inf, 0.0, Inf], [π, e, φ, catalan], [2015, 5], [-sqrt(50.0), 50.0 ^ 2]]
println("List not sorted:\n - ", join(tests, "\n - "))
sort!(tests; lt=islexless)
println("List sorted:\n - ", join(tests, "\n - ")) |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
( 1 2 3 ) ( 1 2 3 4 ) less ?
( 1 2 3 4 ) ( 1 2 3 ) less ?
( 1 2 4 ) ( 1 2 3 ) less ?
( 1 2 3 ) ( 1 2 3 ) less ?
( 1 2 3 ) ( 1 2 4 ) less ?
"End " input |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq | def is_sorted:
if length <= 1 then true
else .[0] <= .[1] and (.[1:] | is_sorted)
end;
def longest_ordered_words:
# avoid string manipulation:
def is_ordered: explode | is_sorted;
map(select(is_ordered))
| (map(length)|max) as $max
| map( select(length == $max) );
split("\n") | longest_ordered_words |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Plain_English | Plain English | To decide if a string is palindromic:
Slap a substring on the string.
Loop.
If the substring's first is greater than the substring's last, say yes.
If the substring's first's target is not the substring's last's target, say no.
Add 1 to the substring's first.
Subtract 1 from the substring's last.
Repeat. |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #FreeBASIC | FreeBASIC | '----------------------
' definition of a "measurement" type with value and uncartainty
' and operators that can operate on them
'---------------------
#macro p2(x)
(x)*(x)
#endmacro
type meas
vlu as double
unc as double
end type
operator + ( a as meas, b as meas ) as meas
dim ret as meas
ret.vlu = a.vlu + b.vlu
ret.unc = sqr( a.unc*a.unc + b.unc*b.unc )
return ret
end operator
operator + ( c as double, a as meas ) as meas
dim ret as meas
ret.vlu = a.vlu + c
ret.unc = a.unc
return ret
end operator
operator + ( a as meas, c as double ) as meas
return c+a
end operator
operator - ( a as meas, b as meas ) as meas
dim ret as meas
ret.vlu = a.vlu - b.vlu
ret.unc = sqr( a.unc*a.unc + b.unc*b.unc )
return ret
end operator
operator - ( c as double, a as meas ) as meas
dim ret as meas
ret.vlu = a.vlu - c
ret.unc = a.unc
return ret
end operator
operator - ( a as meas, c as double ) as meas
dim ret as meas
ret.vlu = c - a.vlu
ret.unc = a.unc
return ret
end operator
operator * ( a as meas, b as meas ) as meas
dim ret as meas
ret.vlu = a.vlu*b.vlu
ret.unc = sqr(p2(ret.vlu) * (p2(a.unc/a.vlu)+p2(b.unc/b.vlu)))
return ret
end operator
operator * ( c as double, a as meas ) as meas
dim ret as meas
ret.vlu = a.vlu*c
ret.unc = abs(c*a.unc)
return ret
end operator
operator * ( a as meas, c as double ) as meas
return c*a
end operator
operator ^ ( a as meas, c as double ) as meas
dim ret as meas
ret.vlu = a.vlu ^ c
ret.unc = abs(ret.vlu*c*a.unc/a.vlu)
return ret
end operator
operator / ( c as double, a as meas ) as meas
return c*a^(-1)
end operator
operator / ( a as meas, c as double ) as meas
return a*(1.0/c)
end operator
operator / ( a as meas, b as meas ) as meas
return b*a^(-1)
end operator
sub printm( a as meas )
print using "####.##### +- ####.####"; a.vlu; a.unc
end sub
'--------------------------------
' now the results
'--------------------------------
dim as meas x1, y1, x2, y2
x1.vlu = 100.
x1.unc = 1.1
y1.vlu = 50.
y1.unc = 1.2
x2.vlu = 200.
x2.unc = 2.2
y2.vlu = 100.
y2.unc = 2.3
printm( ((x1-x2)^2 + (y1-y2)^2)^0.5 ) |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Factor | Factor | USING: continuations kernel io io.streams.string locals unicode.categories ;
IN: rosetta.odd-word
<PRIVATE
! Save current continuation.
: savecc ( -- continuation/f )
[ ] callcc1 ; inline
! Jump back to continuation, where savecc will return f.
: jump-back ( continuation -- )
f swap continue-with ; inline
PRIVATE>
:: read-odd-word ( -- )
f :> first-continuation!
f :> last-continuation!
f :> reverse!
! Read characters. Loop until end of stream.
[ read1 dup ] [
dup Letter? [
! This character is a letter.
reverse [
! Odd word: Write letters in reverse order.
last-continuation savecc dup [
last-continuation!
2drop ! Drop letter and previous continuation.
] [
! After jump: print letters in reverse.
drop ! Drop f.
swap write1 ! Write letter.
jump-back ! Follow chain of continuations.
] if
] [
! Even word: Write letters immediately.
write1
] if
] [
! This character is punctuation.
reverse [
! End odd word. Fix trampoline, follow chain of continuations
! (to print letters in reverse), then bounce off trampoline.
savecc dup [
first-continuation!
last-continuation jump-back
] [ drop ] if
write1 ! Write punctuation.
f reverse! ! Begin even word.
] [
write1 ! Write punctuation.
t reverse! ! Begin odd word.
! Create trampoline to bounce to (future) first-continuation.
savecc dup [
last-continuation!
] [ drop first-continuation jump-back ] if
] if
] if
] while
! Drop f from read1. Then print a cosmetic newline.
drop nl ;
: odd-word ( string -- )
[ read-odd-word ] with-string-reader ; |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #FALSE | FALSE | [$$$$'.=\',=|\';=|\':=|~[^s;!\,]?]s: {recursive reading}
[s;!$'.=~[,^f;!]?]r: {reverse words}
[[$$$$'.=\',=|\';=|\':=|~][,^]#$'.=~[,^r;!]?]f: {forward words}
^f;!, {start} |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #APL | APL | ∇numrev;list;in;swaps
list←{9?9}⍣{⍺≢⍳9}⊢⍬
swaps←0
read:
swaps+←1
in←{⍞←⍵⋄(≢⍵)↓⍞}(⍕list),': swap how many? '
list←⌽@(⍳⍎in)⊢list
→(list≢⍳9)/read
⎕←(⍕list),': Congratulations!'
⎕←'Swaps:',swaps
∇ |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #Ada | Ada | with Ada.Text_Io;
if Object = null then
Ada.Text_Io.Put_line("object is null");
end if; |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #ALGOL_68 | ALGOL 68 | REF STRING no result = NIL;
STRING result := "";
IF no result :=: NIL THEN print(("no result :=: NIL", new line)) FI;
IF result :/=: NIL THEN print(("result :/=: NIL", new line)) FI;
IF no result IS NIL THEN print(("no result IS NIL", new line)) FI;
IF result ISNT NIL THEN print(("result ISNT NIL", new line)) FI;
COMMENT using the UNESCO/IFIP/WG2.1 ALGOL 68 character set
result := °;
IF REF STRING(result) :≠: ° THEN print(("result ≠ °", new line)) FI;
END COMMENT
# Note the following gotcha: #
REF STRING var := NIL;
IF var ISNT NIL THEN print(("The address of var ISNT NIL",new line)) FI;
IF var IS REF STRING(NIL) THEN print(("The address of var IS REF STRING(NIL)",new line)) FI |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #BBC_BASIC | BBC BASIC | DIM rule$(7)
rule$() = "0", "0", "0", "1", "0", "1", "1", "0"
now$ = "01110110101010100100"
FOR generation% = 0 TO 9
PRINT "Generation " ; generation% ":", now$
next$ = ""
FOR cell% = 1 TO LEN(now$)
next$ += rule$(EVAL("%"+MID$("0"+now$+"0", cell%, 3)))
NEXT cell%
SWAP now$, next$
NEXT generation% |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #BBC_BASIC | BBC BASIC | *FLOAT64
@% = 12 : REM Column width
PRINT "Function Range L-Rect R-Rect M-Rect Trapeze Simpson"
FOR func% = 1 TO 4
READ x$, l, h, s%
PRINT x$, ; l " - " ; h, FNlrect(x$, l, h, s%) FNrrect(x$, l, h, s%) ;
PRINT FNmrect(x$, l, h, s%) FNtrapeze(x$, l, h, s%) FNsimpson(x$, l, h, s%)
NEXT
END
DATA "x^3", 0, 1, 100
DATA "1/x", 1, 100, 1000
DATA "x", 0, 5000, 5000000
DATA "x", 0, 6000, 6000000
DEF FNlrect(x$, a, b, n%)
LOCAL i%, d, s, x
d = (b - a) / n%
x = a
FOR i% = 1 TO n%
s += d * EVAL(x$)
x += d
NEXT
= s
DEF FNrrect(x$, a, b, n%)
LOCAL i%, d, s, x
d = (b - a) / n%
x = a
FOR i% = 1 TO n%
x += d
s += d * EVAL(x$)
NEXT
= s
DEF FNmrect(x$, a, b, n%)
LOCAL i%, d, s, x
d = (b - a) / n%
x = a
FOR i% = 1 TO n%
x += d/2
s += d * EVAL(x$)
x += d/2
NEXT
= s
DEF FNtrapeze(x$, a, b, n%)
LOCAL i%, d, f, s, x
d = (b - a) / n%
x = b : f = EVAL(x$)
x = a : s = d * (f + EVAL(x$)) / 2
FOR i% = 1 TO n%-1
x += d
s += d * EVAL(x$)
NEXT
= s
DEF FNsimpson(x$, a, b, n%)
LOCAL i%, d, f, s1, s2, x
d = (b - a) / n%
x = b : f = EVAL(x$)
x = a + d/2 : s1 = EVAL(x$)
FOR i% = 1 TO n%-1
x += d/2
s2 += EVAL(x$)
x += d/2
s1 += EVAL(x$)
NEXT
x = a
= (d / 6) * (f + EVAL(x$) + 4 * s1 + 2 * s2) |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Forth | Forth | : in-seq? ( n -- is N in the sequence? )
0 swap \ height
10 /mod \ digit and rest of number
begin dup while \ as long as the number isn't zero...
10 /mod \ get next digit and quotient
-rot swap \ retrieve previous digit
over - sgn \ see if higher, lower or equal (-1, 0, 1)
>r rot r> + \ add to height
-rot swap \ quotient on top of stack
repeat
drop drop \ drop number and last digit
0= \ is height equal to zero?
;
: next-val ( n -- n: retrieve first element of sequence higher than N )
begin 1+ dup in-seq? until
;
: two-hundred
begin over 200 < while
next-val dup .
swap 1+ swap
repeat
;
: ten-million
begin over 10000000 < while
next-val
swap 1+ swap
repeat
;
0 0 \ top of stack: current index and number
." The first 200 numbers are: " two-hundred cr cr
." The 10,000,000th number is: " ten-million . cr
bye |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Fortran | Fortran | PROGRAM A296712
INTEGER IDX, NUM, I
* Index and number start out at zero
IDX = 0
NUM = 0
* Find and write the first 200 numbers
WRITE (*,'(A)') 'The first 200 numbers are: '
DO 100 I = 1, 200
CALL NEXT NUM(IDX, NUM)
WRITE (*,'(I4)',ADVANCE='NO') NUM
IF (MOD(I,20).EQ.0) WRITE (*,*)
100 CONTINUE
* Find the 10,000,000th number
WRITE (*,*)
WRITE (*,'(A)',ADVANCE='NO') 'The 10,000,000th number is: '
200 CALL NEXT NUM(IDX, NUM)
IF (IDX.NE.10000000) GOTO 200
WRITE (*,'(I8)') NUM
STOP
END
* Given index and current number, retrieve the next number
* in the sequence.
SUBROUTINE NEXT NUM(IDX, NUM)
INTEGER IDX, NUM
LOGICAL IN SEQ
100 NUM = NUM + 1
IF (.NOT. IN SEQ(NUM)) GOTO 100
IDX = IDX + 1
END
* See whether N is in the sequence
LOGICAL FUNCTION IN SEQ(N)
INTEGER N, DL, DR, VAL, HEIGHT
* Get first digit and divide value by 10
DL = MOD(N, 10)
VAL = N / 10
HEIGHT = 0
100 IF (VAL.NE.0) THEN
* Retrieve digits by modulo and division
DR = DL
DL = MOD(VAL, 10)
VAL = VAL / 10
* Record rise or fall
IF (DL.LT.DR) HEIGHT = HEIGHT + 1
IF (DL.GT.DR) HEIGHT = HEIGHT - 1
GOTO 100
END IF
* N is in the sequence if the final height is 0
IN SEQ = HEIGHT.EQ.0
RETURN
END |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Haskell | Haskell | gaussLegendre n f a b = d*sum [ w x*f(m + d*x) | x <- roots ]
where d = (b - a)/2
m = (b + a)/2
w x = 2/(1-x^2)/(legendreP' n x)^2
roots = map (findRoot (legendreP n) (legendreP' n) . x0) [1..n]
x0 i = cos (pi*(i-1/4)/(n+1/2)) |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Objeck | Objeck |
bundle Default {
class Thingy {
@id : Int;
New(id : Int) {
@id := id;
}
method : public : Print() ~ Nil {
@id->PrintLine();
}
}
class Person from Thingy {
@name : String;
New(id : Int, name : String) {
Parent(id);
@name := name;
}
method : public : Print() ~ Nil {
@id->PrintLine();
@name->PrintLine();
}
}
class Serial {
function : Main(args : String[]) ~ Nil {
t := Thingy->New(7);
p := Person->New(13, "Bush");
s := IO.Serializer->New();
s->Write(t->As(Base));
s->Write(p->As(Base));
writer := IO.FileWriter->New("objects.dat");
writer->WriteBuffer(s->Serialize());
writer->Close();
buffer := IO.FileReader->ReadBinaryFile("objects.dat");
d := IO.Deserializer->New(buffer);
t2 := d->ReadObject()->As(Thingy);
t2->Print();
p2 := d->ReadObject()->As(Person);
p2->Print();
}
}
}
|
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Commodore_BASIC | Commodore BASIC |
1 rem rosetta code
2 rem old lady who swallowed a fly
5 print chr$(147);chr$(14)
10 dim a$(10),ex$(10),mu$(8,3):a=1
15 for i=1 to 8:read a$(i),ex$(i):next i
20 for c=1 to 8
30 print chr$(147):print " Old Lady Who Swallowed A Fly ":print
40 print "I know an old lady who swallowed"
45 print " a ";a$(c):gosub 200
50 for bc=c to 1 step -1
55 if bc=c or bc<=2 then print ex$(bc):gosub 200
57 if bc=8 then for t=1 to 1500:next
60 if bc>1 then print "She swallowed a "a$(bc)" to catch the "a$(bc-1)";"
61 gosub 200
65 next bc
70 print " ... Perhaps she'll die!"
75 get k$:if k$="q" then end
77 if k$>"0" and k$<"9" then c=asc(k$)-49
80 print:for t=1 to 1000:next t
90 next c
100 end
200 for t=1 to 500:next t:return:rem generic delay
1000 rem lyrics
1010 data "fly","I don't know why she swallowed a fly..."
1020 data "spider","That wriggled and jiggled and tickled inside her!"
1030 data "bird","How absurd to swallow a bird!"
1040 data "cat","Imagine that! She swallowed a cat!"
1050 data "dog","What a hog, to swallow a dog!"
1060 data "goat","She just opened her throat and swallowed a goat!"
1070 data "cow","I don't know how she swallowed a cow!"
1080 data "horse","...She died, of course!"
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Phix | Phix | with javascript_semantics
constant units = {{"-- metric ---",0},
{"kilometer",1000},
{"km","kilometer"},
{"meter",1},
{"m","meter"},
{"centimeter",0.01},
{"cm","centimeter"},
{" old russian ",0},
{"tochka",0.000254},
{"liniya",0.00254},
{"diuym",0.0254},
{"vershok",0.04445},
{"piad",0.1778},
{"fut",0.3048},
{"arshin",0.7112},
{"sazhen",2.1336},
{"versta",1066.8},
{"milia",7467.6}},
{names,facts} = columnize(units)
function strim(atom v)
string res = sprintf("%,f",v)
integer l = length(res)
while l do
integer c = res[l]
if c!='0' then
l -= 1+(c='.')
exit
end if
l -= 1
end while
res = res[1..l+1]
return res
end function
-- Obviously, uncomment these lines for a prompt (not under p2js)
--while true do
-- string input = prompt_string("\nEnter length & measure or CR to exit:")
-- if input="" then exit end if
-- input = lower(trim(input))
string input = "7.4676 km"
string fmt = iff(find(' ',input)?"%f %s":"%f%s")
sequence r = scanf(input,fmt)
if length(r)!=1 then
printf(1,"enter eg 1km or 1 kilometer\n")
else
{atom v, string name} = r[1]
integer k = find(name,names)
if k=0 or facts[k]=0 then
printf(1,"unrecognised unit: %s\n",{name})
else
if string(facts[k]) then
-- abbreviation, eg cm->centimeter
k = find(facts[k],names)
end if
for i=1 to length(names) do
object f = facts[i]
if f=0 then -- header
printf(1,"--------------%s--------------\n",{names[i]})
elsif atom(facts[i]) then -- not abbrev
printf(1,"%20s %s\n",{strim(v*facts[k]/facts[i]),names[i]})
end if
end for
end if
end if
--end while
|
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Mercury | Mercury | :- module opengl.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module list, glut, glut.callback, glut.window, mogl.
main(!IO) :-
glut.init_window_size(640, 480, !IO),
glut.window.create("Triangle", !IO),
glut.callback.display_func(opengl.paint, !IO),
glut.callback.reshape_func(opengl.reshape, !IO),
glut.main_loop(!IO).
:- pred paint(io::di, io::uo) is det.
paint(!IO) :-
mogl.clear_color(0.3, 0.3, 0.3 , 0.0, !IO),
mogl.clear([color, depth], !IO),
mogl.shade_model(smooth, !IO),
mogl.load_identity(!IO),
mogl.translate(-15.0, -15.0, 0.0, !IO),
mogl.begin(triangles, !IO),
mogl.color3(1.0, 0.0, 0.0, !IO),
mogl.vertex2(0.0, 0.0, !IO),
mogl.color3(0.0, 1.0, 0.0, !IO),
mogl.vertex2(30.0, 0.0, !IO),
mogl.color3(0.0, 0.0, 1.0, !IO),
mogl.vertex2(0.0, 30.0, !IO),
mogl.end(!IO),
mogl.flush(!IO).
:- pred reshape(int::in, int::in, io::di, io::uo) is det.
reshape(Width, Height, !IO) :-
mogl.viewport(0, 0, Width, Height, !IO),
mogl.matrix_mode(projection, !IO),
mogl.load_identity(!IO),
mogl.ortho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0, !IO),
mogl.matrix_mode(modelview, !IO). |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Nim | Nim | import opengl, opengl/glut
proc paint() {.cdecl.} =
glClearColor(0.3,0.3,0.3,0.0)
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)
glShadeModel(GL_SMOOTH)
glLoadIdentity()
glTranslatef(-15.0, -15.0, 0.0)
glBegin(GL_TRIANGLES)
glColor3f(1.0, 0.0, 0.0)
glVertex2f(0.0, 0.0)
glColor3f(0.0, 1.0, 0.0)
glVertex2f(30.0, 0.0)
glColor3f(0.0, 0.0, 1.0)
glVertex2f(0.0, 30.0)
glEnd()
glFlush()
proc reshape(width, height: cint) {.cdecl.} =
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0)
glMatrixMode(GL_MODELVIEW)
enableAutoGlErrorCheck(false)
loadExtensions()
glutInit()
glutInitWindowSize(640, 480)
discard glutCreateWindow("Triangle")
glutDisplayFunc(paint)
glutReshapeFunc(reshape)
glutMainLoop() |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Go | Go | package main
import (
"bufio"
"fmt"
"io"
"math/rand"
"time"
)
// choseLineRandomly implements the method described in the task.
// input is a an io.Reader, which could be an os.File, for example.
// Or, to implement a simulation, it could be anything else that implements
// io.Reader. The method as described suggests saving and returning
// lines, but the rest of the task requires line numbers. This function
// thus returns both.
func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
br := bufio.NewReader(r)
s, err = br.ReadString('\n')
if err != nil {
return
}
ln = 1
lnLast := 1.
var sLast string
for {
// note bufio.ReadString used here. This effectively defines a
// line of the file as zero or more bytes followed by a newline.
sLast, err = br.ReadString('\n')
if err == io.EOF {
return s, ln, nil // normal return
}
if err != nil {
break
}
lnLast++
if rand.Float64() < 1/lnLast {
s = sLast
ln = int(lnLast)
}
}
return // error return
}
// oneOfN function required for task item 1. Specified to take a number
// n, the number of lines in a file, but the method (above) specified to
// to be used does not need n, but rather the file itself. This function
// thus takes both, ignoring n and passing the file to choseLineRandomly.
func oneOfN(n int, file io.Reader) int {
_, ln, err := choseLineRandomly(file)
if err != nil {
panic(err)
}
return ln
}
// simulated file reader for task item 2
type simReader int
func (r *simReader) Read(b []byte) (int, error) {
if *r <= 0 {
return 0, io.EOF
}
b[0] = '\n'
*r--
return 1, nil
}
func main() {
// task item 2 simulation consists of accumulating frequency statistic
// on 1,000,000 calls of oneOfN on simulated file.
n := 10
freq := make([]int, n)
rand.Seed(time.Now().UnixNano())
for times := 0; times < 1e6; times++ {
sr := simReader(n)
freq[oneOfN(n, &sr)-1]++
}
// task item 3. show frequencies.
fmt.Println(freq)
} |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Oz | Oz | declare
class Table
attr
rows
meth init(Rows)
rows := Rows
end
meth sort(ordering:O<=Lexicographic column:C<=1 reverse:R<=false)
fun {Predicate Row1 Row2}
Res = {O {Nth Row1 C} {Nth Row2 C}}
in
if R then {Not Res} else Res end
end
in
rows := {Sort @rows Predicate}
end
end
fun {Lexicographic As Bs} %% omitted for brevity
end
T = {New Table init([["a" "b" "c"] ["" "q" "z"] ["zap" "zip" "Zot"]])}
in
{T sort}
{T sort(column:3)}
{T sort(column:2)}
{T sort(column:2 reverse:true)}
{T sort(ordering:fun {$ A B} {Length B} < {Length A} end)} |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Kotlin | Kotlin | // version 1.0.6
operator fun <T> List<T>.compareTo(other: List<T>): Int
where T: Comparable<T>, T: Number {
for (i in 0 until this.size) {
if (other.size == i) return 1
when {
this[i] < other[i] -> return -1
this[i] > other[i] -> return 1
}
}
return if (this.size == other.size) 0 else -1
}
fun main(args: Array<String>) {
val lists = listOf(
listOf(1, 2, 3, 4, 5),
listOf(1, 2, 1, 5, 2, 2),
listOf(1, 2, 1, 5, 2),
listOf(1, 2, 1, 5, 2),
listOf(1, 2, 1, 3, 2),
listOf(1, 2, 0, 4, 4, 0, 0, 0),
listOf(1, 2, 0, 4, 4, 1, 0, 0)
)
for (i in 0 until lists.size) println("list${i + 1} : ${lists[i]}")
println()
for (i in 0 until lists.size - 1) println("list${i + 1} > list${i + 2} = ${lists[i] > lists[i + 1]}")
} |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia | issorted("abc") # true |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Pointless | Pointless | isPalindrome(chars) =
chars == reverse(chars) |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #Go | Go | package main
import (
"fmt"
"math"
)
// "uncertain number type"
// a little optimization is to represent the error term with its square.
// this saves some taking of square roots in various places.
type unc struct {
n float64 // the number
s float64 // *square* of one sigma error term
}
// constructor, nice to have so it can handle squaring of error term
func newUnc(n, s float64) *unc {
return &unc{n, s * s}
}
// error term accessor method, nice to have so it can handle recovering
// (non-squared) error term from internal (squared) representation
func (z *unc) errorTerm() float64 {
return math.Sqrt(z.s)
}
// Arithmetic methods are modeled on the Go big number package.
// The basic scheme is to pass all operands as method arguments, compute
// the result into the method receiver, and then return the receiver as
// the result of the method. This has an advantage of letting the programer
// determine allocation and use of temporary objects, reducing garbage;
// and has the convenience and efficiency of allowing operations to be chained.
// addition/subtraction
func (z *unc) addC(a *unc, c float64) *unc {
*z = *a
z.n += c
return z
}
func (z *unc) subC(a *unc, c float64) *unc {
*z = *a
z.n -= c
return z
}
func (z *unc) addU(a, b *unc) *unc {
z.n = a.n + b.n
z.s = a.s + b.s
return z
}
func (z *unc) subU(a, b *unc) *unc {
z.n = a.n - b.n
z.s = a.s + b.s
return z
}
// multiplication/division
func (z *unc) mulC(a *unc, c float64) *unc {
z.n = a.n * c
z.s = a.s * c * c
return z
}
func (z *unc) divC(a *unc, c float64) *unc {
z.n = a.n / c
z.s = a.s / (c * c)
return z
}
func (z *unc) mulU(a, b *unc) *unc {
prod := a.n * b.n
z.n, z.s = prod, prod*prod*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
func (z *unc) divU(a, b *unc) *unc {
quot := a.n / b.n
z.n, z.s = quot, quot*quot*(a.s/(a.n*a.n)+b.s/(b.n*b.n))
return z
}
// exponentiation
func (z *unc) expC(a *unc, c float64) *unc {
f := math.Pow(a.n, c)
g := f * c / a.n
z.n = f
z.s = a.s * g * g
return z
}
func main() {
x1 := newUnc(100, 1.1)
x2 := newUnc(200, 2.2)
y1 := newUnc(50, 1.2)
y2 := newUnc(100, 2.3)
var d, d2 unc
d.expC(d.addU(d.expC(d.subU(x1, x2), 2), d2.expC(d2.subU(y1, y2), 2)), .5)
fmt.Println("d: ", d.n)
fmt.Println("error:", d.errorTerm())
} |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Forth | Forth | : word? dup [char] . <> over bl <> and ;
: ?quit dup [char] . = if emit quit then ;
: eatbl begin dup bl = while drop key repeat ?quit ;
: even begin word? while emit key repeat ;
: odd word? if key recurse swap emit then ;
: main cr key eatbl begin even eatbl space odd eatbl space again ; |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Fortran | Fortran | MODULE ELUDOM !Uses the call stack for auxiliary storage.
INTEGER MSG,INF !I/O unit numbers.
LOGICAL DEFER !To stumble, or not to stumble.
CONTAINS
CHARACTER*1 RECURSIVE FUNCTION GET(IN) !Returns one character, going forwards.
INTEGER IN !The input file.
CHARACTER*1 C !The single character to be read therefrom.
READ (IN,1,ADVANCE="NO",EOR=3,END=4) C !Thus. Not advancing to the next record.
1 FORMAT (A1,$) !For output, no advance to the next line either.
2 IF (("A"<=C .AND. C<="Z").OR.("a"<=C .AND. C<="z")) THEN !Unsafe for EBCDIC.
IF (DEFER) THEN !Are we to reverse the current text?
GET = GET(IN) !Yes. Go for the next letter.
WRITE (MSG,1) C !And now, backing out, reveal the letter at this level.
RETURN !Retreat another level.
END IF !Thus passing back the ending non-letter that was encountered.
ELSE !And if we've encountered a non-letter,
DEFER = .NOT. DEFER !Then our backwardness flips.
END IF !Enough inspection of C.
3 GET = C !Pass it back.
RETURN !And we're done.
4 GET = CHAR(0) !Reserving this for end-of-file.
END FUNCTION GET!That was strange.
END MODULE ELUDOM !But as per the specification.
PROGRAM CONFUSED !Just so.
USE ELUDOM !Forwards? Backwards?
CHARACTER*1 C !A scratchpad for multiple inspections.
MSG = 6 !Standard output.
INF = 10 !This will do.
OPEN (INF,NAME = "Confused.txt",STATUS="OLD",ACTION="READ") !Go for the file.
Chew through the input. A full stop marks the end.
10 DEFER = .FALSE. !Start off going forwards.
11 C = GET(INF) !Get some character from file INF.
IF (ICHAR(C).LE.0) STOP !Perhaps end-of-file is reported.
IF (C.NE." ") WRITE (MSG,12) C !Otherwise, write it. A blank for end-of-record.
12 FORMAT (A1,$) !Obviously, not finishing the line each time.
IF (C.NE.".") GO TO 11 !And if not a full stop, do it again.
WRITE (MSG,"('')") !End the line of output.
GO TO 10 !And have another go.
END !That was confusing. |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Applesoft_BASIC | Applesoft BASIC | 100 LET M$ = CHR$ (13)
110 LET A$ = "123456789"
120 FOR S = 0 TO 1 STEP 0
130 LET N$ = A$
140 FOR I = 1 TO 9
150 LET R = INT ( RND (1) * 9 + 1)
160 GOSUB 500SWAP
170 NEXT I
180 LET S = N$ < > A$
190 NEXT S
200 FOR S = 1 TO 1E9
210 PRINT M$"HOW MANY DIGITS "N$M$" FROM THE LEFT ^^^^^^^^^"M$" TO REVERSE? "A$
230 INPUT "--------------> ";N%
300 FOR I = 1 TO INT (N% / 2)
310 LET R = N% - I + 1
320 GOSUB 500SWAP
330 NEXT I
340 IF N$ = A$ THEN PRINT M$"SCORE "S;: END
350 NEXT S
500 LET I$ = MID$ (N$,I,1)
510 LET N$ = MID$ (N$,1,I - 1) + MID$ (N$,R,1) + MID$ (N$,I + 1)
520 LET N$ = MID$ (N$,1,R - 1) + I$ + MID$ (N$,R + 1)
530 RETURN
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #ALGOL_W | ALGOL W | begin
% declare a record type - will be accessed via references %
record R( integer f1, f2, f3 );
% declare a reference to a R instance %
reference(R) refR;
% assign null to the reference %
refR := null;
% test for a null reference - will write "refR is null" %
if refR = null then write( "refR is null" ) else write( "not null" );
end. |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #AmigaE | AmigaE | DEF x : PTR TO object
-> ...
IF object <> NIL
-> ...
ENDIF |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Befunge | Befunge | v
" !!! !! ! ! ! ! ! " ,*25 <v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
v$< @,*25,,,,,,,,,,,,,,,,,,,,<
>110p3>:1-10gg" "-4* \:10gg" "-2* \:1+10gg" "-\:54*1+`#v_20p++ :2`#v_ >:4`#v_> >$" "v
>:3`#^_v>:6`|
^ >$$$$320p10g1+:9`v > >$"!"> 20g10g1+p 20g1+:20p
^ v_10p10g
> ^ |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double int_leftrect(double from, double to, double n, double (*func)())
{
double h = (to-from)/n;
double sum = 0.0, x;
for(x=from; x <= (to-h); x += h)
sum += func(x);
return h*sum;
}
double int_rightrect(double from, double to, double n, double (*func)())
{
double h = (to-from)/n;
double sum = 0.0, x;
for(x=from; x <= (to-h); x += h)
sum += func(x+h);
return h*sum;
}
double int_midrect(double from, double to, double n, double (*func)())
{
double h = (to-from)/n;
double sum = 0.0, x;
for(x=from; x <= (to-h); x += h)
sum += func(x+h/2.0);
return h*sum;
}
double int_trapezium(double from, double to, double n, double (*func)())
{
double h = (to - from) / n;
double sum = func(from) + func(to);
int i;
for(i = 1;i < n;i++)
sum += 2.0*func(from + i * h);
return h * sum / 2.0;
}
double int_simpson(double from, double to, double n, double (*func)())
{
double h = (to - from) / n;
double sum1 = 0.0;
double sum2 = 0.0;
int i;
double x;
for(i = 0;i < n;i++)
sum1 += func(from + h * i + h / 2.0);
for(i = 1;i < n;i++)
sum2 += func(from + h * i);
return h / 6.0 * (func(from) + func(to) + 4.0 * sum1 + 2.0 * sum2);
} |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #FreeBASIC | FreeBASIC | function eqrf( n as uinteger ) as boolean
dim as string sn = str(n)
dim as integer q = 0
for i as uinteger = 2 to len(sn)
if asc(mid(sn,i,1)) > asc(mid(sn,i-1,1)) then
q += 1
elseif asc(mid(sn,i,1)) < asc(mid(sn,i-1,1)) then
q -= 1
end if
next i
if q = 0 then return true else return false
end function
dim as uinteger c = 0, i = 1
while c < 10000001
if eqrf(i) then
c += 1
if c <= 200 then print i;" ";
if c = 10000000 then print : print i
end if
i += 1
wend |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Go | Go | package main
import "fmt"
func risesEqualsFalls(n int) bool {
if n < 10 {
return true
}
rises := 0
falls := 0
prev := -1
for n > 0 {
d := n % 10
if prev >= 0 {
if d < prev {
rises = rises + 1
} else if d > prev {
falls = falls + 1
}
}
prev = d
n /= 10
}
return rises == falls
}
func main() {
fmt.Println("The first 200 numbers in the sequence are:")
count := 0
n := 1
for {
if risesEqualsFalls(n) {
count++
if count <= 200 {
fmt.Printf("%3d ", n)
if count%20 == 0 {
fmt.Println()
}
}
if count == 1e7 {
fmt.Println("\nThe 10 millionth number in the sequence is ", n)
break
}
}
n++
}
} |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #J | J | NB. returns coefficents for yth-order Legendre polynomial
getLegendreCoeffs=: verb define M.
if. y<:1 do. 1 {.~ - y+1 return. end.
(%~ <:@(,~ +:) -/@:* (0;'') ,&> [: getLegendreCoeffs&.> -&1 2) y
)
getPolyRoots=: 1 {:: p. NB. returns the roots of a polynomial
getGaussLegendreWeights=: 2 % -.@*:@[ * (*:@p.~ p..) NB. form: roots getGaussLegendreWeights coeffs
getGaussLegendrePoints=: (getPolyRoots ([ ,: getGaussLegendreWeights) ])@getLegendreCoeffs
NB.*integrateGaussLegendre a Integrates a function u with a n-point Gauss-Legendre quadrature rule over the interval [a,b]
NB. form: npoints function integrateGaussLegendre (a,b)
integrateGaussLegendre=: adverb define
:
'nodes wgts'=. getGaussLegendrePoints x
-: (-~/ y) * wgts +/@:* u -: nodes p.~ (+/ , -~/) y
) |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
// a fantasy two level hierarchy
@interface Animal : NSObject <NSCoding>
{
NSString *animalName;
int numberOfLegs;
}
- (instancetype) initWithName: (NSString*)name andLegs: (NSInteger)legs;
- (void) dump;
@end
@implementation Animal
- (instancetype) initWithName: (NSString*)name andLegs: (NSInteger)legs
{
if ((self = [super init])) {
animalName = name;
numberOfLegs = legs;
}
return self;
}
- (void) dump
{
NSLog(@"%@ has %d legs", animalName, numberOfLegs);
}
// ========
- (void) encodeWithCoder: (NSCoder*)coder
{
[coder encodeObject: animalName forKey: @"Animal.name"];
[coder encodeInt: numberOfLegs forKey: @"Animal.legs"];
}
- (instancetype) initWithCoder: (NSCoder*)coder
{
if ((self = [super init])) {
animalName = [coder decodeObjectForKey: @"Animal.name"];
numberOfLegs = [coder decodeIntForKey: @"Animal.legs"];
}
return self;
}
@end
@interface Mammal : Animal <NSCoding>
{
BOOL hasFur;
NSMutableArray *eatenList;
}
- (instancetype) initWithName: (NSString*)name hasFur: (BOOL)fur;
- (void) addEatenThing: (NSString*)thing;
@end
@implementation Mammal
- (instancetype) init
{
if ((self = [super init])) {
hasFur = NO;
eatenList = [[NSMutableArray alloc] initWithCapacity: 10];
}
return self;
}
- (instancetype) initWithName: (NSString*)name hasFur: (BOOL)fur
{
if ((self = [super initWithName: name andLegs: 4])) {
hasFur = fur;
eatenList = [[NSMutableArray alloc] initWithCapacity: 10];
}
return self;
}
- (void) addEatenThing: (NSString*)thing
{
[eatenList addObject: thing];
}
- (void) dump
{
[super dump];
NSLog(@"has fur? %@", (hasFur) ? @"yes" : @"no" );
NSLog(@"it has eaten %d things:", [eatenList count]);
for ( id element in eatenList )
NSLog(@"it has eaten a %@", element);
NSLog(@"end of eaten things list");
}
// ========= de/archiving
- (void) encodeWithCoder: (NSCoder*)coder
{
[super encodeWithCoder: coder];
[coder encodeBool: numberOfLegs forKey: @"Mammal.hasFur"];
[coder encodeObject: eatenList forKey: @"Mammal.eaten"];
}
- (instancetype) initWithCoder: (NSCoder*)coder
{
if ((self = [super initWithCoder: coder])) {
hasFur = [coder decodeBoolForKey: @"Mammal.hasFur"];
eatenList = [coder decodeObjectForKey: @"Mammal.eaten"];
}
return self;
}
@end
int main()
{
@autoreleasepool {
// let us create a fantasy animal
Animal *anAnimal = [[Animal alloc]
initWithName: @"Eptohippos"
andLegs: 7
];
// for some reason an Eptohippos is not an horse with 7 legs,
// and it is not a mammal, of course...
// let us create a fantasy mammal (which is an animal too)
Mammal *aMammal = [[Mammal alloc]
initWithName: @"Mammaluc"
hasFur: YES
];
// let us add some eaten stuff...
[aMammal addEatenThing: @"lamb"];
[aMammal addEatenThing: @"table"];
[aMammal addEatenThing: @"web page"];
// dump anAnimal
NSLog(@"----- original Animal -----");
[anAnimal dump];
// dump aMammal...
NSLog(@"----- original Mammal -----");
[aMammal dump];
// now let us store the objects...
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *arch = [[NSKeyedArchiver alloc]
initForWritingWithMutableData: data];
[arch encodeObject: anAnimal forKey: @"Eptohippos"];
[arch encodeObject: aMammal forKey: @"Mammaluc"];
[arch finishEncoding];
[data writeToFile: @"objects.dat" atomically: YES];
// now we want to retrieve the saved objects...
NSData *ldata = [[NSData alloc]
initWithContentsOfFile: @"objects.dat"];
NSKeyedUnarchived *darch = [[NSKeyedUnarchiver alloc]
initForReadingWithData: ldata];
Animal *archivedAnimal = [darch decodeObjectForKey: @"Eptohippos"];
Mammal *archivedMammal = [darch decodeObjectForKey: @"Mammaluc"];
[darch finishDecoding];
// now let's dump/print the objects...
NSLog(@"\n");
NSLog(@"----- the archived Animal -----");
[archivedAnimal dump];
NSLog(@"----- the archived Mammal -----");
[archivedMammal dump];
}
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Common_Lisp | Common Lisp | (defun verse (what remark &optional always die) (list what remark always die))
(defun what (verse) (first verse))
(defun remark (verse) (second verse))
(defun always (verse) (third verse))
(defun die (verse) (fourth verse))
(defun ssa (what remark &optional always die )
(verse what (format nil "~a she swallowed a ~a!" remark what always die)))
(defun tsa (what remark &optional always die)
(verse what (format nil "~a, to swallow a ~a!" remark what)))
(defun asa (what remark &optional always die)
(verse what (format nil "~a, and swallowed a ~a!" remark what)))
(let ((verses (list
(verse "fly" "I don't know why she swallowed the fly" T)
(verse "spider" "That wriggled and jiggled and tickled inside her" T)
(tsa "bird" "Now how absurd")
(tsa "cat" "Now fancy that")
(tsa "dog" "what a hog")
(asa "goat" "She just opened her throat")
(ssa "cow" "I don't know how")
(verse "horse" "She's dead, of course!" T T))))
(loop for verse in verses for i from 0 doing
(let ((it (what verse)))
(format t "I know an old lady who swallowed a ~a~%" it)
(format t "~a~%" (remark verse))
(if (not (die verse)) (progn
(if (> i 0)
(loop for j from (1- i) downto 0 doing
(let* ((v (nth j verses)))
(format t "She swallowed the ~a to catch the ~a~%" it (what v))
(setf it (what v))
(if (always v)
(format t "~a~a~%" (if (= j 0) "But " "") (remark v))))))
(format t "Perhaps she'll die. ~%~%")))))) |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Python | Python | from sys import argv
unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254,
"fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254,
"meter": 1.0, "milia": 7467.6, "piad": 0.1778,
"sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,
"versta": 1066.8}
if __name__ == '__main__':
assert len(argv) == 3, 'ERROR. Need two arguments - number then units'
try:
value = float(argv[1])
except:
print('ERROR. First argument must be a (float) number')
raise
unit = argv[2]
assert unit in unit2mult, ( 'ERROR. Only know the following units: '
+ ' '.join(unit2mult.keys()) )
print("%g %s to:" % (value, unit))
for unt, mlt in sorted(unit2mult.items()):
print(' %10s: %g' % (unt, value * unit2mult[unit] / mlt)) |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Racket | Racket |
#lang racket
(define units
'([tochka 0.000254]
[liniya 0.00254]
[diuym 0.0254]
[vershok 0.04445]
[piad 0.1778]
[fut 0.3048]
[arshin 0.7112]
[sazhen 2.1336]
[versta 1066.8]
[milia 7467.6]
[centimeter 0.01]
[meter 1.0]
[kilometer 1000.0]))
(define (show u)
(printf "1 ~s to:\n" u)
(define n (cadr (assq u units)))
(for ([u2 units] #:unless (eq? u (car u2)))
(displayln (~a (~a (car u2) #:width 10 #:align 'right) ": "
(~r (/ n (cadr u2)) #:precision 4))))
(newline))
(show 'meter)
(show 'milia)
|
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #OCaml | OCaml | open GL
open Glut
let display() =
glClearColor 0.3 0.3 0.3 0.0;
glClear[GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
glShadeModel GL_SMOOTH;
glLoadIdentity();
glTranslate (-15.0) (-15.0) (0.0);
glBegin GL_TRIANGLES;
glColor3 1.0 0.0 0.0;
glVertex2 0.0 0.0;
glColor3 0.0 1.0 0.0;
glVertex2 30.0 0.0;
glColor3 0.0 0.0 1.0;
glVertex2 0.0 30.0;
glEnd();
glFlush();
;;
let reshape ~width ~height =
glViewport 0 0 width height;
glMatrixMode GL_PROJECTION;
glLoadIdentity();
glOrtho(-30.0) 30.0 (-30.0) 30.0 (-30.0) 30.0;
glMatrixMode GL_MODELVIEW;
;;
let () =
ignore(glutInit Sys.argv);
glutInitWindowSize 640 480;
ignore(glutCreateWindow "Triangle");
glutDisplayFunc ~display;
glutReshapeFunc ~reshape;
glutMainLoop();
;; |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Haskell | Haskell | import qualified Data.Map as M
import System.Random
import Data.List
import Control.Monad
import System.Environment
testFile = [1..10]
selItem g xs = foldl' f (head xs, 1, 2, g) $ tail xs
where f :: RandomGen a => (b, Int, Int, a) -> b -> (b, Int, Int, a)
f (c, cn, n, gen) l | v == 1 = (l, n, n+1, ngen)
| otherwise = (c, cn, n+1, ngen)
where (v, ngen) = randomR (1, n) gen
oneOfN a = do
g <- newStdGen
let (r, _, _, _) = selItem g a
return r
test = do
x <- replicateM 1000000 (oneOfN testFile)
let f m l = M.insertWith (+) l 1 m
let results = foldl' f M.empty x
forM_ (M.toList results) $ \(x, y) -> putStrLn $ "Line number " ++ show x ++
" had count :" ++ show y
main = do
a <- getArgs
g <- newStdGen
if null a then test
else putStrLn.(\(l, n, _, _) -> "Line " ++
show n ++ ": " ++ l)
.selItem g.lines =<< (readFile $ head a) |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Icon_and_Unicon | Icon and Unicon | procedure main() # one of n
one_of_n_test(10,1000000)
end
procedure one_of_n(n)
every i := 1 to n do
choice := (?0 < 1. / i, i)
return \choice | fail
end
procedure one_of_n_test(n,trials)
bins := table(0)
every i := 1 to trials do
bins[one_of_n(n)] +:= 1
every writes(bins[i := 1 to n]," ")
return bins
end |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #PARI.2FGP | PARI/GP | sort(v, ordering=0, column=0, reverse=0) |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Perl | Perl | sub sorttable
{my @table = @{shift()};
my %opt =
(ordering => sub {$_[0] cmp $_[1]}, column => 0, reverse => 0, @_);
my $col = $opt{column};
my $func = $opt{ordering};
my @result = sort
{$func->($a->[$col], $b->[$col])}
@table;
return ($opt{reverse} ? [reverse @result] : \@result);} |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #LabVIEW | LabVIEW | local(
first = array(1,2,1,3,2),
second = array(1,2,0,4,4,0,0,0),
)
#first < #second
local(
first = array(1,1,1,3,2),
second = array(1,2,0,4,4,0,0,0),
)
#first < #second |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Lasso | Lasso | local(
first = array(1,2,1,3,2),
second = array(1,2,0,4,4,0,0,0),
)
#first < #second
local(
first = array(1,1,1,3,2),
second = array(1,2,0,4,4,0,0,0),
)
#first < #second |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #K | K | w@&d=|/d:#:'w:d@&&/'{~x<y}':'d:0:"unixdict.txt"
("abbott"
"accent"
"accept"
"access"
"accost"
"almost"
"bellow"
"billow"
"biopsy"
"chilly"
"choosy"
"choppy"
"effort"
"floppy"
"glossy"
"knotty") |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | import java.io.File
fun main(args: Array<String>) {
val file = File("unixdict.txt")
val result = mutableListOf<String>()
file.forEachLine {
if (it.toCharArray().sorted().joinToString(separator = "") == it) {
result += it
}
}
result.sortByDescending { it.length }
val max = result[0].length
for (word in result) {
if (word.length == max) {
println(word)
}
}
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Potion | Potion | # The readable recursive version
palindrome_i = (s, b, e):
if (e <= b): true.
elsif (s ord(b) != s ord(e)): false.
else: palindrome_i(s, b+1, e-1).
.
palindrome = (s):
palindrome_i(s, 0, s length - 1).
palindrome(argv(1)) |
http://rosettacode.org/wiki/Numeric_error_propagation | Numeric error propagation | If f, a, and b are values with uncertainties σf, σa, and σb, and c is a constant;
then if f is derived from a, b, and c in the following ways,
then σf can be calculated as follows:
Addition/Subtraction
If f = a ± c, or f = c ± a then σf = σa
If f = a ± b then σf2 = σa2 + σb2
Multiplication/Division
If f = ca or f = ac then σf = |cσa|
If f = ab or f = a / b then σf2 = f2( (σa / a)2 + (σb / b)2)
Exponentiation
If f = ac then σf = |fc(σa / a)|
Caution:
This implementation of error propagation does not address issues of dependent and independent values. It is assumed that a and b are independent and so the formula for multiplication should not be applied to a*a for example. See the talk page for some of the implications of this issue.
Task details
Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term.
Implement enough functionality to perform the following calculations.
Given coordinates and their errors:
x1 = 100 ± 1.1
y1 = 50 ± 1.2
x2 = 200 ± 2.2
y2 = 100 ± 2.3
if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula:
d = √ (x1 - x2)² + (y1 - y2)²
Print and display both d and its error.
References
A Guide to Error Propagation B. Keeney, 2005.
Propagation of uncertainty Wikipedia.
Related task
Quaternion type
| #Haskell | Haskell | data Error a = Error {value :: a, uncertainty :: a} deriving (Eq, Show)
instance (Floating a) => Num (Error a) where
Error a ua + Error b ub = Error (a + b) (sqrt (ua ^ 2 + ub ^ 2))
negate (Error a ua) = Error (negate a) ua
Error a ua * Error b ub = Error (a * b) (abs (a * b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) -- I've factored out the f^2 from the square root
fromInteger a = Error (fromInteger a) 0
instance (Floating a) => Fractional (Error a) where
fromRational a = Error (fromRational a) 0
Error a ua / Error b ub = Error (a / b) (abs (a / b * sqrt ((ua / a) ^ 2 + (ub / b) ^ 2))) -- I've factored out the f^2 from the square root
instance (Floating a) => Floating (Error a) where
Error a ua ** Error c 0 = Error (a ** c) (abs (ua * c * a**c / a))
main = print (sqrt ((x1 - x2) ** 2 + (y1 - y2) ** 2)) where -- using (^) for exponentiation would calculate a*a, which the problem specifically said was calculated wrong
x1 = Error 100 1.1
y1 = Error 50 1.2
x2 = Error 200 2.2
y2 = Error 100 2.3
|
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Go | Go | package main
import (
"bytes"
"fmt"
"io"
"os"
"unicode"
)
func main() {
owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
fmt.Println()
owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
fmt.Println()
}
func owp(dst io.Writer, src io.Reader) {
byte_in := func () byte {
bs := make([]byte, 1)
src.Read(bs)
return bs[0]
}
byte_out := func (b byte) { dst.Write([]byte{b}) }
var odd func() byte
odd = func() byte {
s := byte_in()
if unicode.IsPunct(rune(s)) {
return s
}
b := odd()
byte_out(s)
return b
}
for {
for {
b := byte_in()
byte_out(b)
if b == '.' {
return
}
if unicode.IsPunct(rune(b)) {
break
}
}
b := odd()
byte_out(b)
if b == '.' {
return
}
}
} |
http://rosettacode.org/wiki/Number_names | Number names | Task
Show how to spell out a number in English.
You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional.
Related task
Spelling of ordinal numbers.
| #360_Assembly | 360 Assembly | * Number names 20/02/2017
NUMNAME CSECT
USING NUMNAME,R13
B 72(R15)
DC 17F'0'
STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 end of prolog
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(NG)) do i=1 to hbound(g)
LR R1,R6 i
SLA R1,2
L R2,G-4(R1) g(i)
ST R2,N n=g(i)
L R4,N
IF LTR,R4,Z,R4 THEN if n=0 then
MVC R,=CL256'zero' r='zero'
ELSE , else
MVC R,=CL256' ' r=''
MVC D,=F'10' d=10
MVC C,=F'100' c=100
MVC K,=F'1000' k=1000
L R2,N n
LPR R2,R2 abs(n)
ST R2,A a=abs(n)
SR R7,R7 j=0
DO WHILE=(C,R7,LE,D) do j=0 to d
L R4,A a
SRDA R4,32
D R4,C /c
M R4,C *a
L R8,A a
SR R8,R5 h=a-c*a/c
IF C,R8,GT,=F'0',AND,C,R8,LT,D THEN if h>0 & h<d then
LR R1,R8 h
MH R1,=H'10'
LA R4,S(R1) @s(h+1)
MVC PG(10),0(R4) s(h+1)
MVC PG+10(246),R !!r
MVC R,PG r=s(h+1)!!' '!!r
ENDIF , endif
IF C,R8,GT,=F'9',AND,C,R8,LT,=F'20' THEN if h>9 & h<20 then
LR R1,R8 h
S R1,D -d
MH R1,=H'10'
LA R4,T(R1) @t(h-d+1)
MVC PG(10),0(R4) t(h-d+1)
MVC PG+10(246),R !!r
MVC R,PG r=t(h-d+1)!!' '!!r
ENDIF , endif
IF C,R8,GT,=F'19',AND,C,R8,LT,C THEN if h>19 & h<c then
LR R4,R8 h
SRDA R4,32
D R4,D /d
M R4,D *d
LR R1,R8 h
SR R1,R5 h-d*(h/d)
ST R1,X x=h-d*(h/d)
L R4,X x
IF LTR,R4,NZ,R4 THEN if x^=0 then
MVI Y,C'-' y='-'
ELSE , else
MVI Y,C' ' y=' '
ENDIF , endif
LR R4,R8 h
SRDA R4,32
D R4,D /d
MH R5,=H'10'
LA R4,U(R5) @u(h/d+1)
MVC PG(10),0(R4) u(h/d+1)
MVC PG+10(1),Y y
L R1,X x
MH R1,=H'10'
LA R4,S(R1) @s(x+1)
MVC PG+11(10),0(R4) s(x+1)
MVC PG+21(235),R !!r
MVC R,PG r=u(h/d+1)!!y!!s(x+1)!!r
ENDIF , endif
L R4,A a
SRDA R4,32
D R4,K a/k
M R4,K *k
L R8,A a
SR R8,R5 h=a-k*(a/k)
LR R4,R8 h
SRDA R4,32
D R4,C /c
LR R8,R5 h=h/c
IF LTR,R8,NZ,R8 THEN if h^=0 then
LR R1,R8 h
MH R1,=H'10'
LA R4,S(R1) @s(h+1)
MVC PG(10),0(R4) s(h+1)
MVC PG+10(10),=CL10' hundred '
MVC PG+20(236),R !!r
MVC R,PG r=s(h+1)!!' hundred '!!r
ENDIF , endif
L R4,A a
SRDA R4,32
D R4,K /k
ST R5,A a=a/k
L R4,A
IF LTR,R4,P,R4 THEN if a>0 then
L R4,A a
SRDA R4,32
D R4,K /k
M R4,K *k
L R8,A a
SR R8,R5 h=a-k*(a/k)
IF LTR,R8,NZ,R8 THEN if h^=0 then
LR R1,R7 j
MH R1,=H'10'
LA R4,V(R1) @v(j+1)
MVC PG(10),0(R4) v(j+1)
MVC PG+10(246),R !!r
MVC R,PG r=v(j+1)!!' '!!r
ENDIF , endif
ENDIF , endif
LA R3,1 l=0
LA R9,256 jr=256
LA R10,R ir=0
LA R11,R-1 irr=-1
LOOP CLI 0(R10),C' ' if r[ii]=' ' .....+
BNE OPT |
CLI 1(R10),C' ' if r[ii+1]=' ' |
BE ITER |
CLI 1(R10),C'-' if r[ii+1]='-' |
BE ITER |
OPT LA R11,1(R11) irr=irr+1 |
MVC 0(1,R11),0(R10) rr=rr!!ci |
LA R3,1(R3) l=l+1 |
ITER LA R10,1(R10) ir=ir+1 |
BCT R9,LOOP ...................+
LA R1,R-1 @r
AR R1,R3 +lr
MVC 0(80,R1),=CL80' ' clean the end
L R4,A a
IF LTR,R4,NP,R4 THEN if a<=0 then
B LEAVEJ leave
ENDIF , endif a<=0
LA R7,1(R7) j++
ENDDO , enddo j
LEAVEJ L R4,N n
IF LTR,R4,M,R4 THEN if n<0 then
MVC PG(6),=C'minus ' 'minus '
MVC PG+6(250),R !!r
MVC R,PG r='minus '!!r
ENDIF , endif n<0
ENDIF , endif n=0
MVC PG,=CL132' ' clear buffer
L R1,N n
XDECO R1,PG edit n
MVC PG+13(256),R r
XPRNT PG,132 print buffer
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) epilog
LM R14,R12,12(R13)
XR R15,R15
BR R14 exit
S DC CL10' ',CL10'one',CL10'two',CL10'three',CL10'four'
DC CL10'five',CL10'six',CL10'seven',CL10'eight',CL10'nine'
T DC CL50'ten eleven twelve thirteen fourteen'
DC CL50'fifteen sixteen seventeen eighteen nineteen'
U DC CL50' twenty thirty forty'
DC CL50'fifty sixty seventy eighty ninety'
V DC CL50'thousand million billion trillion'
G DC F'0',F'2',F'19',F'20',F'21',F'99',F'100',F'101',F'-123'
DC F'9123',F'467889',F'1234567',F'2147483647'
NG EQU (*-G)/4
N DS F
D DS F
C DS F
K DS F
A DS F
X DS F
Y DS CL1
R DS CL256
XDEC DS CL12
PG DS CL256
YREGS
END NUMNAME |
http://rosettacode.org/wiki/Number_reversal_game | Number reversal game | Task
Given a jumbled list of the numbers 1 to 9 that are definitely not in
ascending order.
Show the list, and then ask the player how many digits from the
left to reverse.
Reverse those digits, then ask again, until all the digits end up in ascending order.
The score is the count of the reversals needed to attain the ascending order.
Note: Assume the player's input does not need extra validation.
Related tasks
Sorting algorithms/Pancake sort
Pancake sorting.
Topswops
| #Arturo | Arturo | arr: 1..9
while [arr = sort arr]->
arr: shuffle arr
score: 0
while [arr <> sort arr][
prints [arr "-- "]
digits: to :integer strip input "How many digits to reverse? "
arr: (reverse slice arr 0 digits-1) ++ slice arr digits (size arr)-1
score: score + 1
]
print ["Your score:" score] |
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #APL | APL |
⍝⍝ GNU APL
]help ⍬
niladic function: Z ← ⍬ (Zilde)
Zilde is the empty numeric vector (aka. ⍳0)
Not a function but rather an alias for the empty
vector:
⍬≡⍳0
1
|
http://rosettacode.org/wiki/Null_object | Null object |
Null (or nil) is the computer science concept of an undefined or unbound object.
Some languages have an explicit way to access the null object, and some don't.
Some languages distinguish the null object from undefined values, and some don't.
Task
Show how to access null in your language by checking to see if an object is equivalent to the null object.
This task is not about whether a variable is defined. The task is about "null"-like values in various languages, which may or may not be related to the defined-ness of variables in your language.
| #AppleScript | AppleScript | if x is missing value then
display dialog "x is missing value"
end if
if x is null then
display dialog "x is null"
end if |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Bracmat | Bracmat | ( ( evolve
= n z
. @( !arg
: %?n ? @?z
: ?
( ( ( 000
| 001
| 010
| 100
| 111
)
& 0 !n:?n
| (011|101|110)
& 1 !n:?n
)
& ~`
)
?
)
| rev$(str$(!z !n))
)
& 11101101010101001001:?S
& :?seen
& whl
' ( ~(!seen:? !S ?)
& out$!S
& !S !seen:?seen
& evolve$!S:?S
)
); |
http://rosettacode.org/wiki/Numerical_integration | Numerical integration | Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods:
rectangular
left
right
midpoint
trapezium
Simpson's
composite
Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n).
Assume that your example already has a function that gives values for ƒ(x) .
Simpson's method is defined by the following pseudo-code:
Pseudocode: Simpson's method, composite
procedure quad_simpson_composite(f, a, b, n)
h := (b - a) / n
sum1 := f(a + h/2)
sum2 := 0
loop on i from 1 to (n - 1)
sum1 := sum1 + f(a + h * i + h/2)
sum2 := sum2 + f(a + h * i)
answer := (h / 6) * (f(a) + f(b) + 4*sum1 + 2*sum2)
Demonstrate your function by showing the results for:
ƒ(x) = x3, where x is [0,1], with 100 approximations. The exact result is 0.25 (or 1/4)
ƒ(x) = 1/x, where x is [1,100], with 1,000 approximations. The exact result is 4.605170+ (natural log of 100)
ƒ(x) = x, where x is [0,5000], with 5,000,000 approximations. The exact result is 12,500,000
ƒ(x) = x, where x is [0,6000], with 6,000,000 approximations. The exact result is 18,000,000
See also
Active object for integrating a function of real time.
Special:PrefixIndex/Numerical integration for other integration methods.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
public class Interval
{
public Interval(double leftEndpoint, double size)
{
LeftEndpoint = leftEndpoint;
RightEndpoint = leftEndpoint + size;
}
public double LeftEndpoint
{
get;
set;
}
public double RightEndpoint
{
get;
set;
}
public double Size
{
get
{
return RightEndpoint - LeftEndpoint;
}
}
public double Center
{
get
{
return (LeftEndpoint + RightEndpoint) / 2;
}
}
public IEnumerable<Interval> Subdivide(int subintervalCount)
{
double subintervalSize = Size / subintervalCount;
return Enumerable.Range(0, subintervalCount).Select(index => new Interval(LeftEndpoint + index * subintervalSize, subintervalSize));
}
}
public class DefiniteIntegral
{
public DefiniteIntegral(Func<double, double> integrand, Interval domain)
{
Integrand = integrand;
Domain = domain;
}
public Func<double, double> Integrand
{
get;
set;
}
public Interval Domain
{
get;
set;
}
public double SampleIntegrand(ApproximationMethod approximationMethod, Interval subdomain)
{
switch (approximationMethod)
{
case ApproximationMethod.RectangleLeft:
return Integrand(subdomain.LeftEndpoint);
case ApproximationMethod.RectangleMidpoint:
return Integrand(subdomain.Center);
case ApproximationMethod.RectangleRight:
return Integrand(subdomain.RightEndpoint);
case ApproximationMethod.Trapezium:
return (Integrand(subdomain.LeftEndpoint) + Integrand(subdomain.RightEndpoint)) / 2;
case ApproximationMethod.Simpson:
return (Integrand(subdomain.LeftEndpoint) + 4 * Integrand(subdomain.Center) + Integrand(subdomain.RightEndpoint)) / 6;
default:
throw new NotImplementedException();
}
}
public double Approximate(ApproximationMethod approximationMethod, int subdomainCount)
{
return Domain.Size * Domain.Subdivide(subdomainCount).Sum(subdomain => SampleIntegrand(approximationMethod, subdomain)) / subdomainCount;
}
public enum ApproximationMethod
{
RectangleLeft,
RectangleMidpoint,
RectangleRight,
Trapezium,
Simpson
}
}
public class Program
{
private static void TestApproximationMethods(DefiniteIntegral integral, int subdomainCount)
{
foreach (DefiniteIntegral.ApproximationMethod approximationMethod in Enum.GetValues(typeof(DefiniteIntegral.ApproximationMethod)))
{
Console.WriteLine(integral.Approximate(approximationMethod, subdomainCount));
}
}
public static void Main()
{
TestApproximationMethods(new DefiniteIntegral(x => x * x * x, new Interval(0, 1)), 10000);
TestApproximationMethods(new DefiniteIntegral(x => 1 / x, new Interval(1, 99)), 1000);
TestApproximationMethods(new DefiniteIntegral(x => x, new Interval(0, 5000)), 500000);
TestApproximationMethods(new DefiniteIntegral(x => x, new Interval(0, 6000)), 6000000);
}
} |
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Haskell | Haskell | import Data.Char
pairs :: [a] -> [(a,a)]
pairs (a:b:as) = (a,b):pairs (b:as)
pairs _ = []
riseEqFall :: Int -> Bool
riseEqFall n = rel (>) digitPairs == rel (<) digitPairs
where rel r = sum . map (fromEnum . uncurry r)
digitPairs = pairs $ map digitToInt $ show n
a296712 :: [Int]
a296712 = [n | n <- [1..], riseEqFall n]
main :: IO ()
main = do
putStrLn "The first 200 numbers are: "
putStrLn $ unwords $ map show $ take 200 a296712
putStrLn ""
putStr "The 10,000,000th number is: "
putStrLn $ show $ a296712 !! 9999999
|
http://rosettacode.org/wiki/Numbers_with_equal_rises_and_falls | Numbers with equal rises and falls | When a number is written in base 10, adjacent digits may "rise" or "fall" as the number is read (usually from left to right).
Definition
Given the decimal digits of the number are written as a series d:
A rise is an index i such that d(i) < d(i+1)
A fall is an index i such that d(i) > d(i+1)
Examples
The number 726,169 has 3 rises and 2 falls, so it isn't in the sequence.
The number 83,548 has 2 rises and 2 falls, so it is in the sequence.
Task
Print the first 200 numbers in the sequence
Show that the 10 millionth (10,000,000th) number in the sequence is 41,909,002
See also
OEIS Sequence A296712 describes numbers whose digit sequence in base 10 have equal "rises" and "falls".
Related tasks
Esthetic numbers
| #Java | Java | public class EqualRisesFalls {
public static void main(String[] args) {
final int limit1 = 200;
final int limit2 = 10000000;
System.out.printf("The first %d numbers in the sequence are:\n", limit1);
int n = 0;
for (int count = 0; count < limit2; ) {
if (equalRisesAndFalls(++n)) {
++count;
if (count <= limit1)
System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' ');
}
}
System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n);
}
private static boolean equalRisesAndFalls(int n) {
int total = 0;
for (int previousDigit = -1; n > 0; n /= 10) {
int digit = n % 10;
if (previousDigit > digit)
++total;
else if (previousDigit >= 0 && previousDigit < digit)
--total;
previousDigit = digit;
}
return total == 0;
}
} |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #Java | Java | import static java.lang.Math.*;
import java.util.function.Function;
public class Test {
final static int N = 5;
static double[] lroots = new double[N];
static double[] weight = new double[N];
static double[][] lcoef = new double[N + 1][N + 1];
static void legeCoef() {
lcoef[0][0] = lcoef[1][1] = 1;
for (int n = 2; n <= N; n++) {
lcoef[n][0] = -(n - 1) * lcoef[n - 2][0] / n;
for (int i = 1; i <= n; i++) {
lcoef[n][i] = ((2 * n - 1) * lcoef[n - 1][i - 1]
- (n - 1) * lcoef[n - 2][i]) / n;
}
}
}
static double legeEval(int n, double x) {
double s = lcoef[n][n];
for (int i = n; i > 0; i--)
s = s * x + lcoef[n][i - 1];
return s;
}
static double legeDiff(int n, double x) {
return n * (x * legeEval(n, x) - legeEval(n - 1, x)) / (x * x - 1);
}
static void legeRoots() {
double x, x1;
for (int i = 1; i <= N; i++) {
x = cos(PI * (i - 0.25) / (N + 0.5));
do {
x1 = x;
x -= legeEval(N, x) / legeDiff(N, x);
} while (x != x1);
lroots[i - 1] = x;
x1 = legeDiff(N, x);
weight[i - 1] = 2 / ((1 - x * x) * x1 * x1);
}
}
static double legeInte(Function<Double, Double> f, double a, double b) {
double c1 = (b - a) / 2, c2 = (b + a) / 2, sum = 0;
for (int i = 0; i < N; i++)
sum += weight[i] * f.apply(c1 * lroots[i] + c2);
return c1 * sum;
}
public static void main(String[] args) {
legeCoef();
legeRoots();
System.out.print("Roots: ");
for (int i = 0; i < N; i++)
System.out.printf(" %f", lroots[i]);
System.out.print("\nWeight:");
for (int i = 0; i < N; i++)
System.out.printf(" %f", weight[i]);
System.out.printf("%nintegrating Exp(x) over [-3, 3]:%n\t%10.8f,%n"
+ "compared to actual%n\t%10.8f%n",
legeInte(x -> exp(x), -3, 3), exp(3) - exp(-3));
}
} |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #OCaml | OCaml | type entity = { name : string }
let create_entity () = { name = "Entity" }
let print_entity x = print_endline x.name
let create_person () = { name = "Cletus" }
let instance1 = create_person ()
let instance2 = create_entity ()
(* Serialize *)
let out_chan = open_out_bin "objects.dat";;
output_value out_chan instance1;;
output_value out_chan instance2;;
close_out out_chan;;
(* Deserialize *)
let in_chan = open_in_bin "objects.dat";;
let result1 : entity = input_value in_chan;;
let result2 : entity = input_value in_chan;;
close_in in_chan;;
print_entity result1;;
print_entity result2;; |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Ol | Ol |
$ ol
Welcome to Otus Lisp 1.2,
type ',help' to help, ',quit' to end session.
> (define Object (tuple
'(1 2 3 4) ; list
#(4 3 2 1) ; bytevector
"hello" ; ansi string
"こんにちは" ; unicode string
(list->ff '(; associative array
(1 . 123456)
(2 . second)
(3 . "-th-")))
{(4 . 'sym) ; alternatively declared..
(5 . +)} ; ..associative array
#false ; value
-123 ; short number
123456789012345678901234567890123456789 ; long number
)
;; Defined Object
#((1 2 3 4) #(4 3 2 1) hello こんにちは #ff((1 . 123456) (2 . second) (3 . -th-))
#ff((4 . sym) (5 . #<function>)) #false -123
123456789012345678901234567890123456789)
> (fasl-save Object "/tmp/object.bin")
#true
> (define New (fasl-load "/tmp/object.bin" #false))
;; Defined New
#((1 2 3 4) #(4 3 2 1) hello こんにちは #ff((1 . 123456) (2 . second) (3 . -th-))
#ff((4 . sym) (5 . #<function>)) #false -123
123456789012345678901234567890123456789)
> (equal? Object New)
#true
> ,quit
bye-bye :/
$
|
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.