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/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Phix | Phix | with javascript_semantics
function sos(integer n)
if n<3 then return {} end if
integer r = floor(sqrt(n)),
k = floor((n-3)/2)+1,
l = floor((r-3)/2)+1
sequence primes = {},
marked = repeat(false,k)
for i=1 to l do
integer p = 2*i+1,
s = (p*p-1)/2
for j=s to k by p do
marked[j] = true
end for
end for
for i=1 to k do
if not marked[i] then
primes = append(primes, 2*i+1)
end if
end for
return primes
end function
sequence s = sos(16_000_000)
printf(1,"The first 100 odd prime numbers:\n%s\n",{join_by(apply(true,sprintf,{{"%3d"},s[1..100]}),1,10)})
printf(1,"The millionth odd prime number: %,d\n",{s[1_000_000]})
|
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Python | Python | from numpy import log
def sieve_of_Sundaram(nth, print_all=True):
"""
The sieve of Sundaram is a simple deterministic algorithm for finding all the
prime numbers up to a specified integer. This function is modified from the
Wikipedia entry wiki/Sieve_of_Sundaram, to give primes to their nth rather
than the Wikipedia function that gives primes less than n.
"""
assert nth > 0, "nth must be a positive integer"
k = int((2.4 * nth * log(nth)) // 2) # nth prime is at about n * log(n)
integers_list = [True] * k
for i in range(1, k):
j = i
while i + j + 2 * i * j < k:
integers_list[i + j + 2 * i * j] = False
j += 1
pcount = 0
for i in range(1, k + 1):
if integers_list[i]:
pcount += 1
if print_all:
print(f"{2 * i + 1:4}", end=' ')
if pcount % 10 == 0:
print()
if pcount == nth:
print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n")
break
sieve_of_Sundaram(100, True)
sieve_of_Sundaram(1000000, False)
|
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Racket | Racket | #lang racket
(define (make-sieve-as-set limit)
(let ((marked (for/mutable-set ((i limit)) (add1 i))))
(let loop ((start 4) (step 3))
(cond [(>= start limit) marked]
[else (for ((i (in-range start limit step))) (set-remove! marked i))
(loop (+ start 3) (+ step 2))]))
(define (prime? n)
(and (odd? n)
(let ((idx (quotient (sub1 n) 2)))
(unless (<= idx limit) (error 'out-of-bounds))
(set-member? marked idx))))
(values marked prime?)))
(define (Sieve-of-Sundaram)
(define-values (sieve#1 prime?#1) (make-sieve-as-set 1000))
(displayln (for/list ((i 100) (p (sequence-filter prime?#1 (in-naturals)))) p))
;; this will generate primes *twice* as big, which should include 15485867...
(define-values (sieve#2 prime?#2) (make-sieve-as-set 10000000))
(define sorted-sieve#2 (sort (set->list sieve#2) <))
(displayln (add1 (* 2 (list-ref sorted-sieve#2 (sub1 1000000))))))
(module+ main
(Sieve-of-Sundaram)) |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Raku | Raku | my $nth = 1_000_000;
my $k = Int.new: 2.4 * $nth * log($nth) / 2;
my int @sieve;
@sieve[$k] = 0;
hyper for 1 .. $k -> \i {
my int $j = i;
while (my int $l = i + $j + 2 * i * $j) < $k {
@sieve[$l] = 1;
$j = $j + 1;
}
}
@sieve[0] = 1;
say "First 100 Sundaram primes:";
say @sieve.kv.map( { next if $^v; $^k * 2 + 1 } )[^100]».fmt("%4d").batch(10).join: "\n";
say "\nOne millionth:";
my ($count, $index);
for @sieve {
$count += !$_;
say $index * 2 + 1 and last if $count == $nth;
++$index;
} |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #REXX | REXX | /*REXX program finds & displays N Sundaram primes, or displays the Nth Sundaram prime.*/
parse arg n cols . /*get optional number of primes to find*/
if n=='' | n=="," then n= 100 /*Not specified? Then assume default.*/
if cols=='' | cols=="," then cols= 10 /* " " " " " */
@.= .; lim= 16 * n /*default value for array; filter limit*/
do j=1 for n; do k=1 for n until _>lim; _= j + k + 2*j*k; @._=
end /*k*/
end /*j*/
w= 10 /*width of a number in any column. */
title= 'a list of ' commas(N) " Sundaram primes"
if cols>0 then say ' index │'center(title, 1 + cols*(w+1) )
if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─')
#= 0; idx= 1 /*initialize # of Sundaram primes & IDX*/
$= /*a list of Sundaram primes (so far). */
do j=1 until #==n /*display the output (if cols > 0). */
if @.j\==. then iterate /*Is the number not prime? Then skip. */
#= # + 1 /*bump number of Sundaram primes found.*/
a= j /*save J for calculating the Nth prime.*/
if cols<=0 then iterate /*Build the list (to be shown later)? */
c= commas(j + j + 1) /*maybe add commas to Sundaram prime.*/
$= $ right(c, max(w, length(c) ) ) /*add Sundaram prime──►list, allow big#*/
if #//cols\==0 then iterate /*have we populated a line of output? */
say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */
idx= idx + cols /*bump the index count for the output*/
end /*j*/
if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/
if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─')
say
say 'found ' commas(#) " Sundaram primes, and the last Sundaram prime is " commas(a+a+1)
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Ruby | Ruby | def sieve_of_sundaram(upto)
n = (2.4 * upto * Math.log(upto)) / 2
k = (n - 3) / 2 + 1
bools = [true] * k
(0..(Integer.sqrt(n) - 3) / 2 + 1).each do |i|
p = 2*i + 3
s = (p*p - 3) / 2
(s..k).step(p){|j| bools[j] = false}
end
bools.filter_map.each_with_index {|b, i| (i + 1) * 2 + 1 if b }
end
p sieve_of_sundaram(100)
n = 1_000_000
puts "\nThe #{n}th sundaram prime is #{sieve_of_sundaram(n)[n-1]}"
|
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #11l | 11l | F thieleInterpolator(x, y)
V ρ = enumerate(y).map((i, yi) -> [yi] * (@y.len - i))
L(i) 0 .< ρ.len - 1
ρ[i][1] = (x[i] - x[i + 1]) / (ρ[i][0] - ρ[i + 1][0])
L(i) 2 .< ρ.len
L(j) 0 .< ρ.len - i
ρ[j][i] = (x[j] - x[j + i]) / (ρ[j][i - 1] - ρ[j + 1][i - 1]) + ρ[j + 1][i - 2]
V ρ0 = ρ[0]
F t(xin)
V a = 0.0
L(i) (@=ρ0.len - 1 .< 1).step(-1)
a = (xin - @=x[i - 1]) / (@=ρ0[i] - @=ρ0[i - 2] + a)
R @=y[0] + (xin - @=x[0]) / (@=ρ0[1] + a)
R t
V xVal = (0.<32).map(i -> i * 0.05)
V tSin = xVal.map(x -> sin(x))
V tCos = xVal.map(x -> cos(x))
V tTan = xVal.map(x -> tan(x))
V iSin = thieleInterpolator(tSin, xVal)
V iCos = thieleInterpolator(tCos, xVal)
V iTan = thieleInterpolator(tTan, xVal)
print(‘#.14’.format(6 * iSin(0.5)))
print(‘#.14’.format(3 * iCos(0.5)))
print(‘#.14’.format(4 * iTan(1))) |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Wren | Wren | import "/fmt" for Fmt
import "/seq" for Lst
var sos = Fn.new { |n|
if (n < 3) return []
var primes = []
var k = ((n-3)/2).floor + 1
var marked = List.filled(k, true)
var limit = ((n.sqrt.floor - 3)/2).floor + 1
limit = limit.max(0)
for (i in 0...limit) {
var p = 2*i + 3
var s = ((p*p - 3)/2).floor
var j = s
while (j < k) {
marked[j] = false
j = j + p
}
}
for (i in 0...k) {
if (marked[i]) primes.add(2*i + 3)
}
return primes
}
// odds only
var soe = Fn.new { |n|
if (n < 3) return []
var primes = []
var k = ((n-3)/2).floor + 1
var marked = List.filled(k, true)
var limit = ((n.sqrt.floor - 3)/2).floor + 1
limit = limit.max(0)
for (i in 0...limit) {
if (marked[i]) {
var p = 2*i + 3
var s = ((p*p - 3)/2).floor
var j = s
while (j < k) {
marked[j] = false
j = j + p
}
}
}
for (i in 0...k) {
if (marked[i]) primes.add(2*i + 3)
}
return primes
}
var limit = 16e6 // say
var start = System.clock
var primes = sos.call(limit)
var elapsed = ((System.clock - start) * 1000).round
Fmt.print("Using the Sieve of Sundaram generated primes up to $,d in $,d ms.\n", limit, elapsed)
System.print("First 100 odd primes generated by the Sieve of Sundaram:")
for (chunk in Lst.chunks(primes[0..99], 10)) Fmt.print("$3d", chunk)
Fmt.print("\nThe $,d Sundaram prime is $,d", 1e6, primes[1e6-1])
start = System.clock
primes = soe.call(limit)
elapsed = ((System.clock - start) * 1000).round
Fmt.print("\nUsing the Sieve of Eratosthenes would have generated them in $,d ms.", elapsed)
Fmt.print("\nAs a check, the $,d Sundaram prime would again have been $,d", 1e6, primes[1e6-1]) |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Ada | Ada | with Ada.Numerics.Generic_Real_Arrays;
generic
type Real is digits <>;
package Thiele is
package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real);
subtype Real_Array is Real_Arrays.Real_Vector;
type Thiele_Interpolation (Length : Natural) is private;
function Create (X, Y : Real_Array) return Thiele_Interpolation;
function Inverse (T : Thiele_Interpolation; X : Real) return Real;
private
type Thiele_Interpolation (Length : Natural) is record
X, Y, RhoX : Real_Array (1 .. Length);
end record;
end Thiele; |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #ALGOL_68 | ALGOL 68 | PROC raise exception = ([]STRING msg)VOID: ( putf(stand error,("Exception:", $" "g$, msg, $l$)); stop );
# The MODE of lx and ly here should really be a UNION of "something REAL",
"something COMPLex", and "something SYMBOLIC" ... #
PROC thiele=([]REAL lx,ly, REAL x) REAL:
BEGIN
[]REAL xx=lx[@1],yy=ly[@1];
INT n=UPB xx;
IF UPB yy=n THEN
# Assuming that the values of xx are distinct ... #
[0:n-1,1:n]REAL p;
p[0,]:=yy[];
FOR i TO n-1 DO p[1,i]:=(xx[i]-xx[1+i])/(p[0,i]-p[0,1+i]) OD;
FOR i FROM 2 TO n-1 DO
FOR j TO n-i DO
p[i,j]:=(xx[j]-xx[j+i])/(p[i-1,j]-p[i-1,j+1])+p[i-2,j+1]
OD
OD;
REAL a:=0;
FOR i FROM n-1 BY -1 TO 2 DO a:=(x-xx[i])/(p[i,1]-p[i-2,1]+a) OD;
yy[1]+(x-xx[1])/(p[1,1]+a)
ELSE
raise exception(("Unequal length arrays supplied: ",whole(UPB xx,0)," NE ",whole(UPB yy,0))); SKIP
FI
END;
test:(
FORMAT real fmt = $g(0,real width-2)$;
REAL lwb x=0, upb x=1.55, delta x = 0.05;
[0:ENTIER ((upb x-lwb x)/delta x)]STRUCT(REAL x, sin x, cos x, tan x) trig table;
PROC init trig table = VOID:
FOR i FROM LWB trig table TO UPB trig table DO
REAL x = lwb x+i*delta x;
trig table[i]:=(x, sin(x), cos(x), tan(x))
OD;
init trig table;
# Curry the thiele function to create matching inverse trigonometric functions #
PROC (REAL)REAL inv sin = thiele(sin x OF trig table, x OF trig table,),
inv cos = thiele(cos x OF trig table, x OF trig table,),
inv tan = thiele(tan x OF trig table, x OF trig table,);
printf(($"pi estimate using "g" interpolation: "f(real fmt)l$,
"sin", 6*inv sin(1/2),
"cos", 3*inv cos(1/2),
"tan", 4*inv tan(1)
))
) |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #C | C | #include <stdio.h>
#include <string.h>
#include <math.h>
#define N 32
#define N2 (N * (N - 1) / 2)
#define STEP .05
double xval[N], t_sin[N], t_cos[N], t_tan[N];
/* rho tables, layout:
rho_{n-1}(x0)
rho_{n-2}(x0), rho_{n-1}(x1),
....
rho_0(x0), rho_0(x1), ... rho_0(x_{n-1})
rho_i row starts at index (n - 1 - i) * (n - i) / 2 */
double r_sin[N2], r_cos[N2], r_tan[N2];
/* both rho and thiele functions recursively resolve values as decribed by
formulas. rho is cached, thiele is not. */
/* rho_n(x_i, x_{i+1}, ..., x_{i + n}) */
double rho(double *x, double *y, double *r, int i, int n)
{
if (n < 0) return 0;
if (!n) return y[i];
int idx = (N - 1 - n) * (N - n) / 2 + i;
if (r[idx] != r[idx]) /* only happens if value not computed yet */
r[idx] = (x[i] - x[i + n])
/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))
+ rho(x, y, r, i + 1, n - 2);
return r[idx];
}
double thiele(double *x, double *y, double *r, double xin, int n)
{
if (n > N - 1) return 1;
return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)
+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);
}
#define i_sin(x) thiele(t_sin, xval, r_sin, x, 0)
#define i_cos(x) thiele(t_cos, xval, r_cos, x, 0)
#define i_tan(x) thiele(t_tan, xval, r_tan, x, 0)
int main()
{
int i;
for (i = 0; i < N; i++) {
xval[i] = i * STEP;
t_sin[i] = sin(xval[i]);
t_cos[i] = cos(xval[i]);
t_tan[i] = t_sin[i] / t_cos[i];
}
for (i = 0; i < N2; i++)
/* init rho tables to NaN */
r_sin[i] = r_cos[i] = r_tan[i] = 0/0.;
printf("%16.14f\n", 6 * i_sin(.5));
printf("%16.14f\n", 3 * i_cos(.5));
printf("%16.14f\n", 4 * i_tan(1.));
return 0;
} |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #C.2B.2B | C++ | #include <cmath>
#include <iostream>
#include <iomanip>
#include <string.h>
constexpr unsigned int N = 32u;
double xval[N], t_sin[N], t_cos[N], t_tan[N];
constexpr unsigned int N2 = N * (N - 1u) / 2u;
double r_sin[N2], r_cos[N2], r_tan[N2];
double ρ(double *x, double *y, double *r, int i, int n) {
if (n < 0)
return 0;
if (!n)
return y[i];
unsigned int idx = (N - 1 - n) * (N - n) / 2 + i;
if (r[idx] != r[idx])
r[idx] = (x[i] - x[i + n]) / (ρ(x, y, r, i, n - 1) - ρ(x, y, r, i + 1, n - 1)) + ρ(x, y, r, i + 1, n - 2);
return r[idx];
}
double thiele(double *x, double *y, double *r, double xin, unsigned int n) {
return n > N - 1 ? 1. : ρ(x, y, r, 0, n) - ρ(x, y, r, 0, n - 2) + (xin - x[n]) / thiele(x, y, r, xin, n + 1);
}
inline auto i_sin(double x) { return thiele(t_sin, xval, r_sin, x, 0); }
inline auto i_cos(double x) { return thiele(t_cos, xval, r_cos, x, 0); }
inline auto i_tan(double x) { return thiele(t_tan, xval, r_tan, x, 0); }
int main() {
constexpr double step = .05;
for (auto i = 0u; i < N; i++) {
xval[i] = i * step;
t_sin[i] = sin(xval[i]);
t_cos[i] = cos(xval[i]);
t_tan[i] = t_sin[i] / t_cos[i];
}
for (auto i = 0u; i < N2; i++)
r_sin[i] = r_cos[i] = r_tan[i] = NAN;
std::cout << std::setw(16) << std::setprecision(25)
<< 6 * i_sin(.5) << std::endl
<< 3 * i_cos(.5) << std::endl
<< 4 * i_tan(1.) << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Common_Lisp | Common Lisp | ;; 256 is heavy overkill, but hey, we memoized
(defparameter *thiele-length* 256)
(defparameter *rho-cache* (make-hash-table :test #'equal))
(defmacro make-thele-func (f name xx0 xx1)
(let ((xv (gensym)) (yv (gensym))
(x0 (gensym)) (x1 (gensym)))
`(let* ((,xv (make-array (1+ *thiele-length*)))
(,yv (make-array (1+ *thiele-length*)))
(,x0 ,xx0)
(,x1 ,xx1))
(loop for i to *thiele-length* with x do
(setf x (+ ,x0 (* (/ (- ,x1 ,x0) *thiele-length*) i))
(aref ,yv i) x
(aref ,xv i) (funcall ,f x)))
(defun ,name (x) (thiele x ,yv ,xv, 0)))))
(defun rho (yv xv n i)
(let (hit (key (list yv xv n i)))
(if (setf hit (gethash key *rho-cache*))
hit
(setf (gethash key *rho-cache*)
(cond ((zerop n) (aref yv i))
((minusp n) 0)
(t (+ (rho yv xv (- n 2) (1+ i))
(/ (- (aref xv i)
(aref xv (+ i n)))
(- (rho yv xv (1- n) i)
(rho yv xv (1- n) (1+ i)))))))))))
(defun thiele (x yv xv n)
(if (= n *thiele-length*)
1
(+ (- (rho yv xv n 1) (rho yv xv (- n 2) 1))
(/ (- x (aref xv (1+ n)))
(thiele x yv xv (1+ n))))))
(make-thele-func #'sin inv-sin 0 (/ pi 2))
(make-thele-func #'cos inv-cos 0 (/ pi 2))
(make-thele-func #'tan inv-tan 0 (/ pi 2.1)) ; tan(pi/2) is INF
(format t "~f~%" (* 6 (inv-sin .5)))
(format t "~f~%" (* 3 (inv-cos .5)))
(format t "~f~%" (* 4 (inv-tan 1))) |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #D | D | import std.stdio, std.range, std.array, std.algorithm, std.math;
struct Domain {
const real b, e, s;
auto range() const pure /*nothrow*/ @safe /*@nogc*/ {
return iota(b, e + s, s);
}
}
real eval0(alias RY, alias X, alias Y)(in real x) pure nothrow @safe @nogc {
real a = 0.0L;
foreach_reverse (immutable i; 2 .. X.length - 3)
a = (x - X[i]) / (RY[i] - RY[i-2] + a);
return Y[1] + (x - X[1]) / (RY[1] + a);
}
immutable struct Thiele {
immutable real[] Y, X, rhoY, rhoX;
this(real[] y, real[] x) immutable pure nothrow /*@safe*/
in {
assert(x.length > 2, "at leat 3 values");
assert(x.length == y.length, "input arrays not of same size");
} body {
this.Y = y.idup;
this.X = x.idup;
rhoY = rhoN(Y, X);
rhoX = rhoN(X, Y);
}
this(in real function(real) pure nothrow @safe @nogc f,
Domain d = Domain(0.0L, 1.55L, 0.05L))
immutable pure /*nothrow @safe*/ {
auto xrng = d.range.array;
this(xrng.map!f.array, xrng);
}
auto rhoN(immutable real[] y, immutable real[] x)
pure nothrow @safe {
immutable int N = x.length;
auto p = new real[][](N, N);
p[0][] = y[];
p[1][0 .. $ - 1] = (x[0 .. $-1] - x[1 .. $]) /
(p[0][0 .. $-1] - p[0][1 .. $]);
foreach (immutable int j; 2 .. N - 1) {
immutable M = N - j - 1;
p[j][0..M] = p[j-2][1..M+1] + (x[0..M] - x[j..M+j]) /
(p[j-1][0 .. M] - p[j-1][1 .. M+1]);
}
return p.map!q{ a[1] }.array;
}
alias eval = eval0!(rhoY, X, Y);
alias inverse = eval0!(rhoX, Y, X);
}
void main() {
// Can't pass sin, cos and tan directly.
immutable tsin = Thiele(x => x.sin);
immutable tcos = Thiele(x => x.cos);
immutable ttan = Thiele(x => x.tan);
writefln(" %d interpolating points\n", tsin.X.length);
writefln("std.math.sin(0.5): %20.18f", 0.5L.sin);
writefln(" Thiele sin(0.5): %20.18f\n", tsin.eval(0.5L));
writefln("*%20.19f library constant", PI);
writefln(" %20.19f 6 * inv_sin(0.5)", tsin.inverse(0.5L) * 6.0L);
writefln(" %20.19f 3 * inv_cos(0.5)", tcos.inverse(0.5L) * 3.0L);
writefln(" %20.19f 4 * inv_tan(1.0)", ttan.inverse(1.0L) * 4.0L);
} |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Go | Go | package main
import (
"fmt"
"math"
)
func main() {
// task 1: build 32 row trig table
const nn = 32
const step = .05
xVal := make([]float64, nn)
tSin := make([]float64, nn)
tCos := make([]float64, nn)
tTan := make([]float64, nn)
for i := range xVal {
xVal[i] = float64(i) * step
tSin[i], tCos[i] = math.Sincos(xVal[i])
tTan[i] = tSin[i] / tCos[i]
}
// task 2: define inverses
iSin := thieleInterpolator(tSin, xVal)
iCos := thieleInterpolator(tCos, xVal)
iTan := thieleInterpolator(tTan, xVal)
// task 3: demonstrate identities
fmt.Printf("%16.14f\n", 6*iSin(.5))
fmt.Printf("%16.14f\n", 3*iCos(.5))
fmt.Printf("%16.14f\n", 4*iTan(1))
}
func thieleInterpolator(x, y []float64) func(float64) float64 {
n := len(x)
ρ := make([][]float64, n)
for i := range ρ {
ρ[i] = make([]float64, n-i)
ρ[i][0] = y[i]
}
for i := 0; i < n-1; i++ {
ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
}
for i := 2; i < n; i++ {
for j := 0; j < n-i; j++ {
ρ[j][i] = (x[j]-x[j+i])/(ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
}
}
// ρ0 used in closure. the rest of ρ becomes garbage.
ρ0 := ρ[0]
return func(xin float64) float64 {
var a float64
for i := n - 1; i > 1; i-- {
a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
}
return y[0] + (xin-x[0])/(ρ0[1]+a)
}
} |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Haskell | Haskell | thiele :: [Double] -> [Double] -> Double -> Double
thiele xs ys = f rho1 (tail xs)
where
f _ [] _ = 1
f r@(r0:r1:r2:rs) (x:xs) v = r2 - r0 + (v - x) / f (tail r) xs v
rho1 = (!! 1) . (++ [0]) <$> rho
rho = repeat 0 : repeat 0 : ys : rnext (tail rho) xs (tail xs)
where
rnext _ _ [] = []
rnext r@(r0:r1:rs) x xn =
let z_ = zipWith
in z_ (+) (tail r0) (z_ (/) (z_ (-) x xn) (z_ (-) r1 (tail r1))) :
rnext (tail r) x (tail xn)
-- Inverted interpolation function of f
invInterp :: (Double -> Double) -> [Double] -> Double -> Double
invInterp f xs = thiele (map f xs) xs
main :: IO ()
main =
mapM_
print
[ 3.21 * inv_sin (sin (pi / 3.21))
, pi / 1.2345 * inv_cos (cos 1.2345)
, 7 * inv_tan (tan (pi / 7))
]
where
[inv_sin, inv_cos, inv_tan] =
uncurry ((. div_pi) . invInterp) <$>
[(sin, (2, 31)), (cos, (2, 100)), (tan, (4, 1000))]
-- N points taken uniformly from 0 to Pi/d
div_pi (d, n) = (* (pi / (d * n))) <$> [0 .. n] |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #J | J |
span =: {. - {: NB. head - tail
spans =: span\ NB. apply span to successive infixes
|
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Java | Java | import static java.lang.Math.*;
public class Test {
final static int N = 32;
final static int N2 = (N * (N - 1) / 2);
final static double STEP = 0.05;
static double[] xval = new double[N];
static double[] t_sin = new double[N];
static double[] t_cos = new double[N];
static double[] t_tan = new double[N];
static double[] r_sin = new double[N2];
static double[] r_cos = new double[N2];
static double[] r_tan = new double[N2];
static double rho(double[] x, double[] y, double[] r, int i, int n) {
if (n < 0)
return 0;
if (n == 0)
return y[i];
int idx = (N - 1 - n) * (N - n) / 2 + i;
if (r[idx] != r[idx])
r[idx] = (x[i] - x[i + n])
/ (rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1))
+ rho(x, y, r, i + 1, n - 2);
return r[idx];
}
static double thiele(double[] x, double[] y, double[] r, double xin, int n) {
if (n > N - 1)
return 1;
return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2)
+ (xin - x[n]) / thiele(x, y, r, xin, n + 1);
}
public static void main(String[] args) {
for (int i = 0; i < N; i++) {
xval[i] = i * STEP;
t_sin[i] = sin(xval[i]);
t_cos[i] = cos(xval[i]);
t_tan[i] = t_sin[i] / t_cos[i];
}
for (int i = 0; i < N2; i++)
r_sin[i] = r_cos[i] = r_tan[i] = Double.NaN;
System.out.printf("%16.14f%n", 6 * thiele(t_sin, xval, r_sin, 0.5, 0));
System.out.printf("%16.14f%n", 3 * thiele(t_cos, xval, r_cos, 0.5, 0));
System.out.printf("%16.14f%n", 4 * thiele(t_tan, xval, r_tan, 1.0, 0));
}
} |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Julia | Julia | const N = 256
const N2 = N * div(N - 1, 2)
const step = 0.01
const xval_table = zeros(Float64, N)
const tsin_table = zeros(Float64, N)
const tcos_table = zeros(Float64, N)
const ttan_table = zeros(Float64, N)
const rsin_cache = Dict{Float64, Float64}()
const rcos_cache = Dict{Float64, Float64}()
const rtan_cache = Dict{Float64, Float64}()
function rho(x, y, rhocache, i, n)
if n < 0
return 0.0
elseif n == 0
return y[i+1]
end
idx = (N - 1 - n) * div(N - n, 2) + i
if !haskey(rhocache, idx)
rhocache[idx] = (x[i+1] - x[i + n+1]) / (rho(x, y, rhocache, i, n - 1) -
rho(x, y, rhocache, i + 1, n - 1)) + rho(x, y, rhocache, i + 1, n - 2)
end
rhocache[idx]
end
function thiele(x, y, r, xin, n)
if n > N - 1
return 1.0
end
rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) + (xin - x[n + 1]) / thiele(x, y, r, xin, n + 1)
end
function thiele_tables()
for i in 1:N
xval_table[i] = (i-1) * step
tsin_table[i] = sin(xval_table[i])
tcos_table[i] = cos(xval_table[i])
ttan_table[i] = tsin_table[i] / tcos_table[i]
end
println(6 * thiele(tsin_table, xval_table, rsin_cache, 0.5, 0))
println(3 * thiele(tcos_table, xval_table, rcos_cache, 0.5, 0))
println(4 * thiele(ttan_table, xval_table, rtan_cache, 1.0, 0))
end
thiele_tables()
|
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Kotlin | Kotlin | // version 1.1.2
const val N = 32
const val N2 = N * (N - 1) / 2
const val STEP = 0.05
val xval = DoubleArray(N)
val tsin = DoubleArray(N)
val tcos = DoubleArray(N)
val ttan = DoubleArray(N)
val rsin = DoubleArray(N2) { Double.NaN }
val rcos = DoubleArray(N2) { Double.NaN }
val rtan = DoubleArray(N2) { Double.NaN }
fun rho(x: DoubleArray, y: DoubleArray, r: DoubleArray, i: Int, n: Int): Double {
if (n < 0) return 0.0
if (n == 0) return y[i]
val idx = (N - 1 - n) * (N - n) / 2 + i
if (r[idx].isNaN()) {
r[idx] = (x[i] - x[i + n]) /
(rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) +
rho(x, y, r, i + 1, n - 2)
}
return r[idx]
}
fun thiele(x: DoubleArray, y: DoubleArray, r: DoubleArray, xin: Double, n: Int): Double {
if (n > N - 1) return 1.0
return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) +
(xin - x[n]) / thiele(x, y, r, xin, n + 1)
}
fun main(args: Array<String>) {
for (i in 0 until N) {
xval[i] = i * STEP
tsin[i] = Math.sin(xval[i])
tcos[i] = Math.cos(xval[i])
ttan[i] = tsin[i] / tcos[i]
}
println("%16.14f".format(6 * thiele(tsin, xval, rsin, 0.5, 0)))
println("%16.14f".format(3 * thiele(tcos, xval, rcos, 0.5, 0)))
println("%16.14f".format(4 * thiele(ttan, xval, rtan, 1.0, 0)))
} |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | num = 32;
num2 = num (num - 1)/2;
step = 0.05;
ClearAll[\[Rho], Thiele]
\[Rho][x_List, y_List, i_Integer, n_Integer] := Module[{idx},
If[n < 0,
0
,
If[n == 0,
y[[i + 1]]
,
idx = (num - 1 - n) (num - n)/2 + i + 1;
If[r[[idx]] === Null,
r[[idx]] = (x[[1 + i]] -
x[[1 + i + n]])/(\[Rho][x, y, i, n - 1] - \[Rho][x, y,
i + 1, n - 1]) + \[Rho][x, y, i + 1, n - 2];
];
r[[idx]]
]
]
]
Thiele[x_List, y_List, xin_, n_Integer] := Module[{},
If[n > num - 1,
1
,
\[Rho][x, y, 0, n] - \[Rho][x, y, 0, n - 2] + (xin - x[[n + 1]])/
Thiele[x, y, xin, n + 1]
]
]
xval = Range[0, num - 1] step;
funcvals = Sin[xval];
r = ConstantArray[Null, num2];
6 Thiele[funcvals, xval, 0.5, 0]
funcvals = Cos[xval];
r = ConstantArray[Null, num2];
3 Thiele[funcvals, xval, 0.5, 0]
funcvals = Tan[xval];
r = ConstantArray[Null, num2];
4 Thiele[funcvals, xval, 1.0, 0] |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Nim | Nim | import strformat
import math
const N = 32
const N2 = N * (N - 1) div 2
const STEP = 0.05
var xval = newSeq[float](N)
var tsin = newSeq[float](N)
var tcos = newSeq[float](N)
var ttan = newSeq[float](N)
var rsin = newSeq[float](N2)
var rcos = newSeq[float](N2)
var rtan = newSeq[float](N2)
proc rho(x, y: openArray[float], r: var openArray[float], i, n: int): float =
if n < 0:
return 0
if n == 0:
return y[i]
let idx = (N - 1 - n) * (N - n) div 2 + i
if r[idx] != r[idx]:
r[idx] = (x[i] - x[i + n]) /
(rho(x, y, r, i, n - 1) - rho(x, y, r, i + 1, n - 1)) +
rho(x, y, r, i + 1, n - 2)
return r[idx]
proc thiele(x, y: openArray[float], r: var openArray[float], xin: float, n: int): float =
if n > N - 1:
return 1
return rho(x, y, r, 0, n) - rho(x, y, r, 0, n - 2) +
(xin - x[n]) / thiele(x, y, r, xin, n + 1)
for i in 0..<N:
xval[i] = float(i) * STEP
tsin[i] = sin(xval[i])
tcos[i] = cos(xval[i])
ttan[i] = tsin[i] / tcos[i]
for i in 0..<N2:
rsin[i] = NaN
rcos[i] = NaN
rtan[i] = NaN
echo fmt"{6 * thiele(tsin, xval, rsin, 0.5, 0):16.14f}"
echo fmt"{3 * thiele(tcos, xval, rcos, 0.5, 0):16.14f}"
echo fmt"{4 * thiele(ttan, xval, rtan, 1.0, 0):16.14f}" |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #OCaml | OCaml | let xv, fv = fst, snd
let rec rdiff a l r =
if l > r then 0.0 else
if l = r then fv a.(l) else
if l+1 = r then (xv a.(l) -. xv a.(r)) /. (fv a.(l) -. fv a.(r)) else
(xv a.(l) -. xv a.(r)) /. (rdiff a l (r-1) -. rdiff a (l+1) r) +. rdiff a (l+1) (r-1)
let rec thiele x a a0 k n =
if k = n then 1.0 else
rdiff a a0 (a0+k) -. rdiff a a0 (a0+k-2) +. (x -. xv a.(a0+k)) /. thiele x a a0 (k+1) n
let interpolate x a n =
let m = Array.length a in
let dist i = abs_float (x -. xv a.(i)) in
let nearer i j = if dist j < dist i then j else i in
let rec closest i j = if j = m then i else closest (nearer i j) (j+1) in
let c = closest 0 1 in
let c' = if c < n/2 then 0 else if c > m-n then m-n else c-(n/2) in
thiele x a c' 0 n
let table a b n f =
let g i =
let x = a +. (b-.a)*.(float i)/.(float (n-1)) in
(f x, x) in
Array.init n g
let [sin_tab; cos_tab; tan_tab] = List.map (table 0.0 1.55 32) [sin; cos; tan]
let test n =
Printf.printf "\nDegree %d interpolation:\n" n;
Printf.printf "6*arcsin(0.5) = %.15f\n" (6.0*.(interpolate 0.5 sin_tab n));
Printf.printf "3*arccos(0.5) = %.15f\n" (3.0*.(interpolate 0.5 cos_tab n));
Printf.printf "4*arctan(1.0) = %.15f\n" (4.0*.(interpolate 1.0 tan_tab n));;
List.iter test [8; 12; 16] |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use Math::Trig;
use utf8;
sub thiele {
my($x, $y) = @_;
my @ρ;
push @ρ, [($$y[$_]) x (@$y-$_)] for 0 .. @$y-1;
for my $i (0 .. @ρ - 2) {
$ρ[$i][1] = (($$x[$i] - $$x[$i+1]) / ($ρ[$i][0] - $ρ[$i+1][0]))
}
for my $i (2 .. @ρ - 2) {
for my $j (0 .. (@ρ - 2) - $i) {
$ρ[$j][$i] = ((($$x[$j]-$$x[$j+$i]) / ($ρ[$j][$i-1]-$ρ[$j+1][$i-1])) + $ρ[$j+1][$i-2])
}
}
my @ρ0 = @{$ρ[0]};
return sub {
my($xin) = @_;
my $a = 0;
for my $i (reverse 2 .. @ρ0 - 2) {
$a = (($xin - $$x[$i-1]) / ($ρ0[$i] - $ρ0[$i-2] + $a))
}
$$y[0] + (($xin - $$x[0]) / ($ρ0[1] + $a))
}
}
my(@x,@sin_table,@cos_table,@tan_table);
push @x, .05 * $_ for 0..31;
push @sin_table, sin($_) for @x;
push @cos_table, cos($_) for @x;
push @tan_table, tan($_) for @x;
my $sin_inverse = thiele(\@sin_table, \@x);
my $cos_inverse = thiele(\@cos_table, \@x);
my $tan_inverse = thiele(\@tan_table, \@x);
say 6 * &$sin_inverse(0.5);
say 3 * &$cos_inverse(0.5);
say 4 * &$tan_inverse(1.0); |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | F print_verse(n)
V l = [String(‘b’), ‘f’, ‘m’]
V s = n[1..]
V? i = l.find(n[0].lowercase())
I i != N
l[i] = ‘’
E I n[0] C (‘A’, ‘E’, ‘I’, ‘O’, ‘U’)
s = n.lowercase()
print("#., #., bo-#.#.\nBanana-fana fo-#.#.\nFee-fi-mo-#.#.\n#.!\n".format(n, n, l[0], s, l[1], s, l[2], s, n))
L(n) [‘Gary’, ‘Earl’, ‘Billy’, ‘Felix’, ‘Mary’]
print_verse(n) |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Phix | Phix | constant N = 32,
N2 = (N * (N - 1) / 2),
STEP = 0.05
constant inf = 1e300*1e300,
nan = -(inf/inf)
sequence {xval, t_sin, t_cos, t_tan} = repeat(repeat(0,N),4)
for i=1 to N do
xval[i] = (i-1) * STEP
t_sin[i] = sin(xval[i])
t_cos[i] = cos(xval[i])
t_tan[i] = t_sin[i] / t_cos[i]
end for
enum R_SIN, R_COS, R_TAN, R_TRIG=$
sequence rhot = repeat(repeat(nan,N2),R_TRIG)
function rho(sequence x, y, integer rdx, int i, int n)
if n<0 then return 0 end if
if n=0 then return y[i+1] end if
integer idx = (N - 1 - n) * (N - n) / 2 + i + 1;
if rhot[rdx][idx]=nan then -- value not computed yet
rhot[rdx][idx] = (x[i+1] - x[i+1 + n])
/ (rho(x, y, rdx, i, n-1) - rho(x, y, rdx, i+1, n-1))
+ rho(x, y, rdx, i+1, n-2)
end if
return rhot[rdx][idx]
end function
function thiele(sequence x, y, integer rdx, atom xin, integer n)
if n>N-1 then return 1 end if
return rho(x, y, rdx, 0, n) - rho(x, y, rdx, 0, n-2)
+ (xin-x[n+1]) / thiele(x, y, rdx, xin, n+1)
end function
constant fmt = iff(machine_bits()=32?"%32s : %.14f\n"
:"%32s : %.17f\n")
printf(1,fmt,{"PI",PI})
printf(1,fmt,{"6*arcsin(0.5)",6*arcsin(0.5)})
printf(1,fmt,{"3*arccos(0.5)",3*arccos(0.5)})
printf(1,fmt,{"4*arctan(1)",4*arctan(1)})
printf(1,fmt,{"6*thiele(t_sin,xval,R_SIN,0.5,0)",6*thiele(t_sin,xval,R_SIN,0.5,0)})
printf(1,fmt,{"3*thiele(t_cos,xval,R_COS,0.5,0)",3*thiele(t_cos,xval,R_COS,0.5,0)})
printf(1,fmt,{"4*thiele(t_tan,xval,R_TAN,1,0)",4*thiele(t_tan,xval,R_TAN,1,0)})
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | with Ada.Characters.Handling;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
procedure The_Name_Game
is
package ACH renames Ada.Characters.Handling;
package ASU renames Ada.Strings.Unbounded;
function "+"(input : in String) return ASU.Unbounded_String renames ASU.To_Unbounded_String;
function "+"(input : in ASU.Unbounded_String) return String renames ASU.To_String;
function Normalize_Case(input : in String) return String is
begin
return ACH.To_Upper(input(input'First))
& ACH.To_Lower(input(input'First + 1 .. input'Last));
end Normalize_Case;
function Transform(input : in String; letter : in Character) return String is
begin
case input(input'First) is
when 'A' | 'E' | 'I' | 'O' | 'U' =>
return letter & ACH.To_Lower(input);
when others =>
if ACH.To_Lower(input(input'First)) = letter then
return input(input'First + 1 .. input'Last);
else
return letter & input(input'First + 1 .. input'Last);
end if;
end case;
end Transform;
procedure Lyrics(name : in String)
is
normalized : constant String := Normalize_Case(name);
begin
Ada.Text_IO.Put_Line(normalized & ", " & normalized & ", bo-" & Transform(normalized, 'b'));
Ada.Text_IO.Put_Line("Banana-fana, fo-" & Transform(normalized, 'f'));
Ada.Text_IO.Put_Line("fi-fee-mo-" & Transform(normalized, 'm'));
Ada.Text_IO.Put_Line(normalized & '!');
Ada.Text_IO.New_Line;
end Lyrics;
names : constant array(1 .. 5) of ASU.Unbounded_String :=
(+"Gary",
+"EARL",
+"billy",
+"FeLiX",
+"Mary");
begin
for name of names loop
Lyrics(+name);
end loop;
end The_Name_Game; |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #PicoLisp | PicoLisp | (scl 17)
(load "@lib/math.l")
(setq
*X-Table (range 0.0 1.55 0.05)
*SinTable (mapcar sin *X-Table)
*CosTable (mapcar cos *X-Table)
*TanTable (mapcar tan *X-Table)
*TrigRows (length *X-Table) )
(let N2 (>> 1 (* *TrigRows (dec *TrigRows)))
(setq
*InvSinTable (need N2)
*InvCosTable (need N2)
*InvTanTable (need N2) ) )
(de rho (Tbl Inv I N)
(cond
((lt0 N) 0)
((=0 N) (get *X-Table I))
(T
(let Idx (+ I (>> 1 (* (- *TrigRows 1 N) (- *TrigRows N))))
(or
(get Inv Idx)
(set (nth Inv Idx) # only happens if value not computed yet
(+
(rho Tbl Inv (inc I) (- N 2))
(*/
(- (get Tbl I) (get Tbl (+ I N)))
1.0
(-
(rho Tbl Inv I (dec N))
(rho Tbl Inv (inc I) (dec N)) ) ) ) ) ) ) ) ) )
(de thiele (Tbl Inv X N)
(if (> N *TrigRows)
1.0
(+
(-
(rho Tbl Inv 1 (dec N))
(rho Tbl Inv 1 (- N 3)) )
(*/
(- X (get Tbl N))
1.0
(thiele Tbl Inv X (inc N)) ) ) ) )
(de iSin (X)
(thiele *SinTable *InvSinTable X 1) )
(de iCos (X)
(thiele *CosTable *InvCosTable X 1) )
(de iTan (X)
(thiele *TanTable *InvTanTable 1.0 1) ) |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #11l | 11l | V debug = 0B
V datePat = re:‘\d{4}-\d{2}-\d{2}’
V valuPat = re:‘[-+]?\d+\.\d+’
V statPat = re:‘-?\d+’
V totalLines = 0
Set[String] dupdate
Set[String] badform
Set[String] badlen
V badreading = 0
Set[String] datestamps
L(line) File(‘readings.txt’).read().rtrim("\n").split("\n")
totalLines++
V fields = line.split("\t")
V date = fields[0]
V pairs = (1 .< fields.len).step(2).map(i -> (@fields[i], @fields[i + 1]))
V lineFormatOk = datePat.match(date)
& all(pairs.map(p -> :valuPat.match(p[0])))
& all(pairs.map(p -> :statPat.match(p[1])))
I !lineFormatOk
I debug
print(‘Bad formatting ’line)
badform.add(date)
I pairs.len != 24 | any(pairs.map(p -> Int(p[1]) < 1))
I debug
print(‘Missing values ’line)
I pairs.len != 24
badlen.add(date)
I any(pairs.map(p -> Int(p[1]) < 1))
badreading++
I date C datestamps
I debug
print(‘Duplicate datestamp ’line)
dupdate.add(date)
datestamps.add(date)
print("Duplicate dates:\n "sorted(Array(dupdate)).join("\n "))
print("Bad format:\n "sorted(Array(badform)).join("\n "))
print("Bad number of fields:\n "sorted(Array(badlen)).join("\n "))
print("Records with good readings: #. = #2.2%\n".format(
totalLines - badreading, (totalLines - badreading) / Float(totalLines) * 100))
print(‘Total records: ’totalLines) |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 |
main:(
PROC print lyrics = (STRING name) VOID:
BEGIN
PROC change name = (STRING name, CHAR initial) STRING:
BEGIN
CHAR lower first = to lower(name[1]);
IF char in string(lower first, NIL, "aeiou") THEN
lower first + name[2:]
ELIF lower first = initial THEN
name[2:]
ELSE
initial + name[2:]
FI
END;
print((name, ", ", name, ", bo-", change name(name, "b"), new line,
"Banana-fana fo-", change name(name, "f"), new line,
"Fee-fi-mo-", change name(name, "m"), new line,
name, "!", new line))
END;
[]STRING names = ("Gary", "Earl", "Billy", "Felix", "Mary");
FOR i FROM LWB names TO UPB names DO
print lyrics(names[i]);
print(new line)
OD
)
|
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #PowerShell | PowerShell | Function Reciprocal-Difference( [Double[][]] $function )
{
$rho=@()
$rho+=0
$funcl = $function.length
if( $funcl -gt 0 )
{
-2..($funcl-1) | ForEach-Object {
$i=$_
#Write-Host "$($i+1) - $($rho[$i+1]) - $($rho[$i+1].GetType())"
$rho[$i+2] = $( 0..($funcl-$i-1) | Where-Object {$_ -lt $funcl} | ForEach-Object {
$j=$_
switch ($i) {
{$_ -lt 0 } { 0 }
{$_ -eq 0 } { $function[$j][1] }
{$_ -gt 0 } { ( $function[$j][0] - $function[$j+$i][0] ) / ( $rho[$i+1][$j] - $rho[$i+1][$j+1] ) + $rho[$i][$j+1] }
}
if( $_ -lt $funcl )
{
$rho += 0
}
})
}
}
$rho
}
Function Thiele-Interpolation ( [Double[][]] $function )
{
$funcl = $function.length
$invoke = "{`n`tparam([Double] `$x)`n"
if($funcl -gt 1)
{
$rho = Reciprocal-Difference $function
($funcl-1)..0 | ForEach-Object {
$invoke += "`t"
$invoke += '$x{0} = {1} - {2}' -f $_, @($rho[$_+2])[0], @($rho[$_])[0]
if($_ -lt ($funcl-1))
{
$invoke += ' + ( $x - {0} ) / $x{1} ' -f $function[$_][0], ($_+1)
}
$invoke += "`n"
}
$invoke+="`t`$x0`n}"
} else {
$invoke += "`t`$x`n}"
}
invoke-expression $invoke
}
$sint=@{}; 0..31 | ForEach-Object { $_ * 0.05 } | ForEach-Object { $sint[$_] = [Math]::sin($_) }
$cost=@{}; 0..31 | ForEach-Object { $_ * 0.05 } | ForEach-Object { $cost[$_] = [Math]::cos($_) }
$tant=@{}; 0..31 | ForEach-Object { $_ * 0.05 } | ForEach-Object { $tant[$_] = [Math]::tan($_) }
$asint=New-Object 'Double[][]' 32,2; $sint.GetEnumerator() | Sort-Object Value | ForEach-Object {$i=0}{ $asint[$i][0] = $_.Value; $asint[$i][1] = $_.Name; $i++ }
$acost=New-Object 'Double[][]' 32,2; $cost.GetEnumerator() | Sort-Object Value | ForEach-Object { $i=0 }{ $acost[$i][0] = $_.Value; $acost[$i][1] = $_.Name; $i++ }
$atant=New-Object 'Double[][]' 32,2; $tant.GetEnumerator() | Sort-Object Value | ForEach-Object {$i=0}{ $atant[$i][0] = $_.Value; $atant[$i][1] = $_.Name; $i++ }
$asin = (Thiele-Interpolation $asint)
#uncomment to see the function
#"{$asin}"
6*$asin.InvokeReturnAsIs(.5)
$acos = (Thiele-Interpolation $acost)
#uncomment to see the function
#"{$acos}"
3*$acos.InvokeReturnAsIs(.5)
$atan = (Thiele-Interpolation $atant)
#uncomment to see the function
#"{$atan}"
4*$atan.InvokeReturnAsIs(1) |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
with Ada.Text_IO; use Ada.Text_IO;
with Strings_Edit; use Strings_Edit;
with Strings_Edit.Floats; use Strings_Edit.Floats;
with Strings_Edit.Integers; use Strings_Edit.Integers;
with Generic_Map;
procedure Data_Munging_2 is
package Time_To_Line is new Generic_Map (Time, Natural);
use Time_To_Line;
File : File_Type;
Line_No : Natural := 0;
Count : Natural := 0;
Stamps : Map;
begin
Open (File, In_File, "readings.txt");
loop
declare
Line : constant String := Get_Line (File);
Pointer : Integer := Line'First;
Flag : Integer;
Year, Month, Day : Integer;
Data : Float;
Stamp : Time;
Valid : Boolean := True;
begin
Line_No := Line_No + 1;
Get (Line, Pointer, SpaceAndTab);
Get (Line, Pointer, Year);
Get (Line, Pointer, Month);
Get (Line, Pointer, Day);
Stamp := Time_Of (Year_Number (Year), Month_Number (-Month), Day_Number (-Day));
begin
Add (Stamps, Stamp, Line_No);
exception
when Constraint_Error =>
Put (Image (Year) & Image (Month) & Image (Day) & ": record at " & Image (Line_No));
Put_Line (" duplicates record at " & Image (Get (Stamps, Stamp)));
end;
Get (Line, Pointer, SpaceAndTab);
for Reading in 1..24 loop
Get (Line, Pointer, Data);
Get (Line, Pointer, SpaceAndTab);
Get (Line, Pointer, Flag);
Get (Line, Pointer, SpaceAndTab);
Valid := Valid and then Flag >= 1;
end loop;
if Pointer <= Line'Last then
Put_Line ("Unrecognized tail at " & Image (Line_No) & ':' & Image (Pointer));
elsif Valid then
Count := Count + 1;
end if;
exception
when End_Error | Data_Error | Constraint_Error | Time_Error =>
Put_Line ("Syntax error at " & Image (Line_No) & ':' & Image (Pointer));
end;
end loop;
exception
when End_Error =>
Close (File);
Put_Line ("Valid records " & Image (Count) & " of " & Image (Line_No) & " total");
end Data_Munging_2; |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #AutoHotkey | AutoHotkey | for i, x in StrSplit("Gary,Earl,Billy,Felix,Mary", ","){
BFM := false
if (SubStr(x, 1, 1) ~= "i)^[AEIOU]") ; Vowel
y := x
else if (SubStr(x, 1, 1) ~= "i)^[BFM]") ; BFM
y := SubStr(x,2), BFM := true
else
y := SubStr(x,2)
StringLower, y, y
output := X ", " X ", bo-" (SubStr(x,1,1)="b"&&BFM ? "" : "b") Y
. "`nBanana-fana fo-" (SubStr(x,1,1)="f"&&BFM ? "" : "f") Y
. "`nFee-fi-mo-" (SubStr(x,1,1)="m"&&BFM ? "" : "m") Y
. "`n" X "!"
result .= output "`n`n"
}
MsgBox, 262144, ,% result |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Python | Python | #!/usr/bin/env python3
import math
def thieleInterpolator(x, y):
ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]
for i in range(len(ρ)-1):
ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
for i in range(2, len(ρ)):
for j in range(len(ρ)-i):
ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
ρ0 = ρ[0]
def t(xin):
a = 0
for i in range(len(ρ0)-1, 1, -1):
a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
return y[0] + (xin-x[0]) / (ρ0[1]+a)
return t
# task 1: build 32 row trig table
xVal = [i*.05 for i in range(32)]
tSin = [math.sin(x) for x in xVal]
tCos = [math.cos(x) for x in xVal]
tTan = [math.tan(x) for x in xVal]
# task 2: define inverses
iSin = thieleInterpolator(tSin, xVal)
iCos = thieleInterpolator(tCos, xVal)
iTan = thieleInterpolator(tTan, xVal)
# task 3: demonstrate identities
print('{:16.14f}'.format(6*iSin(.5)))
print('{:16.14f}'.format(3*iCos(.5)))
print('{:16.14f}'.format(4*iTan(1))) |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Aime | Aime | check_format(list l)
{
integer i;
text s;
if (~l != 49) {
error("bad field count");
}
s = l[0];
if (match("????-??-??", s)) {
error("bad date format");
}
l[0] = s.delete(7).delete(4).atoi;
i = 1;
while (i < 49) {
atof(l[i]);
i += 1;
l[i >> 1] = atoi(l[i]);
i += 1;
}
l.erase(25, -1);
}
main(void)
{
integer goods, i, v;
file f;
list l;
index x;
goods = 0;
f.affix("readings.txt");
while (f.list(l, 0) != -1) {
if (!trap(check_format, l)) {
if ((x[v = lf_x_integer(l)] += 1) != 1) {
v_form("duplicate ~ line\n", v);
}
i = 1;
l.ucall(min_i, 1, i);
goods += iclip(0, i, 1);
}
}
o_(goods, " good lines\n");
0;
} |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #AWK | AWK |
# syntax: GAWK -f THE_NAME_GAME.AWK
BEGIN {
n = split("gary,earl,billy,felix,mary,shirley",arr,",")
for (i=1; i<=n; i++) {
print_verse(arr[i])
}
exit(0)
}
function print_verse(name, c,x,y) {
x = toupper(substr(name,1,1)) tolower(substr(name,2))
y = (x ~ /^[AEIOU]/) ? tolower(x) : substr(x,2)
c = substr(x,1,1)
printf("%s, %s, bo-%s%s\n",x,x,(c~/B/)?"":"b",y)
printf("Banana-fana fo-%s%s\n",(c~/F/)?"":"f",y)
printf("Fee-fi-mo-%s%s\n",(c~/M/)?"":"m",y)
printf("%s!\n\n",x)
}
|
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | [Char = String] CH2NUM
L(chars) ‘abc def ghi jkl mno pqrs tuv wxyz’.split(‘ ’)
V num = L.index + 2
L(ch) chars
CH2NUM[ch] = String(num)
F mapnum2words(words)
DefaultDict[String, [String]] number2words
V reject = 0
L(word) words
X.try
number2words[word.map(ch -> :CH2NUM[ch]).join(‘’)].append(word)
X.catch KeyError
reject++
R (number2words, reject)
V words = File(‘unixdict.txt’).read().rtrim("\n").split("\n")
print(‘Read #. words from 'unixdict.txt'’.format(words.len))
V wordset = Set(words)
V (num2words, reject) = mapnum2words(words)
F interactiveconversions()
L(inp) (‘rosetta’, ‘code’, ‘2468’, ‘3579’)
print("\nType a number or a word to get the translation and textonyms: "inp)
I all(inp.map(ch -> ch C ‘23456789’))
I inp C :num2words
print(‘ Number #. has the following textonyms in the dictionary: #.’.format(inp, (:num2words[inp]).join(‘, ’)))
E
print(‘ Number #. has no textonyms in the dictionary.’.format(inp))
E I all(inp.map(ch -> ch C :CH2NUM))
V num = inp.map(ch -> :CH2NUM[ch]).join(‘’)
print(‘ Word #. is#. in the dictionary and is number #. with textonyms: #.’.format(inp, (I inp C :wordset {‘’} E ‘n't’), num, (:num2words[num]).join(‘, ’)))
E
print(‘ I don't understand '#.'’.format(inp))
V morethan1word = sum(num2words.keys().filter(w -> :num2words[w].len > 1).map(w -> 1))
V maxwordpernum = max(num2words.values().map(values -> values.len))
print(‘
There are #. words in #. which can be represented by the Textonyms mapping.
They require #. digit combinations to represent them.
#. digit combinations represent Textonyms.’.format(words.len - reject, ‘'unixdict.txt'’, num2words.len, morethan1word))
print("\nThe numbers mapping to the most words map to #. words each:".format(maxwordpernum))
V maxwpn = sorted(num2words.filter((key, val) -> val.len == :maxwordpernum))
L(num, wrds) maxwpn
print(‘ #. maps to: #.’.format(num, wrds.join(‘, ’)))
interactiveconversions() |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Racket | Racket |
#lang racket
(define xs (for/vector ([x (in-range 0.0 1.6 0.05)]) x))
(define (x i) (vector-ref xs i))
(define-syntax define-table
(syntax-rules ()
[(_ f tf rf if)
(begin (define tab (for/vector ([x xs]) (f x)))
(define (tf n) (vector-ref tab n))
(define cache (make-vector (/ (* 32 31) 2) #f))
(define (rf n thunk)
(or (vector-ref cache n)
(let ([v (thunk)])
(vector-set! cache n v)
v)))
(define (if t) (thiele tf x rf t 0)))]))
(define-table sin tsin rsin isin)
(define-table cos tcos rcos icos)
(define-table tan ttan rtan itan)
(define (rho x y r i n)
(cond
[(< n 0) 0]
[(= n 0) (y i)]
[else (r (+ (/ (* (- 32 1 n) (- 32 n)) 2) i)
(λ() (+ (/ (- (x i) (x (+ i n)))
(- (rho x y r i (- n 1)) (rho x y r (+ i 1) (- n 1))))
(rho x y r (+ i 1) (- n 2)))))]))
(define (thiele x y r xin n)
(cond
[(> n 31) 1]
[(+ (rho x y r 0 n) (- (rho x y r 0 (- n 2)))
(/ (- xin (x n)) (thiele x y r xin (+ n 1))))]))
(* 6 (isin 0.5))
(* 3 (icos 0.5))
(* 4 (itan 1.))
|
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #AutoHotkey | AutoHotkey | ; Author: AlephX Aug 17 2011
data = %A_scriptdir%\readings.txt
Loop, Read, %data%
{
Lines := A_Index
StringReplace, dummy, A_LoopReadLine, %A_Tab%,, All UseErrorLevel
Loop, parse, A_LoopReadLine, %A_Tab%
{
wrong := 0
if A_index = 1
{
Date := A_LoopField
if (Date == OldDate)
{
WrongDates = %WrongDates%%OldDate% at %Lines%`n
TotwrongDates++
Wrong := 1
break
}
}
else
{
if (A_loopfield/1 < 0)
{
Wrong := 1
break
}
}
}
if (wrong == 1)
totwrong++
else
valid++
if (errorlevel <> 48)
{
if (wrong == 0)
{
totwrong++
valid--
}
unvalidformat++
}
olddate := date
}
msgbox, Duplicate Dates:`n%wrongDates%`nRead Lines: %lines%`nValid Lines: %valid%`nwrong lines: %totwrong%`nDuplicates: %TotWrongDates%`nWrong Formatted: %unvalidformat%`n
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #BASIC256 | BASIC256 | subroutine TheGameName(nombre)
x = lower(nombre)
x = upper(mid(x,1,1)) + (mid(x,2,length(x)-1))
x0 = upper(mid(x,1,1))
if x0 = "A" or x0 = "e" or x0 = "I" or x0 = "O" or x0 = "U" then
y = lower(x)
else
y = mid(x,2,length(x)-1)
end If
b = "b" + y
f = "f" + y
m = "m" + y
begin case
case x0 = "B"
b = y
case x0 = "F"
f = y
case x0 = "M"
m = y
end case
print x + ", " + x + ", bo-" + b
print "Banana-fana fo-" + f
print "Fee-fi-mo-" + m
print x + "!" + chr(10)
end subroutine
dim listanombres[5]
listanombres = {"Gary", "EARL", "billy", "FeLiX", "Mary", "ShirleY"}
for i = 0 to listanombres[?]-1
call TheGameName(listanombres[i])
next i
end |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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 | C | #include <stdio.h>
#include <string.h>
void print_verse(const char *name) {
char *x, *y;
int b = 1, f = 1, m = 1, i = 1;
/* ensure name is in title-case */
x = strdup(name);
x[0] = toupper(x[0]);
for (; x[i]; ++i) x[i] = tolower(x[i]);
if (strchr("AEIOU", x[0])) {
y = strdup(x);
y[0] = tolower(y[0]);
}
else {
y = x + 1;
}
switch(x[0]) {
case 'B': b = 0; break;
case 'F': f = 0; break;
case 'M': m = 0; break;
default : break;
}
printf("%s, %s, bo-%s%s\n", x, x, (b) ? "b" : "", y);
printf("Banana-fana fo-%s%s\n", (f) ? "f" : "", y);
printf("Fee-fi-mo-%s%s\n", (m) ? "m" : "", y);
printf("%s!\n\n", x);
}
int main() {
int i;
const char *names[6] = {"gARY", "Earl", "Billy", "Felix", "Mary", "sHIRley"};
for (i = 0; i < 6; ++i) print_verse(names[i]);
return 0;
} |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | # find textonyms in a list of words #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
# returns the number of occurances of ch in text #
PROC count = ( STRING text, CHAR ch )INT:
BEGIN
INT result := 0;
FOR c FROM LWB text TO UPB text DO IF text[ c ] = ch THEN result +:= 1 FI OD;
result
END # count # ;
CHAR invalid char = "*";
# returns text with the characters replaced by their text digits #
PROC to text = ( STRING text )STRING:
BEGIN
STRING result := text;
FOR pos FROM LWB result TO UPB result DO
CHAR c = to upper( result[ pos ] );
IF c = "A" OR c = "B" OR c = "C" THEN result[ pos ] := "2"
ELIF c = "D" OR c = "E" OR c = "F" THEN result[ pos ] := "3"
ELIF c = "G" OR c = "H" OR c = "I" THEN result[ pos ] := "4"
ELIF c = "J" OR c = "K" OR c = "L" THEN result[ pos ] := "5"
ELIF c = "M" OR c = "N" OR c = "O" THEN result[ pos ] := "6"
ELIF c = "P" OR c = "Q" OR c = "R" OR c = "S" THEN result[ pos ] := "7"
ELIF c = "T" OR c = "U" OR c = "V" THEN result[ pos ] := "8"
ELIF c = "W" OR c = "X" OR c = "Y" OR c = "Z" THEN result[ pos ] := "9"
ELSE # not a character that can be encoded # result[ pos ] := invalid char
FI
OD;
result
END # to text # ;
# read the list of words and store in an associative array #
CHAR separator = "/"; # character that will separate the textonyms #
IF FILE input file;
STRING file name = "unixdict.txt";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
# set the EOF handler for the file #
on logical file end( input file, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the #
# latest read #
at eof := TRUE;
# return TRUE so processing can continue #
TRUE
END
);
REF AARRAY words := INIT LOC AARRAY;
INT word count := 0;
INT combinations := 0;
INT multiple count := 0;
INT max length := 0;
WHILE STRING word;
get( input file, ( word, newline ) );
NOT at eof
DO
STRING text word = to text( word );
IF count( text word, invalid char ) = 0 THEN
# the word can be fully encoded #
word count +:= 1;
INT length := ( UPB word - LWB word ) + 1;
IF length > max length THEN
# this word is longer than the maximum length found so far #
max length := length
FI;
IF ( words // text word ) = "" THEN
# first occurance of this encoding #
combinations +:= 1;
words // text word := word
ELSE
# this encoding has already been used #
IF count( words // text word, separator ) = 0
THEN
# this is the second time this encoding is used #
multiple count +:= 1
FI;
words // text word +:= separator + word
FI
FI
OD;
# close the file #
close( input file );
# find the maximum number of textonyms #
INT max textonyms := 0;
REF AAELEMENT e := FIRST words;
WHILE e ISNT nil element DO
INT textonyms := count( value OF e, separator );
IF textonyms > max textonyms
THEN
max textonyms := textonyms
FI;
e := NEXT words
OD;
print( ( "There are ", whole( word count, 0 ), " words in ", file name, " which can be represented by the digit key mapping.", newline ) );
print( ( "They require ", whole( combinations, 0 ), " digit combinations to represent them.", newline ) );
print( ( whole( multiple count, 0 ), " combinations represent Textonyms.", newline ) );
# show the textonyms with the maximum number #
print( ( "The maximum number of textonyms for a particular digit key mapping is ", whole( max textonyms + 1, 0 ), " as follows:", newline ) );
e := FIRST words;
WHILE e ISNT nil element DO
IF INT textonyms := count( value OF e, separator );
textonyms = max textonyms
THEN
print( ( " ", key OF e, " encodes ", value OF e, newline ) )
FI;
e := NEXT words
OD;
# show the textonyms with the maximum length #
print( ( "The longest words are ", whole( max length, 0 ), " chracters long", newline ) );
print( ( "Encodings with this length are:", newline ) );
e := FIRST words;
WHILE e ISNT nil element DO
IF max length = ( UPB key OF e - LWB key OF e ) + 1
THEN
print( ( " ", key OF e, " encodes ", value OF e, newline ) )
FI;
e := NEXT words
OD;
FI
|
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Raku | Raku | # reciprocal difference:
multi sub ρ(&f, @x where * < 1) { 0 } # Identity
multi sub ρ(&f, @x where * == 1) { &f(@x[0]) }
multi sub ρ(&f, @x where * > 1) {
( @x[0] - @x[* - 1] ) # ( x - x[n] )
/ (ρ(&f, @x[^(@x - 1)]) # / ( ρ[n-1](x[0], ..., x[n-1])
- ρ(&f, @x[1..^@x]) ) # - ρ[n-1](x[1], ..., x[n]) )
+ ρ(&f, @x[1..^(@x - 1)]); # + ρ[n-2](x[1], ..., x[n-1])
}
# Thiele:
multi sub thiele($x, %f, $ord where { $ord == +%f }) { 1 } # Identity
multi sub thiele($x, %f, $ord) {
my &f = {%f{$^a}}; # f(x) as a table lookup
# must sort hash keys to maintain order between invocations
my $a = ρ(&f, %f.keys.sort[^($ord +1)]);
my $b = ρ(&f, %f.keys.sort[^($ord -1)]);
my $num = $x - %f.keys.sort[$ord];
my $cont = thiele($x, %f, $ord +1);
# Thiele always takes this form:
return $a - $b + ( $num / $cont );
}
## Demo
sub mk-inv(&fn, $d, $lim) {
my %h;
for 0..$lim { %h{ &fn($_ * $d) } = $_ * $d }
return %h;
}
sub MAIN($tblsz = 12) {
my ($sin_pi, $cos_pi, $tan_pi);
my $p1 = Promise.start( { my %invsin = mk-inv(&sin, 0.05, $tblsz); $sin_pi = 6 * thiele(0.5, %invsin, 0) } );
my $p2 = Promise.start( { my %invcos = mk-inv(&cos, 0.05, $tblsz); $cos_pi = 3 * thiele(0.5, %invcos, 0) } );
my $p3 = Promise.start( { my %invtan = mk-inv(&tan, 0.05, $tblsz); $tan_pi = 4 * thiele(1.0, %invtan, 0) } );
await $p1, $p2, $p3;
say "pi = {pi}";
say "estimations using a table of $tblsz elements:";
say "sin interpolation: $sin_pi";
say "cos interpolation: $cos_pi";
say "tan interpolation: $tan_pi";
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #AWK | AWK | bash$ awk '/[eE]/' readings.txt
bash$ |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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.23 | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace TheNameGame {
class Program {
static void PrintVerse(string name) {
StringBuilder sb = new StringBuilder(name.ToLower());
sb[0] = Char.ToUpper(sb[0]);
string x = sb.ToString();
string y = "AEIOU".IndexOf(x[0]) > -1 ? x.ToLower() : x.Substring(1);
string b = "b" + y;
string f = "f" + y;
string m = "m" + y;
switch (x[0]) {
case 'B':
b = y;
break;
case 'F':
f = y;
break;
case 'M':
m = y;
break;
}
Console.WriteLine("{0}, {0}, bo-{1}", x, b);
Console.WriteLine("Banana-fana fo-{0}", f);
Console.WriteLine("Fee-fi-mo-{0}", m);
Console.WriteLine("{0}!", x);
Console.WriteLine();
}
static void Main(string[] args) {
List<string> nameList = new List<string>() { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" };
nameList.ForEach(PrintVerse);
}
}
} |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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 | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
char text_char(char c) {
switch (c) {
case 'a': case 'b': case 'c':
return '2';
case 'd': case 'e': case 'f':
return '3';
case 'g': case 'h': case 'i':
return '4';
case 'j': case 'k': case 'l':
return '5';
case 'm': case 'n': case 'o':
return '6';
case 'p': case 'q': case 'r': case 's':
return '7';
case 't': case 'u': case 'v':
return '8';
case 'w': case 'x': case 'y': case 'z':
return '9';
default:
return 0;
}
}
bool text_string(const GString* word, GString* text) {
g_string_set_size(text, word->len);
for (size_t i = 0; i < word->len; ++i) {
char c = text_char(g_ascii_tolower(word->str[i]));
if (c == 0)
return false;
text->str[i] = c;
}
return true;
}
typedef struct textonym_tag {
const char* text;
size_t length;
GPtrArray* words;
} textonym_t;
int compare_by_text_length(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->length > t2->length)
return -1;
if (t1->length < t2->length)
return 1;
return strcmp(t1->text, t2->text);
}
int compare_by_word_count(const void* p1, const void* p2) {
const textonym_t* t1 = p1;
const textonym_t* t2 = p2;
if (t1->words->len > t2->words->len)
return -1;
if (t1->words->len < t2->words->len)
return 1;
return strcmp(t1->text, t2->text);
}
void print_words(GPtrArray* words) {
for (guint i = 0, n = words->len; i < n; ++i) {
if (i > 0)
printf(", ");
printf("%s", g_ptr_array_index(words, i));
}
printf("\n");
}
void print_top_words(GArray* textonyms, guint top) {
for (guint i = 0; i < top; ++i) {
const textonym_t* t = &g_array_index(textonyms, textonym_t, i);
printf("%s = ", t->text);
print_words(t->words);
}
}
void free_strings(gpointer ptr) {
g_ptr_array_free(ptr, TRUE);
}
bool find_textonyms(const char* filename, GError** error_ptr) {
GError* error = NULL;
GIOChannel* channel = g_io_channel_new_file(filename, "r", &error);
if (channel == NULL) {
g_propagate_error(error_ptr, error);
return false;
}
GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, free_strings);
GString* word = g_string_sized_new(64);
GString* text = g_string_sized_new(64);
guint count = 0;
gsize term_pos;
while (g_io_channel_read_line_string(channel, word, &term_pos,
&error) == G_IO_STATUS_NORMAL) {
g_string_truncate(word, term_pos);
if (!text_string(word, text))
continue;
GPtrArray* words = g_hash_table_lookup(ht, text->str);
if (words == NULL) {
words = g_ptr_array_new_full(1, g_free);
g_hash_table_insert(ht, g_strdup(text->str), words);
}
g_ptr_array_add(words, g_strdup(word->str));
++count;
}
g_io_channel_unref(channel);
g_string_free(word, TRUE);
g_string_free(text, TRUE);
if (error != NULL) {
g_propagate_error(error_ptr, error);
g_hash_table_destroy(ht);
return false;
}
GArray* words = g_array_new(FALSE, FALSE, sizeof(textonym_t));
GHashTableIter iter;
gpointer key, value;
g_hash_table_iter_init(&iter, ht);
while (g_hash_table_iter_next(&iter, &key, &value)) {
GPtrArray* v = value;
if (v->len > 1) {
textonym_t textonym;
textonym.text = key;
textonym.length = strlen(key);
textonym.words = v;
g_array_append_val(words, textonym);
}
}
printf("There are %u words in '%s' which can be represented by the digit key mapping.\n",
count, filename);
guint size = g_hash_table_size(ht);
printf("They require %u digit combinations to represent them.\n", size);
guint textonyms = words->len;
printf("%u digit combinations represent Textonyms.\n", textonyms);
guint top = 5;
if (textonyms < top)
top = textonyms;
printf("\nTop %u by number of words:\n", top);
g_array_sort(words, compare_by_word_count);
print_top_words(words, top);
printf("\nTop %u by length:\n", top);
g_array_sort(words, compare_by_text_length);
print_top_words(words, top);
g_array_free(words, TRUE);
g_hash_table_destroy(ht);
return true;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage: %s word-list\n", argv[0]);
return EXIT_FAILURE;
}
GError* error = NULL;
if (!find_textonyms(argv[1], &error)) {
if (error != NULL) {
fprintf(stderr, "%s: %s\n", argv[1], error->message);
g_error_free(error);
}
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #11l | 11l | V out = 0
V max_out = -1
[String] max_times
L(job) File(‘mlijobs.txt’).read_lines()
out += I ‘OUT’ C job {1} E -1
I out > max_out
max_out = out
max_times.clear()
I out == max_out
max_times.append(job.split(‘ ’)[3])
print(‘Maximum simultaneous license use is #. at the following times:’.format(max_out))
print(‘ ’max_times.join("\n ")) |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Rust | Rust |
const N: usize = 32;
const STEP: f64 = 0.05;
fn main() {
let x: Vec<f64> = (0..N).map(|i| i as f64 * STEP).collect();
let sin = x.iter().map(|x| x.sin()).collect::<Vec<_>>();
let cos = x.iter().map(|x| x.cos()).collect::<Vec<_>>();
let tan = x.iter().map(|x| x.tan()).collect::<Vec<_>>();
println!(
"{}\n{}\n{}",
6. * thiele(&sin, &x, 0.5),
3. * thiele(&cos, &x, 0.5),
4. * thiele(&tan, &x, 1.)
);
}
fn thiele(x: &[f64], y: &[f64], xin: f64) -> f64 {
let mut p: Vec<Vec<f64>> = (0..N).map(|i| (i..N).map(|_| 0.0).collect()).collect();
(0..N).for_each(|i| p[i][0] = y[i]);
(0..N - 1).for_each(|i| p[i][1] = (x[i] - x[i + 1]) / (p[i][0] - p[i + 1][0]));
(2..N).for_each(|i| {
(0..N - i).for_each(|j| {
p[j][i] = (x[j] - x[j + i]) / (p[j][i - 1] - p[j + 1][i - 1]) + p[j + 1][i - 2];
})
});
let mut a = 0.;
(2..N).rev().for_each(|i| {
a = (xin - x[i - 1]) / (p[0][i] - p[0][i - 2] + a);
});
y[0] + (xin - x[0]) / (p[0][1] + a)
}
|
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Sidef | Sidef | func thiele(x, y) {
var ρ = {|i| [y[i]]*(y.len-i) }.map(^y)
for i in ^(ρ.end) {
ρ[i][1] = ((x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]))
}
for i (2 .. ρ.end) {
for j (0 .. ρ.end-i) {
ρ[j][i] = (((x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1])) + ρ[j+1][i-2])
}
}
var ρ0 = ρ[0]
func t(xin) {
var a = 0
for i (ρ0.len ^.. 2) {
a = ((xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a))
}
y[0] + ((xin-x[0]) / (ρ0[1]+a))
}
return t
}
# task 1: build 32 row trig table
var xVal = {|k| k * 0.05 }.map(^32)
var tSin = xVal.map { .sin }
var tCos = xVal.map { .cos }
var tTan = xVal.map { .tan }
# task 2: define inverses
var iSin = thiele(tSin, xVal)
var iCos = thiele(tCos, xVal)
var iTan = thiele(tTan, xVal)
# task 3: demonstrate identities
say 6*iSin(0.5)
say 3*iCos(0.5)
say 4*iTan(1) |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #C | C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
typedef struct { const char *s; int ln, bad; } rec_t;
int cmp_rec(const void *aa, const void *bb)
{
const rec_t *a = aa, *b = bb;
return a->s == b->s ? 0 : !a->s ? 1 : !b->s ? -1 : strncmp(a->s, b->s, 10);
}
int read_file(const char *fn)
{
int fd = open(fn, O_RDONLY);
if (fd == -1) return 0;
struct stat s;
fstat(fd, &s);
char *txt = malloc(s.st_size);
read(fd, txt, s.st_size);
close(fd);
int i, j, lines = 0, k, di, bad;
for (i = lines = 0; i < s.st_size; i++)
if (txt[i] == '\n') {
txt[i] = '\0';
lines++;
}
rec_t *rec = calloc(sizeof(rec_t), lines);
const char *ptr, *end;
rec[0].s = txt;
rec[0].ln = 1;
for (i = 0; i < lines; i++) {
if (i + 1 < lines) {
rec[i + 1].s = rec[i].s + strlen(rec[i].s) + 1;
rec[i + 1].ln = i + 2;
}
if (sscanf(rec[i].s, "%4d-%2d-%2d", &di, &di, &di) != 3) {
printf("bad line %d: %s\n", i, rec[i].s);
rec[i].s = 0;
continue;
}
ptr = rec[i].s + 10;
for (j = k = 0; j < 25; j++) {
if (!strtod(ptr, (char**)&end) && end == ptr) break;
k++, ptr = end;
if (!(di = strtol(ptr, (char**)&end, 10)) && end == ptr) break;
k++, ptr = end;
if (di < 1) rec[i].bad = 1;
}
if (k != 48) {
printf("bad format at line %d: %s\n", i, rec[i].s);
rec[i].s = 0;
}
}
qsort(rec, lines, sizeof(rec_t), cmp_rec);
for (i = 1, bad = rec[0].bad, j = 0; i < lines && rec[i].s; i++) {
if (rec[i].bad) bad++;
if (strncmp(rec[i].s, rec[j].s, 10)) {
j = i;
} else
printf("dup line %d: %.10s\n", rec[i].ln, rec[i].s);
}
free(rec);
free(txt);
printf("\n%d out %d lines good\n", lines - bad, lines);
return 0;
}
int main()
{
read_file("readings.txt");
return 0;
} |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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 <algorithm>
#include <iostream>
#include <string>
#include <vector>
static void printVerse(const std::string& name) {
std::string x = name;
std::transform(x.begin(), x.end(), x.begin(), ::tolower);
x[0] = toupper(x[0]);
std::string y;
switch (x[0]) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
y = x;
std::transform(y.begin(), y.end(), y.begin(), ::tolower);
break;
default:
y = x.substr(1);
break;
}
std::string b("b" + y);
std::string f("f" + y);
std::string m("m" + y);
switch (x[0]) {
case 'B':
b = y;
break;
case 'F':
f = y;
break;
case 'M':
m = y;
break;
default:
break;
}
printf("%s, %s, bo-%s\n", x.c_str(), x.c_str(), b.c_str());
printf("Banana-fana fo-%s\n", f.c_str());
printf("Fee-fi-mo-%s\n", m.c_str());
printf("%s!\n\n", x.c_str());
}
int main() {
using namespace std;
vector<string> nameList{ "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" };
for (auto& name : nameList) {
printVerse(name);
}
return 0;
} |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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 <fstream>
#include <iostream>
#include <unordered_map>
#include <vector>
struct Textonym_Checker {
private:
int total;
int elements;
int textonyms;
int max_found;
std::vector<std::string> max_strings;
std::unordered_map<std::string, std::vector<std::string>> values;
int get_mapping(std::string &result, const std::string &input)
{
static std::unordered_map<char, char> mapping = {
{'A', '2'}, {'B', '2'}, {'C', '2'},
{'D', '3'}, {'E', '3'}, {'F', '3'},
{'G', '4'}, {'H', '4'}, {'I', '4'},
{'J', '5'}, {'K', '5'}, {'L', '5'},
{'M', '6'}, {'N', '6'}, {'O', '6'},
{'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'},
{'T', '8'}, {'U', '8'}, {'V', '8'},
{'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'}
};
result = input;
for (char &c : result) {
if (!isalnum(c)) return 0;
if (isalpha(c)) c = mapping[toupper(c)];
}
return 1;
}
public:
Textonym_Checker() : total(0), elements(0), textonyms(0), max_found(0) { }
~Textonym_Checker() { }
void add(const std::string &str) {
std::string mapping;
total++;
if (!get_mapping(mapping, str)) return;
const int num_strings = values[mapping].size();
if (num_strings == 1) textonyms++;
elements++;
if (num_strings > max_found) {
max_strings.clear();
max_strings.push_back(mapping);
max_found = num_strings;
}
else if (num_strings == max_found)
max_strings.push_back(mapping);
values[mapping].push_back(str);
}
void results(const std::string &filename) {
std::cout << "Read " << total << " words from " << filename << "\n\n";
std::cout << "There are " << elements << " words in " << filename;
std::cout << " which can be represented by the digit key mapping.\n";
std::cout << "They require " << values.size() <<
" digit combinations to represent them.\n";
std::cout << textonyms << " digit combinations represent Textonyms.\n\n";
std::cout << "The numbers mapping to the most words map to ";
std::cout << max_found + 1 << " words each:\n";
for (auto it1 : max_strings) {
std::cout << '\t' << it1 << " maps to: ";
for (auto it2 : values[it1])
std::cout << it2 << " ";
std::cout << '\n';
}
std::cout << '\n';
}
void match(const std::string &str) {
auto match = values.find(str);
if (match == values.end()) {
std::cout << "Key '" << str << "' not found\n";
}
else {
std::cout << "Key '" << str << "' matches: ";
for (auto it : values[str])
std::cout << it << " ";
std::cout << '\n';
}
}
};
int main()
{
auto filename = "unixdict.txt";
std::ifstream input(filename);
Textonym_Checker tc;
if (input.is_open()) {
std::string line;
while (getline(input, line))
tc.add(line);
}
input.close();
tc.results(filename);
tc.match("001");
tc.match("228");
tc.match("27484247");
tc.match("7244967473642");
} |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Ada | Ada | -- licenselist.adb --
-- run under GPS 4.3-5 (Sidux/Debian)
-- process rosetta.org text_processing/3 example
-- uses linked-list to hold times
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded,
Ada.Strings.Unbounded.Text_IO,
Ada.Containers.Doubly_Linked_Lists;
use Ada.Text_IO, Ada.Integer_Text_IO,
Ada.Strings.Unbounded, Ada.Strings.Unbounded.Text_IO,
Ada.Containers;
procedure licenselist is
type logrec is record -- define a record 'logrec' to place in a list
logtext : String(1..19);
end record;
package dblist is new Doubly_Linked_Lists(logrec);
use dblist;
-- declare dblist as a list of logrec's
licenselog : list;
logtime : logrec;
-- to record the time of max OUT licenses
infile : File_Type; -- file handle
str : Unbounded_String; -- input string buffer of unknown length
outcnt, maxoutcnt : integer := 0;
infilename : string := "license.log";
procedure trace_times is
-- loop thru times list and print
pntr : cursor := licenselog.first;
-- pntr is of system type cursor reference to local list 'licenselog'
begin
new_line;
while has_element(pntr) loop
put(element(pntr).logtext); new_line;
next(pntr);
end loop;
end trace_times;
begin -- main program --
open ( infile,
mode=> in_file,
name=> infilename );
loop
exit when End_of_file ( infile );
str := get_line( infile );
if index( str, "OUT" ) > 0 then -- test if OUT record
outcnt := outcnt +1;
else -- else assume IN record
outcnt := outcnt -1;
end if;
if outcnt > maxoutcnt then
maxoutcnt := outcnt;
logtime.logtext := slice(str,15,33); -- date_time field
licenselog.clear; -- reset list for new time(s)
licenselog.append (logtime); -- put current time into list
elsif outcnt = maxoutcnt then
logtime.logtext := slice(str,15,33); -- date_time field
licenselog.append (logtime); -- add current time into list
end if; -- have to account for possibility of equal number of OUT's
end loop;
put("The max. number of licenses OUT is ");put(maxoutcnt,5); new_line;
put(" at these times ");
trace_times;
close ( infile );
end licenselist; |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Swift | Swift | let N = 32
let N2 = N * (N - 1) / 2
let step = 0.05
var xval = [Double](repeating: 0, count: N)
var tsin = [Double](repeating: 0, count: N)
var tcos = [Double](repeating: 0, count: N)
var ttan = [Double](repeating: 0, count: N)
var rsin = [Double](repeating: .nan, count: N2)
var rcos = [Double](repeating: .nan, count: N2)
var rtan = [Double](repeating: .nan, count: N2)
func rho(_ x: [Double], _ y: [Double], _ r: inout [Double], _ i: Int, _ n: Int) -> Double {
guard n >= 0 else {
return 0
}
guard n != 0 else {
return y[i]
}
let idx = (N - 1 - n) * (N - n) / 2 + i
if r[idx] != r[idx] {
r[idx] = (x[i] - x[i + n]) /
(rho(x, y, &r, i, n - 1) - rho(x, y, &r, i + 1, n - 1)) + rho(x, y, &r, i + 1, n - 2)
}
return r[idx]
}
func thiele(_ x: [Double], _ y: [Double], _ r: inout [Double], _ xin: Double, _ n: Int) -> Double {
guard n <= N - 1 else {
return 1
}
return rho(x, y, &r, 0, n) - rho(x, y, &r, 0, n - 2) + (xin - x[n]) / thiele(x, y, &r, xin, n + 1)
}
for i in 0..<N {
xval[i] = Double(i) * step
tsin[i] = sin(xval[i])
tcos[i] = cos(xval[i])
ttan[i] = tsin[i] / tcos[i]
}
print(String(format: "%16.14f", 6 * thiele(tsin, xval, &rsin, 0.5, 0)))
print(String(format: "%16.14f", 3 * thiele(tcos, xval, &rcos, 0.5, 0)))
print(String(format: "%16.14f", 4 * thiele(ttan, xval, &rtan, 1.0, 0)))
|
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
namespace TextProc2
{
class Program
{
static void Main(string[] args)
{
Regex multiWhite = new Regex(@"\s+");
Regex dateEx = new Regex(@"^\d{4}-\d{2}-\d{2}$");
Regex valEx = new Regex(@"^\d+\.{1}\d{3}$");
Regex flagEx = new Regex(@"^[1-9]{1}$");
int missformcount = 0, totalcount = 0;
Dictionary<int, string> dates = new Dictionary<int, string>();
using (StreamReader sr = new StreamReader("readings.txt"))
{
string line = sr.ReadLine();
while (line != null)
{
line = multiWhite.Replace(line, @" ");
string[] splitLine = line.Split(' ');
if (splitLine.Length != 49)
missformcount++;
if (!dateEx.IsMatch(splitLine[0]))
missformcount++;
else
dates.Add(totalcount + 1, dateEx.Match(splitLine[0]).ToString());
int err = 0;
for (int i = 1; i < splitLine.Length; i++)
{
if (i%2 != 0)
{
if (!valEx.IsMatch(splitLine[i]))
err++;
}
else
{
if (!flagEx.IsMatch(splitLine[i]))
err++;
}
}
if (err != 0) missformcount++;
line = sr.ReadLine();
totalcount++;
}
}
int goodEntries = totalcount - missformcount;
Dictionary<string,List<int>> dateReverse = new Dictionary<string,List<int>>();
foreach (KeyValuePair<int, string> kvp in dates)
{
if (!dateReverse.ContainsKey(kvp.Value))
dateReverse[kvp.Value] = new List<int>();
dateReverse[kvp.Value].Add(kvp.Key);
}
Console.WriteLine(goodEntries + " valid Records out of " + totalcount);
foreach (KeyValuePair<string, List<int>> kvp in dateReverse)
{
if (kvp.Value.Count > 1)
Console.WriteLine("{0} is duplicated at Lines : {1}", kvp.Key, string.Join(",", kvp.Value));
}
}
}
} |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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 name game
2 rem rosetta code
5 dim cn$(3),bl$(3,32):gosub 1000
10 print chr$(147);chr$(14);"Name Game":print
15 cn$(0)="":cn$(1)="b":cn$(2)="f":cn$(3)="m"
20 print chr$(147);chr$(14);"Name Game":print:input "Enter any name";n$
25 rem ensure first letter is lowercase
30 n$=chr$(asc(n$) and 95)+right$(n$,len(n$)-1)
35 rem check vowels
40 v$="aeiou":i$=left$(n$,1):v=0
45 for i=1 to 5:v=i$=mid$(v$,i,1):if not v then next i
50 if v then tn$=n$:goto 70
55 gosub 500
60 if bl then goto 70
65 tn$=right$(n$,len(n$)-1):gosub 600
70 rem capitalize first letter in name
75 n$=chr$(asc(n$) or 128)+right$(n$,len(n$)-1)
80 gosub 700
83 print:print "Again? (Y/N)"
85 get k$:if k$<>"y" and k$<>"n" then 85
90 if k$="y" then goto 10
95 end
500 rem check blends
510 bl=0:for g=3 to 1 step -1
520 l$=left$(n$,g+1):tn$=right$(n$,len(n$)-(g+1))
530 for i=1 to 32:if l$=bl$(g,i) then bl=-1:return
540 next i:next g
550 return
600 rem check b, f, and m
610 for i=1 to 3:if cn$(i)=chr$(asc(n$)) then cn$(i)=""
620 next i:return
700 rem sing the verse
710 print:print n$;", ";n$;", bo-";cn$(1);tn$
720 print " Banana-fana fo-";cn$(2);tn$
730 print " Fee-fi-mo-";cn$(3);tn$
740 print n$;"!"
750 return
1000 rem load blends
1010 for g=1 to 3
1015 for i=1 to 32
1020 read bl$(g,i):if bl$(g,i)="xx" then next g:return
1030 next i
2000 rem digraphs
2005 data bl,br,ch,ck,cl,cr,dr,fl,fr,gh,gl,gr,ng
2010 data ph,pl,pr,qu,sc,sh,sk,sl,sm,sn,sp,st,sw
2020 data th,tr,tw,wh,wr
2029 data xx
2030 rem trigraphs
2040 data chr,sch,scr,shr,spl,spr,squ,str,thr
2049 data xx
2050 rem quadgraph
2060 data schr,schl
2069 data xx |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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
| #Clojure | Clojure |
(def table
{\a 2 \b 2 \c 2 \A 2 \B 2 \C 2
\d 3 \e 3 \f 3 \D 3 \E 3 \F 3
\g 4 \h 4 \i 4 \G 4 \H 4 \I 4
\j 5 \k 5 \l 5 \J 5 \K 5 \L 5
\m 6 \n 6 \o 6 \M 6 \N 6 \O 6
\p 7 \q 7 \r 7 \s 7 \P 7 \Q 7 \R 7 \S 7
\t 8 \u 8 \v 8 \T 8 \U 8 \V 8
\w 9 \x 9 \y 9 \z 9 \W 9 \X 9 \Y 9 \Z 9})
(def words-url "http://www.puzzlers.org/pub/wordlists/unixdict.txt")
(def words (-> words-url slurp clojure.string/split-lines))
(def digits (partial map table))
(let [textable (filter #(every? table %) words) ;; words with letters only
mapping (group-by digits textable) ;; map of digits to words
textonyms (filter #(< 1 (count (val %))) mapping)] ;; textonyms only
(print
(str "There are " (count textable) " words in " \' words-url \'
" which can be represented by the digit key mapping. They require "
(count mapping) " digit combinations to represent them. "
(count textonyms) " digit combinations represent Textonyms.")))
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #ALGOL_68 | ALGOL 68 | PROC report = (REF FILE file in)INT: (
MODE TIME = [19]CHAR;
STRUCT ([3]CHAR inout, TIME time, INT jobnum) record;
FORMAT record fmt = $"License "g" @ "g" for job "g(0)l$;
FLEX[1]TIME max time;
INT lic out := 0, max out := LWB max time-1, max count := LWB max time-1;
BOOL file in ended := FALSE;
on logical file end(file in, (REF FILE file in)BOOL: file in ended := TRUE);
WHILE
getf(file in, (record fmt, record));
# WHILE # NOT file in ended DO
IF inout OF record = "OUT" THEN
lic out +:= 1
ELIF lic out > 0 THEN # incase license already "OUT" #
lic out -:= 1
FI;
IF lic out > max out THEN
max out := lic out;
max count := LWB max time-1
FI;
IF lic out = max out THEN
IF max count = UPB max time THEN
[UPB max time*2]TIME new max time;
new max time[:UPB max time] := max time;
max time := new max time
# ;putf(stand error, ($"increasing UPB max time (now it is "g(0)")"l$, UPB max time)); #
FI;
max time[max count +:= 1] := time OF record
FI
OD;
printf(($"Maximum simultaneous license use is "g(0)" at the following times:"l$, max out));
FOR lic out FROM LWB max time TO max count DO
printf(($gl$, max time[lic out]))
OD;
0 EXIT
exit report error: errno
);
INT errno;
COMMENT
Usage:
a68g Text_processing_3.a68 --exit Text_processing_3.dat
a68g Text_processing_3.a68 < Text_processing_3.dat
END COMMENT
main:
(
INT argv1 := 4;
IF argc >= argv1 THEN
FOR i FROM argv1 TO argc DO
FILE file in;
errno := open(file in, argv(i), stand in channel);
IF errno /= 0 THEN
putf(stand error, ($"cannot read "gl$, argv(1)));
exit main error
ELSE
report(file in)
FI;
close(file in)
OD
ELSE
report(stand in)
FI;
exit main error: SKIP
) |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Tcl | Tcl | #
### Create a thiele-interpretation function with the given name that interpolates
### off the given table.
#
proc thiele {name : X -> F} {
# Sanity check
if {[llength $X] != [llength $F]} {
error "unequal length lists supplied: [llength $X] != [llength $F]"
}
#
### Compute the table of reciprocal differences
#
set p [lrepeat [llength $X] [lrepeat [llength $X] 0.0]]
set i 0
foreach x0 [lrange $X 0 end-1] x1 [lrange $X 1 end] \
f0 [lrange $F 0 end-1] f1 [lrange $F 1 end] {
lset p $i 0 $f0
lset p $i 1 [expr {($x0 - $x1) / ($f0 - $f1)}]
lset p [incr i] 0 $f1
}
for {set j 2} {$j<[llength $X]-1} {incr j} {
for {set i 0} {$i<[llength $X]-$j} {incr i} {
lset p $i $j [expr {
[lindex $p $i+1 $j-2] +
([lindex $X $i] - [lindex $X $i+$j]) /
([lindex $p $i $j-1] - [lindex $p $i+1 $j-1])
}]
}
}
#
### Make pseudo-curried function that actually evaluates Thiele's formula
#
interp alias {} $name {} apply {{X rho f1 x} {
set a 0.0
foreach Xi [lreverse [lrange $X 2 end]] \
Ri [lreverse [lrange $rho 2 end]] \
Ri2 [lreverse [lrange $rho 0 end-2]] {
set a [expr {($x - $Xi) / ($Ri - $Ri2 + $a)}]
}
expr {$f1 + ($x - [lindex $X 1]) / ([lindex $rho 1] + $a)}
}} $X [lindex $p 1] [lindex $F 1]
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #C.2B.2B | C++ | #include <boost/regex.hpp>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <cstdlib>
#include <algorithm>
using namespace std ;
boost::regex e ( "\\s+" ) ;
int main( int argc , char *argv[ ] ) {
ifstream infile( argv[ 1 ] ) ;
vector<string> duplicates ;
set<string> datestamps ; //for the datestamps
if ( ! infile.is_open( ) ) {
cerr << "Can't open file " << argv[ 1 ] << '\n' ;
return 1 ;
}
int all_ok = 0 ;//all_ok for lines in the given pattern e
int pattern_ok = 0 ; //overall field pattern of record is ok
while ( infile ) {
string eingabe ;
getline( infile , eingabe ) ;
boost::sregex_token_iterator i ( eingabe.begin( ), eingabe.end( ) , e , -1 ), j ;//we tokenize on empty fields
vector<string> fields( i, j ) ;
if ( fields.size( ) == 49 ) //we expect 49 fields in a record
pattern_ok++ ;
else
cout << "Format not ok!\n" ;
if ( datestamps.insert( fields[ 0 ] ).second ) { //not duplicated
int howoften = ( fields.size( ) - 1 ) / 2 ;//number of measurement
//devices and values
for ( int n = 1 ; atoi( fields[ 2 * n ].c_str( ) ) >= 1 ; n++ ) {
if ( n == howoften ) {
all_ok++ ;
break ;
}
}
}
else {
duplicates.push_back( fields[ 0 ] ) ;//first field holds datestamp
}
}
infile.close( ) ;
cout << "The following " << duplicates.size() << " datestamps were duplicated:\n" ;
copy( duplicates.begin( ) , duplicates.end( ) ,
ostream_iterator<string>( cout , "\n" ) ) ;
cout << all_ok << " records were complete and ok!\n" ;
return 0 ;
} |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #D | D | import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.uni;
void printVerse(string name) {
auto sb = name.map!toLower.array;
sb[0] = sb[0].toUpper;
string x = sb.to!string;
string y;
switch(sb[0]) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
y = x.map!toLower.to!string;
break;
default:
y = x[1..$];
break;
}
string b = "b" ~ y;
string f = "f" ~ y;
string m = "m" ~ y;
switch (x[0]) {
case 'B':
b = y;
break;
case 'F':
f = y;
break;
case 'M':
m = y;
break;
default:
// no adjustment needed
break;
}
writeln(x, ", ", x, ", bo-", b);
writeln("Banana-fana fo-", f);
writeln("Fee-fi-mo-", m);
writeln(x, "!\n");
}
void main() {
foreach (name; ["Gary","Earl","Billy","Felix","Mary","steve"]) {
printVerse(name);
}
} |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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
| #D | D | void main() {
import std.stdio, std.string, std.range, std.algorithm, std.ascii;
immutable src = "unixdict.txt";
const words = src.File.byLineCopy.map!strip.filter!(w => w.all!isAlpha).array;
immutable table = makeTrans("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"2223334445556667777888999922233344455566677778889999");
string[][string] dials;
foreach (const word; words)
dials[word.translate(table)] ~= word;
auto textonyms = dials.byPair.filter!(p => p[1].length > 1).array;
writefln("There are %d words in %s which can be represented by the digit key mapping.", words.length, src);
writefln("They require %d digit combinations to represent them.", dials.length);
writefln("%d digit combinations represent Textonyms.", textonyms.length);
"\nTop 5 in ambiguity:".writeln;
foreach (p; textonyms.schwartzSort!(p => -p[1].length).take(5))
writefln(" %s => %-(%s %)", p[]);
"\nTop 5 in length:".writeln;
foreach (p; textonyms.schwartzSort!(p => -p[0].length).take(5))
writefln(" %s => %-(%s %)", p[]);
} |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #APL | APL | ⍝ Copy/paste file's contents into TXT (easiest), or TXT ← ⎕NREAD
I ← TXT[;8+⎕IO]
D ← TXT[;⎕IO+14+⍳19]
lu ← +\ ¯1 * 'OI' ⍳ I
mx ← (⎕IO+⍳⍴lu)/⍨lu= max ← ⌈/ lu
⎕ ← 'Maximum simultaneous license use is ' , ' at the following times:' ,⍨ ⍕max ⋄ ⎕←D[mx;] |
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #Wren | Wren | import "/fmt" for Fmt
var N = 32
var N2 = N * (N - 1) / 2
var STEP = 0.05
var xval = List.filled(N, 0.0)
var tsin = List.filled(N, 0.0)
var tcos = List.filled(N, 0.0)
var ttan = List.filled(N, 0.0)
var rsin = List.filled(N2, 0/0)
var rcos = List.filled(N2, 0/0)
var rtan = List.filled(N2, 0/0)
var rho
rho = Fn.new { |x, y, r, i, n|
if (n < 0) return 0
if (n == 0) return y[i]
var idx = (N - 1 - n) * (N - n) / 2 + i
if (r[idx].isNan) {
r[idx] = (x[i] - x[i + n]) /
(rho.call(x, y, r, i, n - 1) - rho.call(x, y, r, i + 1, n - 1)) +
rho.call(x, y, r, i + 1, n - 2)
}
return r[idx]
}
var thiele
thiele = Fn.new { |x, y, r, xin, n|
if (n > N - 1) return 1
return rho.call(x, y, r, 0, n) - rho.call(x, y, r, 0, n -2) +
(xin - x[n]) / thiele.call(x, y, r, xin, n + 1)
}
for (i in 0...N) {
xval[i] = i * STEP
tsin[i] = xval[i].sin
tcos[i] = xval[i].cos
ttan[i] = tsin[i] / tcos[i]
}
Fmt.print("$16.14f", 6 * thiele.call(tsin, xval, rsin, 0.5, 0))
Fmt.print("$16.14f", 3 * thiele.call(tcos, xval, rcos, 0.5, 0))
Fmt.print("$16.14f", 4 * thiele.call(ttan, xval, rtan, 1.0, 0)) |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Clojure | Clojure |
(defn parse-line [s]
(let [[date & data-toks] (str/split s #"\s+")
data-fields (map read-string data-toks)
valid-date? (fn [s] (re-find #"\d{4}-\d{2}-\d{2}" s))
valid-line? (and (valid-date? date)
(= 48 (count data-toks))
(every? number? data-fields))
readings (for [[v flag] (partition 2 data-fields)]
{:val v :flag flag})]
(when (not valid-line?)
(println "Malformed Line: " s))
{:date date
:no-missing-readings? (and (= 48 (count data-toks))
(every? pos? (map :flag readings)))}))
(defn analyze-file [path]
(reduce (fn [m line]
(let [{:keys [all-dates dupl-dates n-full-recs invalid-lines]} m
this-date (:date line)
dupl? (contains? all-dates this-date)
full? (:no-missing-readings? line)]
(cond-> m
dupl? (update-in [:dupl-dates] conj this-date)
full? (update-in [:n-full-recs] inc)
true (update-in [:all-dates] conj this-date))))
{:dupl-dates #{} :all-dates #{} :n-full-recs 0}
(->> (slurp path)
clojure.string/split-lines
(map parse-line))))
(defn report-summary [path]
(let [m (analyze-file path)]
(println (format "%d unique dates" (count (:all-dates m))))
(println (format "%d duplicated dates [%s]"
(count (:dupl-dates m))
(clojure.string/join " " (sort (:dupl-dates m)))))
(println (format "%d lines with no missing data" (:n-full-recs m)))))
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #Dyalect | Dyalect | func printVerse(name) {
let x = name[..1].Upper() + name[1..].Lower();
let y = "AEIOU".IndexOf(x[0]) > -1 ? x.Lower() : x[1..]
let b = x[0] is 'B' ? y : "b" + y
let f = x[0] is 'F' ? y : "f" + y
let m = x[0] is 'M' ? y : "m" + y
print("\(x), \(x), bo-\(b)")
print("Banana-fana fo-\(f)")
print("Fee-fi-mo-\(m)")
print("\(x)!", x)
print()
}
let seq = yields { "Gary", "Earl", "Billy", "Felix", "Mary", "Steve" }
for x in seq {
printVerse(x)
} |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #F.23 | F# |
// The Name Game. Nigel Galloway: March 28th., 2018
let fN g =
let fG α β γ = printfn "%s, %s, bo-%s\nBanana-fana fo-%s\nFee-fi-mo-%s\n%s!" g g α β γ g
match g.ToLower().[0] with
|'a'|'e'|'i'|'o'|'u' as n -> fG ("b"+(string n)+g.[1..]) ("f"+(string n)+g.[1..]) ("m"+(string n)+g.[1..])
|'b' -> fG (g.[1..]) ("f"+g.[1..]) ("m"+g.[1..])
|'f' -> fG ("b"+g.[1..]) (g.[1..]) ("m"+g.[1..])
|'m' -> fG ("b"+g.[1..]) ("f"+g.[1..]) (g.[1..])
|_ -> fG ("b"+g.[1..]) ("f"+g.[1..]) ("m"+g.[1..])
|
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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
| #Delphi | Delphi |
program Textonyms;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
System.Character;
const
TEXTONYM_MAP = '22233344455566677778889999';
type
TextonymsChecker = class
private
Total, Elements, Textonyms, MaxFound: Integer;
MaxStrings: TList<string>;
Values: TDictionary<string, TList<string>>;
FFileName: TFileName;
function Map(c: Char): Char;
function GetMapping(var return: string; const Input: string): Boolean;
public
constructor Create(FileName: TFileName);
destructor Destroy; override;
procedure Add(const Str: string);
procedure Load(FileName: TFileName);
procedure Test;
function Match(const str: string): Boolean;
property FileName: TFileName read FFileName;
end;
{ TextonymsChecker }
procedure TextonymsChecker.Add(const Str: string);
var
mapping: string;
num_strings: Integer;
procedure AddValues(mapping: string; NewItem: string);
begin
if not Values.ContainsKey(mapping) then
Values.Add(mapping, TList<string>.Create);
Values[mapping].Add(NewItem);
end;
begin
inc(total);
if not GetMapping(mapping, Str) then
Exit;
if Values.ContainsKey(mapping) then
num_strings := Values[mapping].Count
else
num_strings := 0;
inc(Textonyms, ord(num_strings = 1));
inc(Elements);
if (num_strings > maxfound) then
begin
MaxStrings.Clear;
MaxStrings.Add(mapping);
MaxFound := num_strings;
end
else if num_strings = MaxFound then
begin
MaxStrings.Add(mapping);
end;
AddValues(mapping, Str);
end;
constructor TextonymsChecker.Create(FileName: TFileName);
begin
MaxStrings := TList<string>.Create;
Values := TDictionary<string, TList<string>>.Create;
Total := 0;
Textonyms := 0;
MaxFound := 0;
Elements := 0;
Load(FileName);
end;
destructor TextonymsChecker.Destroy;
var
key: string;
begin
for key in Values.Keys do
Values[key].Free;
Values.Free;
MaxStrings.Free;
inherited;
end;
function TextonymsChecker.GetMapping(var return: string; const Input: string): Boolean;
var
i: Integer;
begin
return := Input;
for i := 1 to return.Length do
begin
if not return[i].IsLetterOrDigit then
exit(False);
if return[i].IsLetter then
return[i] := Map(return[i]);
end;
Result := True;
end;
procedure TextonymsChecker.Load(FileName: TFileName);
var
i: Integer;
begin
if not FileExists(FileName) then
begin
writeln('File "', FileName, '" not found');
exit;
end;
with TStringList.Create do
begin
LoadFromFile(FileName);
for i := 0 to count - 1 do
begin
self.Add(Strings[i]);
end;
Free;
end;
end;
function TextonymsChecker.Map(c: Char): Char;
begin
Result := TEXTONYM_MAP.Chars[Ord(UpCase(c)) - Ord('A')];
end;
function TextonymsChecker.Match(const str: string): Boolean;
var
w: string;
begin
Result := Values.ContainsKey(str);
if not Result then
begin
writeln('Key "', str, '" not found');
end
else
begin
write('Key "', str, '" matches: ');
for w in Values[str] do
begin
write(w, ' ');
end;
writeln;
end;
end;
procedure TextonymsChecker.Test;
var
i, j: Integer;
begin
writeln('Read ', Total, ' words from ', FileName, #10);
writeln(' which can be represented by the digit key mapping.');
writeln('They require ', Values.Count, ' digit combinations to represent them.');
writeln(textonyms, ' digit combinations represent Textonyms.', #10);
write('The numbers mapping to the most words map to');
writeln(MaxFound + 1, ' words each:');
for i := 0 to MaxStrings.Count - 1 do
begin
write(^I, MaxStrings[i], ' maps to: ');
for j := 0 to Values[MaxStrings[i]].Count - 1 do
begin
write(Values[MaxStrings[i]][j], ' ');
end;
Writeln;
end;
end;
var
Tc: TextonymsChecker;
begin
Tc := TextonymsChecker.Create('unixdict.txt');
Tc.Test;
tc.match('001');
tc.match('228');
tc.match('27484247');
tc.match('7244967473642');
Tc.Free;
readln;
end.
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #AutoHotkey | AutoHotkey |
IfNotExist, mlijobs.txt
UrlDownloadToFile, http://rosettacode.org/mlijobs.txt, mlijobs.txt
out := 0, max_out := -1, max_times := ""
Loop, Read, mlijobs.txt
{
If InStr(A_LoopReadLine, "OUT")
out++
Else
out--
If (out > max_out)
max_out := out, max_times := ""
If (out = max_out)
{
StringSplit, lineArr, A_LoopReadLine, %A_Space%
max_times .= lineArr4 . "`n"
}
}
MsgBox Maximum use is %max_out% at:`n`n%max_times%
|
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula | Thiele's interpolation formula |
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Thiele's interpolation formula is an interpolation formula for a function f(•) of a single variable. It is expressed as a continued fraction:
f
(
x
)
=
f
(
x
1
)
+
x
−
x
1
ρ
1
(
x
1
,
x
2
)
+
x
−
x
2
ρ
2
(
x
1
,
x
2
,
x
3
)
−
f
(
x
1
)
+
x
−
x
3
ρ
3
(
x
1
,
x
2
,
x
3
,
x
4
)
−
ρ
1
(
x
1
,
x
2
)
+
⋯
{\displaystyle f(x)=f(x_{1})+{\cfrac {x-x_{1}}{\rho _{1}(x_{1},x_{2})+{\cfrac {x-x_{2}}{\rho _{2}(x_{1},x_{2},x_{3})-f(x_{1})+{\cfrac {x-x_{3}}{\rho _{3}(x_{1},x_{2},x_{3},x_{4})-\rho _{1}(x_{1},x_{2})+\cdots }}}}}}}
ρ
{\displaystyle \rho }
represents the reciprocal difference, demonstrated here for reference:
ρ
1
(
x
0
,
x
1
)
=
x
0
−
x
1
f
(
x
0
)
−
f
(
x
1
)
{\displaystyle \rho _{1}(x_{0},x_{1})={\frac {x_{0}-x_{1}}{f(x_{0})-f(x_{1})}}}
ρ
2
(
x
0
,
x
1
,
x
2
)
=
x
0
−
x
2
ρ
1
(
x
0
,
x
1
)
−
ρ
1
(
x
1
,
x
2
)
+
f
(
x
1
)
{\displaystyle \rho _{2}(x_{0},x_{1},x_{2})={\frac {x_{0}-x_{2}}{\rho _{1}(x_{0},x_{1})-\rho _{1}(x_{1},x_{2})}}+f(x_{1})}
ρ
n
(
x
0
,
x
1
,
…
,
x
n
)
=
x
0
−
x
n
ρ
n
−
1
(
x
0
,
x
1
,
…
,
x
n
−
1
)
−
ρ
n
−
1
(
x
1
,
x
2
,
…
,
x
n
)
+
ρ
n
−
2
(
x
1
,
…
,
x
n
−
1
)
{\displaystyle \rho _{n}(x_{0},x_{1},\ldots ,x_{n})={\frac {x_{0}-x_{n}}{\rho _{n-1}(x_{0},x_{1},\ldots ,x_{n-1})-\rho _{n-1}(x_{1},x_{2},\ldots ,x_{n})}}+\rho _{n-2}(x_{1},\ldots ,x_{n-1})}
Demonstrate Thiele's interpolation function by:
Building a 32 row trig table of values for
x
{\displaystyle x}
from 0 by 0.05 to 1.55 of the trig functions:
sin
cos
tan
Using columns from this table define an inverse - using Thiele's interpolation - for each trig function;
Finally: demonstrate the following well known trigonometric identities:
6 × sin-1 ½ =
π
{\displaystyle \pi }
3 × cos-1 ½ =
π
{\displaystyle \pi }
4 × tan-1 1 =
π
{\displaystyle \pi }
| #zkl | zkl | const N=32, N2=(N * (N - 1) / 2), STEP=0.05;
fcn rho(xs,ys,rs, i,n){
if (n < 0) return(0.0);
if (not n) return(ys[i]);
idx := (N - 1 - n) * (N - n) / 2 + i;
if (Void==rs[idx])
rs[idx] = (xs[i] - xs[i + n])
/ (rho(xs, ys, rs, i, n - 1) - rho(xs, ys, rs, i + 1, n - 1))
+ rho(xs, ys, rs, i + 1, n - 2);
return(rs[idx]);
}
fcn thiele(xs,ys,rs, xin, n){
if (n > N - 1) return(1.0);
rho(xs, ys, rs, 0, n) - rho(xs, ys, rs, 0, n - 2)
+ (xin - xs[n]) / thiele(xs, ys, rs, xin, n + 1);
}
///////////
reg t_sin=L(), t_cos=L(), t_tan=L(),
r_sin=L(), r_cos=L(), r_tan=L(), xval=L();
i_sin := thiele.fpM("11101",t_sin, xval, r_sin, 0);
i_cos := thiele.fpM("11101",t_cos, xval, r_cos, 0);
i_tan := thiele.fpM("11101",t_tan, xval, r_tan, 0);
foreach i in (N){
xval.append(x:=STEP*i);
t_sin.append(x.sin());
t_cos.append(x.cos());
t_tan.append(t_sin[i] / t_cos[i]);
}
foreach i in (N2){ r_sin+Void; r_cos+Void; r_tan+Void; }
print("%16.14f\n".fmt( 6.0 * i_sin(0.5)));
print("%16.14f\n".fmt( 3.0 * i_cos(0.5)));
print("%16.14f\n".fmt( 4.0 * i_tan(1.0))); |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. text-processing-2.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT readings ASSIGN Input-File-Path
ORGANIZATION LINE SEQUENTIAL
FILE STATUS file-status.
DATA DIVISION.
FILE SECTION.
FD readings.
01 reading-record.
03 date-stamp PIC X(10).
03 FILLER PIC X.
03 input-data PIC X(300).
LOCAL-STORAGE SECTION.
78 Input-File-Path VALUE "readings.txt".
78 Num-Data-Points VALUE 48.
01 file-status PIC XX.
01 current-line PIC 9(5).
01 num-date-stamps-read PIC 9(5).
01 read-date-stamps-area.
03 read-date-stamps PIC X(10) OCCURS 1 TO 10000 TIMES
DEPENDING ON num-date-stamps-read
INDEXED BY date-stamp-idx.
01 offset PIC 999.
01 data-len PIC 999.
01 data-flag PIC X.
88 data-not-found VALUE "N".
01 data-field PIC X(25).
01 i PIC 99.
01 num-good-readings PIC 9(5).
01 reading-flag PIC X.
88 bad-reading VALUE "B".
01 delim PIC X.
PROCEDURE DIVISION.
DECLARATIVES.
readings-error SECTION.
USE AFTER ERROR ON readings
DISPLAY "An error occurred while using " Input-File-Path
DISPLAY "Error code " file-status
DISPLAY "The program will terminate."
CLOSE readings
GOBACK
.
END DECLARATIVES.
main-line.
OPEN INPUT readings
*> Process each line of the file.
PERFORM FOREVER
READ readings
AT END
EXIT PERFORM
END-READ
ADD 1 TO current-line
IF reading-record = SPACES
DISPLAY "Line " current-line " is blank."
EXIT PERFORM CYCLE
END-IF
PERFORM check-duplicate-date-stamp
*> Check there are 24 data pairs and see if all the
*> readings are ok.
INITIALIZE offset, reading-flag, data-flag
PERFORM VARYING i FROM 1 BY 1 UNTIL Num-Data-Points < i
PERFORM get-next-field
IF data-not-found
DISPLAY "Line " current-line " has missing "
"fields."
SET bad-reading TO TRUE
EXIT PERFORM
END-IF
*> Every other data field is the instrument flag.
IF FUNCTION MOD(i, 2) = 0 AND NOT bad-reading
IF FUNCTION NUMVAL(data-field) <= 0
SET bad-reading TO TRUE
END-IF
END-IF
ADD data-len TO offset
END-PERFORM
IF NOT bad-reading
ADD 1 TO num-good-readings
END-IF
END-PERFORM
CLOSE readings
*> Display results.
DISPLAY SPACE
DISPLAY current-line " lines read."
DISPLAY num-good-readings " have good readings for all "
"instruments."
GOBACK
.
check-duplicate-date-stamp.
SEARCH read-date-stamps
AT END
ADD 1 TO num-date-stamps-read
MOVE date-stamp
TO read-date-stamps (num-date-stamps-read)
WHEN read-date-stamps (date-stamp-idx) = date-stamp
DISPLAY "Date " date-stamp " is duplicated at "
"line " current-line "."
END-SEARCH
.
get-next-field.
INSPECT input-data (offset:) TALLYING offset
FOR LEADING X"09"
*> The fields are normally delimited by a tab.
MOVE X"09" TO delim
PERFORM find-num-chars-before-delim
*> If the delimiter was not found...
IF FUNCTION SUM(data-len, offset) > 300
*> The data may be delimited by a space if it is at the
*> end of the line.
MOVE SPACE TO delim
PERFORM find-num-chars-before-delim
IF FUNCTION SUM(data-len, offset) > 300
SET data-not-found TO TRUE
EXIT PARAGRAPH
END-IF
END-IF
IF data-len = 0
SET data-not-found TO TRUE
EXIT PARAGRAPH
END-IF
MOVE input-data (offset:data-len) TO data-field
.
find-num-chars-before-delim.
INITIALIZE data-len
INSPECT input-data (offset:) TALLYING data-len
FOR CHARACTERS BEFORE delim
. |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #Factor | Factor | USING: ascii combinators interpolate io kernel locals
pair-rocket qw sequences ;
IN: rosetta-code.name-game
: vowel? ( char -- ? ) "AEIOU" member? ;
:: name-game ( Name -- )
Name first :> L
Name >lower :> name! L vowel? [ name rest name! ] unless
"b" :> B!
"f" :> F!
"m" :> M!
L { CHAR: B => [ "" B! ]
CHAR: F => [ "" F! ]
CHAR: M => [ "" M! ] [ drop ] } case
[I ${Name}, ${Name}, bo-${B}${name}
Banana-fana fo-${F}${name}
Fee-fi-mo-${M}${name}
${Name}!I] nl nl ;
qw{ Gary Earl Billy Felix Milton Steve } [ name-game ] each |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #FreeBASIC | FreeBASIC | Sub TheGameName(nombre As String)
Dim As String x = Lcase(nombre)
x = Ucase(Mid(x,1,1)) + (Mid(x,2,Len(x)-1))
Dim As String x0 = Ucase(Mid(x,1,1))
Dim As String y
If x0 = "A" Or x0 = "E" Or x0 = "I" Or x0 = "O" Or x0 = "U" Then
y = Lcase(x)
Else
y = Mid(x,2)
End If
Dim As String b = "b" + y, f = "f" + y, m = "m" + y
Select Case x0
Case "B" : b = y
Case "F" : f = y
Case "M" : m = y
End Select
Print x + ", " + x + ", bo-" + b
Print "Banana-fana fo-" + f
Print "Fee-fi-mo-" + m
Print x + "!" + Chr(10)
End Sub
Dim listanombres(5) As String = {"Gary", "EARL", "billy", "FeLiX", "Mary", "ShirlEY"}
For i As Integer = 0 To Ubound(listanombres)
TheGameName(listanombres(i))
Next i
Sleep |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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
| #Factor | Factor | USING: assocs assocs.extras interpolate io io.encodings.utf8
io.files kernel literals math math.parser prettyprint sequences
unicode ;
<< CONSTANT: src "unixdict.txt" >>
CONSTANT: words
$[ src utf8 file-lines [ [ letter? ] all? ] filter ]
CONSTANT: digits "22233344455566677778889999"
: >phone ( str -- n )
[ CHAR: a - digits nth ] map string>number ;
: textonyms ( seq -- assoc )
[ [ >phone ] keep ] map>alist expand-keys-push-at ;
: #textonyms ( assoc -- n )
[ nip length 1 > ] assoc-filter assoc-size ;
words length src words textonyms [ assoc-size ] keep #textonyms
[I There are ${} words in ${} which can be represented by the digit key mapping.
They require ${} digit combinations to represent them.
${} digit combinations represent Textonyms.I] nl nl
"7325 -> " write words textonyms 7325 of . |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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
| #Go | Go | package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
func main() {
log.SetFlags(0)
log.SetPrefix("textonyms: ")
wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
t := NewTextonym(phoneMap)
_, err := ReadFromFile(t, *wordlist)
if err != nil {
log.Fatal(err)
}
t.Report(os.Stdout, *wordlist)
}
// phoneMap is the digit to letter mapping of a typical phone.
var phoneMap = map[byte][]rune{
'2': []rune("ABC"),
'3': []rune("DEF"),
'4': []rune("GHI"),
'5': []rune("JKL"),
'6': []rune("MNO"),
'7': []rune("PQRS"),
'8': []rune("TUV"),
'9': []rune("WXYZ"),
}
// ReadFromFile is a generic convience function that allows the use of a
// filename with an io.ReaderFrom and handles errors related to open and
// closing the file.
func ReadFromFile(r io.ReaderFrom, filename string) (int64, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
n, err := r.ReadFrom(f)
if cerr := f.Close(); err == nil && cerr != nil {
err = cerr
}
return n, err
}
type Textonym struct {
numberMap map[string][]string // map numeric string into words
letterMap map[rune]byte // map letter to digit
count int // total number of words in numberMap
textonyms int // number of numeric strings with >1 words
}
func NewTextonym(dm map[byte][]rune) *Textonym {
lm := make(map[rune]byte, 26)
for d, ll := range dm {
for _, l := range ll {
lm[l] = d
}
}
return &Textonym{letterMap: lm}
}
func (t *Textonym) ReadFrom(r io.Reader) (n int64, err error) {
t.numberMap = make(map[string][]string)
buf := make([]byte, 0, 32)
sc := bufio.NewScanner(r)
sc.Split(bufio.ScanWords)
scan:
for sc.Scan() {
buf = buf[:0]
word := sc.Text()
// XXX we only bother approximating the number of bytes
// consumed. This isn't used in the calling code and was
// only included to match the io.ReaderFrom interface.
n += int64(len(word)) + 1
for _, r := range word {
d, ok := t.letterMap[unicode.ToUpper(r)]
if !ok {
//log.Printf("ignoring %q\n", word)
continue scan
}
buf = append(buf, d)
}
//log.Printf("scanned %q\n", word)
num := string(buf)
t.numberMap[num] = append(t.numberMap[num], word)
t.count++
if len(t.numberMap[num]) == 2 {
t.textonyms++
}
//log.Printf("%q → %v\t→ %v\n", word, num, t.numberMap[num])
}
return n, sc.Err()
}
func (t *Textonym) Most() (most int, subset map[string][]string) {
for k, v := range t.numberMap {
switch {
case len(v) > most:
subset = make(map[string][]string)
most = len(v)
fallthrough
case len(v) == most:
subset[k] = v
}
}
return most, subset
}
func (t *Textonym) Report(w io.Writer, name string) {
// Could be fancy and use text/template package but fmt is sufficient
fmt.Fprintf(w, `
There are %v words in %q which can be represented by the digit key mapping.
They require %v digit combinations to represent them.
%v digit combinations represent Textonyms.
`,
t.count, name, len(t.numberMap), t.textonyms)
n, sub := t.Most()
fmt.Fprintln(w, "\nThe numbers mapping to the most words map to",
n, "words each:")
for k, v := range sub {
fmt.Fprintln(w, "\t", k, "maps to:", strings.Join(v, ", "))
}
} |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #AWK | AWK | $2=="OUT" {
count = count + 1
time = $4
if ( count > maxcount ) {
maxcount = count
maxtimes = time
} else {
if ( count == maxcount ) {
maxtimes = maxtimes " and " time
}
}
}
$2=="IN" { count = count - 1 }
END {print "The biggest number of licenses is " maxcount " at " maxtimes " !"} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #D | D | void main() {
import std.stdio, std.array, std.string, std.regex, std.conv,
std.algorithm;
auto rxDate = `^\d\d\d\d-\d\d-\d\d$`.regex;
// Works but eats lot of RAM in DMD 2.064.
// auto rxDate = ctRegex!(`^\d\d\d\d-\d\d-\d\d$`);
int[string] repeatedDates;
int goodReadings;
foreach (string line; "readings.txt".File.lines) {
try {
auto parts = line.split;
if (parts.length != 49)
throw new Exception("Wrong column count");
if (parts[0].match(rxDate).empty)
throw new Exception("Date is wrong");
repeatedDates[parts[0]]++;
bool noProblem = true;
for (int i = 1; i < 48; i += 2) {
if (parts[i + 1].to!int < 1)
// don't break loop because it's validation too.
noProblem = false;
if (!parts[i].isNumeric)
throw new Exception("Reading is wrong: "~parts[i]);
}
if (noProblem)
goodReadings++;
} catch(Exception ex) {
writefln(`Problem in line "%s": %s`, line, ex);
}
}
writefln("Duplicated timestamps: %-(%s, %)",
repeatedDates.byKey.filter!(k => repeatedDates[k] > 1));
writeln("Good reading records: ", goodReadings);
} |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"strings"
)
func printVerse(name string) {
x := strings.Title(strings.ToLower(name))
y := x[1:]
if strings.Contains("AEIOU", x[:1]) {
y = strings.ToLower(x)
}
b := "b" + y
f := "f" + y
m := "m" + y
switch x[0] {
case 'B':
b = y
case 'F':
f = y
case 'M':
m = y
}
fmt.Printf("%s, %s, bo-%s\n", x, x, b)
fmt.Printf("Banana-fana fo-%s\n", f)
fmt.Printf("Fee-fi-mo-%s\n", m)
fmt.Printf("%s!\n\n", x)
}
func main() {
names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"}
for _, name := range names {
printVerse(name)
}
} |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | import Data.Char (toUpper)
import Data.Function (on)
import Data.List (groupBy, sortBy)
import Data.Maybe (fromMaybe, isJust, isNothing)
toKey :: Char -> Maybe Char
toKey ch
| ch < 'A' = Nothing
| ch < 'D' = Just '2'
| ch < 'G' = Just '3'
| ch < 'J' = Just '4'
| ch < 'M' = Just '5'
| ch < 'P' = Just '6'
| ch < 'T' = Just '7'
| ch < 'W' = Just '8'
| ch <= 'Z' = Just '9'
| otherwise = Nothing
toKeyString :: String -> Maybe String
toKeyString st
| any isNothing mch = Nothing
| otherwise = Just $ map (fromMaybe '!') mch
where
mch = map (toKey . toUpper) st
showTextonym :: [(String, String)] -> String
showTextonym ts =
fst (head ts)
++ " => "
++ concat
[ w ++ " "
| (_, w) <- ts
]
main :: IO ()
main = do
let src = "unixdict.txt"
contents <- readFile src
let wordList = lines contents
keyedList =
[ (key, word)
| (Just key, word) <-
filter (isJust . fst) $
zip (map toKeyString wordList) wordList
]
groupedList =
groupBy ((==) `on` fst) $
sortBy (compare `on` fst) keyedList
textonymList = filter ((> 1) . length) groupedList
mapM_ putStrLn $
[ "There are "
++ show (length keyedList)
++ " words in "
++ src
++ " which can be represented by the digit key mapping.",
"They require "
++ show (length groupedList)
++ " digit combinations to represent them.",
show (length textonymList) ++ " digit combinations represent Textonyms.",
"",
"Top 5 in ambiguity:"
]
++ fmap
showTextonym
( take 5 $
sortBy (flip compare `on` length) textonymList
)
++ ["", "Top 5 in length:"]
++ fmap
showTextonym
(take 5 $ sortBy (flip compare `on` (length . fst . head)) textonymList) |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #BBC_BASIC | BBC BASIC | max% = 0
nlicence% = 0
file% = OPENIN("mlijobs.txt")
WHILE NOT EOF#file%
a$ = GET$#file%
stamp$ = MID$(a$, 15, 19)
IF INSTR(a$, "OUT") THEN
nlicence% += 1
IF nlicence% > max% THEN
max% = nlicence%
start$ = stamp$
ENDIF
ENDIF
IF INSTR(a$, "IN") THEN
IF nlicence% = max% THEN
finish$ = previous$
ENDIF
nlicence% -= 1
ENDIF
previous$ = stamp$
ENDWHILE
CLOSE #file%
PRINT "Maximum licences checked out = " ; max%
PRINT "From " start$ " to " finish$
END |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Bracmat | Bracmat | ( 0:?N:?n
& :?Ts
& @( get$("mlijobs.txt",STR)
: ?
( "e " ?OI " @ " ?T " " ?
& ( !OI:OUT
& !n+1
: ( >!N:?N&!T:?Ts
| !N&!Ts !T:?Ts
| ?
)
| !n+-1
)
: ?n
& ~
)
)
| out$(!N !Ts)
);
|
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Eiffel | Eiffel |
class
APPLICATION
create
make
feature
make
-- Finds double date stamps and wrong formats.
local
found: INTEGER
double: STRING
do
read_wordlist
fill_hash_table
across
hash as h
loop
if h.key.has_substring ("_double") then
io.put_string ("Double date stamp: %N")
double := h.key
double.remove_tail (7)
io.put_string (double)
io.new_line
end
if h.item.count /= 24 then
io.put_string (h.key.out + " has the wrong format. %N")
found := found + 1
end
end
io.put_string (found.out + " records have not 24 readings.%N")
good_records
end
good_records
-- Number of records that have flag values > 0 for all readings.
local
count, total: INTEGER
end_date: STRING
do
create end_date.make_empty
across
hash as h
loop
count := 0
across
h.item as d
loop
if d.item.flag > 0 then
count := count + 1
end
end
if count = 24 then
total := total + 1
end
end
io.put_string ("%NGood records: " + total.out + ". %N")
end
original_list: STRING = "readings.txt"
read_wordlist
--Preprocesses data in 'data'.
local
l_file: PLAIN_TEXT_FILE
do
create l_file.make_open_read_write (original_list)
l_file.read_stream (l_file.count)
data := l_file.last_string.split ('%N')
l_file.close
end
data: LIST [STRING]
fill_hash_table
--Fills 'hash' using the date as key.
local
by_dates: LIST [STRING]
date: STRING
data_tup: TUPLE [val: REAL; flag: INTEGER]
data_arr: ARRAY [TUPLE [val: REAL; flag: INTEGER]]
i: INTEGER
do
create hash.make (data.count)
across
data as d
loop
if not d.item.is_empty then
by_dates := d.item.split ('%T')
date := by_dates [1]
by_dates.prune (date)
create data_tup
create data_arr.make_empty
from
i := 1
until
i > by_dates.count - 1
loop
data_tup := [by_dates [i].to_real, by_dates [i + 1].to_integer]
data_arr.force (data_tup, data_arr.count + 1)
i := i + 2
end
hash.put (data_arr, date)
if not hash.inserted then
date.append ("_double")
hash.put (data_arr, date)
end
end
end
end
hash: HASH_TABLE [ARRAY [TUPLE [val: REAL; flag: INTEGER]], STRING]
end
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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
| #Go | Go | package main
import (
"fmt"
"strings"
)
func printVerse(name string) {
x := strings.Title(strings.ToLower(name))
y := x[1:]
if strings.Contains("AEIOU", x[:1]) {
y = strings.ToLower(x)
}
b := "b" + y
f := "f" + y
m := "m" + y
switch x[0] {
case 'B':
b = y
case 'F':
f = y
case 'M':
m = y
}
fmt.Printf("%s, %s, bo-%s\n", x, x, b)
fmt.Printf("Banana-fana fo-%s\n", f)
fmt.Printf("Fee-fi-mo-%s\n", m)
fmt.Printf("%s!\n\n", x)
}
func main() {
names := [6]string{"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"}
for _, name := range names {
printVerse(name)
}
} |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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
| #Io | Io | main := method(
setupLetterToDigitMapping
file := File clone openForReading("./unixdict.txt")
words := file readLines
file close
wordCount := 0
textonymCount := 0
dict := Map clone
words foreach(word,
(key := word asPhoneDigits) ifNonNil(
wordCount = wordCount+1
value := dict atIfAbsentPut(key,list())
value append(word)
if(value size == 2,textonymCount = textonymCount+1)
)
)
write("There are ",wordCount," words in ",file name)
writeln(" which can be represented by the digit key mapping.")
writeln("They require ",dict size," digit combinations to represent them.")
writeln(textonymCount," digit combinations represent Textonyms.")
samplers := list(maxAmbiquitySampler, noMatchingCharsSampler)
dict foreach(key,value,
if(value size == 1, continue)
samplers foreach(sampler,sampler examine(key,value))
)
samplers foreach(sampler,sampler report)
)
setupLetterToDigitMapping := method(
fromChars := Sequence clone
toChars := Sequence clone
list(
list("ABC", "2"), list("DEF", "3"), list("GHI", "4"),
list("JKL", "5"), list("MNO", "6"), list("PQRS","7"),
list("TUV", "8"), list("WXYZ","9")
) foreach( map,
fromChars appendSeq(map at(0), map at(0) asLowercase)
toChars alignLeftInPlace(fromChars size, map at(1))
)
Sequence asPhoneDigits := block(
str := call target asMutable translate(fromChars,toChars)
if( str contains(0), nil, str )
) setIsActivatable(true)
)
maxAmbiquitySampler := Object clone do(
max := list()
samples := list()
examine := method(key,textonyms,
i := key size - 1
if(i > max size - 1,
max setSize(i+1)
samples setSize(i+1)
)
nw := textonyms size
nwmax := max at(i)
if( nwmax isNil or nw > nwmax,
max atPut(i,nw)
samples atPut(i,list(key,textonyms))
)
)
report := method(
writeln("\nExamples of maximum ambiquity for each word length:")
samples foreach(sample,
sample ifNonNil(
writeln(" ",sample at(0)," -> ",sample at(1) join(" "))
)
)
)
)
noMatchingCharsSampler := Object clone do(
samples := list()
examine := method(key,textonyms,
for(i,0,textonyms size - 2 ,
for(j,i+1,textonyms size - 1,
if( _noMatchingChars(textonyms at(i), textonyms at(j)),
samples append(list(textonyms at(i),textonyms at(j)))
)
)
)
)
_noMatchingChars := method(t1,t2,
t1 foreach(i,ich,
if(ich == t2 at(i), return false)
)
true
)
report := method(
write("\nThere are ",samples size," textonym pairs which ")
writeln("differ at each character position.")
if(samples size > 10, writeln("The ten largest are:"))
samples sortInPlace(at(0) size negate)
if(samples size > 10,samples slice(0,10),samples) foreach(sample,
writeln(" ",sample join(" ")," -> ",sample at(0) asPhoneDigits)
)
)
)
main |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#define INOUT_LEN 4
#define TIME_LEN 20
#define MAX_MAXOUT 1000
char inout[INOUT_LEN];
char time[TIME_LEN];
uint jobnum;
char maxtime[MAX_MAXOUT][TIME_LEN];
int main(int argc, char **argv)
{
FILE *in = NULL;
int l_out = 0, maxout=-1, maxcount=0;
if ( argc > 1 ) {
in = fopen(argv[1], "r");
if ( in == NULL ) {
fprintf(stderr, "cannot read %s\n", argv[1]);
exit(1);
}
} else {
in = stdin;
}
while( fscanf(in, "License %s @ %s for job %u\n", inout, time, &jobnum) != EOF ) {
if ( strcmp(inout, "OUT") == 0 )
l_out++;
else
l_out--;
if ( l_out > maxout ) {
maxout = l_out;
maxcount=0; maxtime[0][0] = '\0';
}
if ( l_out == maxout ) {
if ( maxcount < MAX_MAXOUT ) {
strncpy(maxtime[maxcount], time, TIME_LEN);
maxcount++;
} else {
fprintf(stderr, "increase MAX_MAXOUT (now it is %u)\n", MAX_MAXOUT);
exit(1);
}
}
}
printf("Maximum simultaneous license use is %d at the following times:\n", maxout);
for(l_out=0; l_out < maxcount; l_out++) {
printf("%s\n", maxtime[l_out]);
}
if ( in != stdin ) fclose(in);
exit(0);
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Erlang | Erlang |
-module( text_processing2 ).
-export( [task/0] ).
task() ->
Name = "priv/readings.txt",
try
File_contents = text_processing:file_contents( Name ),
[correct_field_format(X) || X<- File_contents],
{_Previous, Duplicates} = lists:foldl( fun date_duplicates/2, {"", []}, File_contents ),
io:fwrite( "Duplicates: ~p~n", [Duplicates] ),
Good = [X || X <- File_contents, is_all_good_readings(X)],
io:fwrite( "Good readings: ~p~n", [erlang:length(Good)] )
catch
_:Error ->
io:fwrite( "Error: Failed when checking ~s: ~p~n", [Name, Error] )
end.
correct_field_format( {_Date, Value_flags} ) ->
Corret_number = value_flag_records(),
{correct_field_format, Corret_number} = {correct_field_format, erlang:length(Value_flags)}.
date_duplicates( {Date, _Value_flags}, {Date, Acc} ) -> {Date, [Date | Acc]};
date_duplicates( {Date, _Value_flags}, {_Other, Acc} ) -> {Date, Acc}.
is_all_good_readings( {_Date, Value_flags} ) -> value_flag_records() =:= erlang:length( [ok || {_Value, ok} <- Value_flags] ).
value_flag_records() -> 24.
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell |
-- The Name Game, Ethan Riley, 22nd May 2018
import Data.Char
isVowel :: Char -> Bool
isVowel c
| char == 'A' = True
| char == 'E' = True
| char == 'I' = True
| char == 'O' = True
| char == 'U' = True
| otherwise = False
where char = toUpper c
isSpecial :: Char -> Bool
isSpecial c
| char == 'B' = True
| char == 'F' = True
| char == 'M' = True
| otherwise = False
where char = toUpper c
shorten :: String -> String
shorten name
| isVowel $ head name = map toLower name
| otherwise = map toLower $ tail name
line :: String -> Char -> String -> String
line prefix letter name
| letter == char = prefix ++ shorten name ++ "\n"
| otherwise = prefix ++ letter:[] ++ shorten name ++ "\n"
where char = toLower $ head name
theNameGame :: String -> String
theNameGame name =
line (name ++ ", " ++ name ++ ", bo-") 'b' name ++
line "Banana-fana fo-" 'f' name ++
line "Fee-fi-mo-" 'm' name ++
name ++ "!\n"
main =
mapM_ (putStrLn . theNameGame) ["Gary", "Earl", "Billy", "Felix", "Mike", "Steve"]
|
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J | require'regex strings web/gethttp'
strip=:dyad define
(('(?s)',x);'') rxrplc y
)
fetch=:monad define
txt=. '.*<pre>' strip '</pre>.*' strip gethttp y
cutopen tolower txt-.' '
)
keys=:noun define
2 abc
3 def
4 ghi
5 jkl
6 mno
7 pqrs
8 tuv
9 wxyz
)
reporttext=:noun define
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
)
report=:dyad define
x rplc (":&.>y),.~('#{',":,'}'"_)&.>i.#y
)
textonymrpt=:dyad define
'digits letters'=. |:>;,&.>,&.>/&.>/"1 <;._1;._2 x
valid=. (#~ */@e.&letters&>) fetch y NB. ignore illegals
reps=. {&digits@(letters&i.)&.> valid NB. reps is digit seq
reporttext report (#valid);y;(#~.reps);+/(1<#)/.~reps
) |
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace TextProc3
{
class Program
{
static void Main(string[] args)
{
string line;
int count = 0, maxcount = 0;
List<string> times = new List<string>();
System.IO.StreamReader file = new StreamReader("mlijobs.txt");
while ((line = file.ReadLine()) != null)
{
string[] lineelements = line.Split(' ');
switch (lineelements[1])
{
case "IN":
count--;
break;
case "OUT":
count++;
if (count > maxcount)
{
maxcount = count;
times.Clear();
times.Add(lineelements[3]);
}else if(count == maxcount){
times.Add(lineelements[3]);
}
break;
}
}
file.Close();
Console.WriteLine(maxcount);
foreach (string time in times)
{
Console.WriteLine(time);
}
}
}
}
|
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #F.23 | F# |
let file = @"readings.txt"
let dates = HashSet(HashIdentity.Structural)
let mutable ok = 0
do
for line in System.IO.File.ReadAllLines file do
match String.split [' '; '\t'] line with
| [] -> ()
| date::xys ->
if dates.Contains date then
printf "Date %s is duplicated\n" date
else
dates.Add date
let f (b, t) h = not b, if b then int h::t else t
let _, states = Seq.fold f (false, []) xys
if Seq.forall (fun s -> s >= 1) states then
ok <- ok + 1
printf "%d records were ok\n" ok
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J |
T=:TEMPLATE=: noun define
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
)
nameGame=: monad define
X=. y
Y=. tolower }.^:('aeiouAEIOU' -.@:e.~ {.) y
heady=. tolower {. y
t=. TEMPLATE -. '()'
'ix iy'=. I. 'XY' =/ t
tbox=. ;/ t
match=. heady = (<: iy){::"0 _ tbox
remove =. match # iy
special_rule_box=. a: (<: remove)}tbox
ybox=. (< Y) iy} special_rule_box
XBox=. (< X) ix} ybox
; XBox
)
|
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | import java.util.stream.Stream;
public class NameGame {
private static void printVerse(String name) {
StringBuilder sb = new StringBuilder(name.toLowerCase());
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
String x = sb.toString();
String y = "AEIOU".indexOf(x.charAt(0)) > -1 ? x.toLowerCase() : x.substring(1);
String b = "b" + y;
String f = "f" + y;
String m = "m" + y;
switch (x.charAt(0)) {
case 'B':
b = y;
break;
case 'F':
f = y;
break;
case 'M':
m = y;
break;
default:
// no adjustment needed
break;
}
System.out.printf("%s, %s, bo-%s\n", x, x, b);
System.out.printf("Banana-fana fo-%s\n", f);
System.out.printf("Fee-fi-mo-%s\n", m);
System.out.printf("%s!\n\n", x);
}
public static void main(String[] args) {
Stream.of("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach(NameGame::printVerse);
}
} |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java |
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
public class RTextonyms {
private static final Map<Character, Character> mapping;
private int total, elements, textonyms, max_found;
private String filename, mappingResult;
private Vector<String> max_strings;
private Map<String, Vector<String>> values;
static {
mapping = new HashMap<Character, Character>();
mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2');
mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3');
mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4');
mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5');
mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6');
mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7');
mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8');
mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9');
}
public RTextonyms(String filename) {
this.filename = filename;
this.total = this.elements = this.textonyms = this.max_found = 0;
this.values = new HashMap<String, Vector<String>>();
this.max_strings = new Vector<String>();
return;
}
public void add(String line) {
String mapping = "";
total++;
if (!get_mapping(line)) {
return;
}
mapping = mappingResult;
if (values.get(mapping) == null) {
values.put(mapping, new Vector<String>());
}
int num_strings;
num_strings = values.get(mapping).size();
textonyms += num_strings == 1 ? 1 : 0;
elements++;
if (num_strings > max_found) {
max_strings.clear();
max_strings.add(mapping);
max_found = num_strings;
}
else if (num_strings == max_found) {
max_strings.add(mapping);
}
values.get(mapping).add(line);
return;
}
public void results() {
System.out.printf("Read %,d words from %s%n%n", total, filename);
System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements,
filename);
System.out.printf("They require %,d digit combinations to represent them.%n", values.size());
System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms);
System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1);
for (String key : max_strings) {
System.out.printf("%16s maps to: %s%n", key, values.get(key).toString());
}
System.out.println();
return;
}
public void match(String key) {
Vector<String> match;
match = values.get(key);
if (match == null) {
System.out.printf("Key %s not found%n", key);
}
else {
System.out.printf("Key %s matches: %s%n", key, match.toString());
}
return;
}
private boolean get_mapping(String line) {
mappingResult = line;
StringBuilder mappingBuilder = new StringBuilder();
for (char cc : line.toCharArray()) {
if (Character.isAlphabetic(cc)) {
mappingBuilder.append(mapping.get(Character.toUpperCase(cc)));
}
else if (Character.isDigit(cc)) {
mappingBuilder.append(cc);
}
else {
return false;
}
}
mappingResult = mappingBuilder.toString();
return true;
}
public static void main(String[] args) {
String filename;
if (args.length > 0) {
filename = args[0];
}
else {
filename = "./unixdict.txt";
}
RTextonyms tc;
tc = new RTextonyms(filename);
Path fp = Paths.get(filename);
try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) {
while (fs.hasNextLine()) {
tc.add(fs.nextLine());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
List<String> numbers = Arrays.asList(
"001", "228", "27484247", "7244967473642",
"."
);
tc.results();
for (String number : numbers) {
if (number.equals(".")) {
System.out.println();
}
else {
tc.match(number);
}
}
return;
}
}
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #C.2B.2B | C++ | #include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
const char logfilename[] = "mlijobs.txt";
std::ifstream logfile(logfilename);
if (!logfile.is_open())
{
std::cerr << "Error opening: " << logfilename << "\n";
return -1;
}
int license = 0, max_license = 0;
std::vector<std::string> max_timestamp;
for (std::string logline; std::getline(logfile, logline); )
{
std::string action(logline.substr(8,3));
if (action == "OUT")
{
if (++license >= max_license)
{
if (license > max_license)
{
max_license = license;
max_timestamp.clear();
}
max_timestamp.push_back(logline.substr(14, 19));
}
}
else if (action == "IN ")
{
--license;
}
}
std::cout << "License count at log end: " << license
<< "\nMaximum simultaneous license: " << max_license
<< "\nMaximum license time(s):\n";
std::copy(max_timestamp.begin(), max_timestamp.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
} |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Factor | Factor | USING: io io.encodings.ascii io.files kernel math math.parser
prettyprint sequences sequences.extras sets splitting ;
: check-format ( seq -- )
[ " \t" split length 49 = ] all?
"Format okay." "Format not okay." ? print ;
"readings.txt" ascii file-lines [ check-format ] keep
[ "Duplicates:" print [ "\t" split1 drop ] map duplicates . ]
[ [ " \t" split rest <odds> [ string>number 0 <= ] none? ] count ]
bi pprint " records were good." print |
http://rosettacode.org/wiki/The_Name_Game | The Name Game | Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game".
The regular verse
Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.
The verse for the name 'Gary' would be like this:
Gary, Gary, bo-bary
Banana-fana fo-fary
Fee-fi-mo-mary
Gary!
At the end of every line, the name gets repeated without the first letter: Gary becomes ary
If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:
(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!
Vowel as first letter of the name
If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.
The verse looks like this:
Earl, Earl, bo-bearl
Banana-fana fo-fearl
Fee-fi-mo-mearl
Earl!
'B', 'F' or 'M' as first letter of the name
In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.
The line which would 'rebuild' the name (e.g. bo-billy) is sang without the first letter of the name.
The verse for the name Billy looks like this:
Billy, Billy, bo-illy
Banana-fana fo-filly
Fee-fi-mo-milly
Billy!
For the name 'Felix', this would be right:
Felix, Felix, bo-belix
Banana-fana fo-elix
Fee-fi-mo-melix
Felix!
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 | function singNameGame(name) {
// normalize name
name = name.toLowerCase();
name = name[0].toUpperCase() + name.slice(1);
// ... and sometimes y
// let's pray this works
let firstVowelPos = (function() {
let vowels =
'aeiouàáâãäåæèéêëìíîïòóôõöøùúûüāăąēĕėęěĩīĭįıijōŏőœũūŭůűų'
.split('');
function isVowel(char) {
return vowels.indexOf(char) >= 0;
}
if (isVowel(name[0].toLowerCase())) return 0;
if (name[0] == 'Y' && !isVowel(name[1])) return 0;
if (name[0] == 'Y' && isVowel(name[1])) return 1;
vowels = vowels.concat(vowels, 'yÿý'.split(''));
for (let i = 1; i < name.length; i++)
if (isVowel(name[i])) return i;
})();
let init = name[0].toLowerCase(),
trunk = name.slice(firstVowelPos).toLowerCase(),
b = trunk, f = trunk, m = trunk;
switch (init) {
case 'b': f = 'f' + trunk; m = 'm' + trunk; break;
case 'f': b = 'b' + trunk; m = 'm' + trunk; break;
case 'm': b = 'b' + trunk; f = 'f' + trunk; break;
default: b = 'b' + trunk; f = 'f' + trunk; m = 'm' + trunk;
}
return `
<p>${name}, ${name}, bo-${b}<br>
Banana-fana fo-${f}<br>
Fee-fi-fo-mo-${m}<br>
${name}!<br></p>
`
}
// testing
let names =
'Gary Earl Billy Felix Mary Christine Brian Yvonne Yannick'.split(' ');
for (let i = 0; i < names.length; i++)
document.write(singNameGame(names[i])); |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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 textonym_value:
gsub("a|b|c|A|B|C"; "2")
| gsub("d|e|f|D|E|F"; "3")
| gsub("g|h|i|G|H|I"; "4")
| gsub("j|k|l|J|K|L"; "5")
| gsub("m|n|o|M|N|O"; "6")
| gsub("p|q|r|s|P|Q|R|S"; "7")
| gsub("t|u|v|T|U|V"; "8")
| gsub("w|x|y|z|W|X|Y|Z"; "9");
def explore:
# given an array (or hash), find the maximum length of the items (or values):
def max_length: [.[] | length] | max;
# The length of the longest textonym in the dictionary of numericString => array:
def longest:
[to_entries[] | select(.value|length > 1) | .key | length] | max;
# pretty-print a key-value pair:
def pp: "\(.key) maps to: \(.value|tostring)";
split("\n")
| map(select(test("^[a-zA-Z]+$"))) # select the strictly alphabetic strings
| length as $nwords
| reduce .[] as $line
( {};
($line | textonym_value) as $key
| .[$key] += [$line] )
| max_length as $max_length
| longest as $longest
| "There are \($nwords) words in the Textonyms/wordlist word list that can be represented by the digit-key mapping.",
"They require \(length) digit combinations to represent them.",
"\( [.[] | select(length>1) ] | length ) digit combinations represent Textonyms.",
"The numbers mapping to the most words map to \($max_length) words:",
(to_entries[] | select((.value|length) == $max_length) | pp ),
"The longest Textonyms in the word list have length \($longest):",
(to_entries[] | select((.key|length) == $longest and (.value|length > 1)) | pp)
;
explore |
http://rosettacode.org/wiki/Textonyms | Textonyms | When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.
Assuming the digit keys are mapped to letters as follows:
2 -> ABC
3 -> DEF
4 -> GHI
5 -> JKL
6 -> MNO
7 -> PQRS
8 -> TUV
9 -> WXYZ
Task
Write a program that finds textonyms in a list of words such as
Textonyms/wordlist or
unixdict.txt.
The task should produce a report:
There are #{0} words in #{1} which can be represented by the digit key mapping.
They require #{2} digit combinations to represent them.
#{3} digit combinations represent Textonyms.
Where:
#{0} is the number of words in the list which can be represented by the digit key mapping.
#{1} is the URL of the wordlist being used.
#{2} is the number of digit combinations required to represent the words in #{0}.
#{3} is the number of #{2} which represent more than one word.
At your discretion show a couple of examples of your solution displaying Textonyms.
E.G.:
2748424767 -> "Briticisms", "criticisms"
Extra credit
Use a word list and keypad mapping other than English.
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 | using Printf
const tcode = (Regex=>Char)[r"A|B|C|Ä|Å|Á|Â|Ç" => '2',
r"D|E|F|È|Ê|É" => '3',
r"G|H|I|Í" => '4',
r"J|K|L" => '5',
r"M|N|O|Ó|Ö|Ô|Ñ" => '6',
r"P|Q|R|S" => '7',
r"T|U|V|Û|Ü" => '8',
r"W|X|Y|Z" => '9']
function tpad(str::IOStream)
tnym = (String=>Array{String,1})[]
for w in eachline(str)
w = chomp(w)
t = uppercase(w)
for (k,v) in tcode
t = replace(t, k, v)
end
t = replace(t, r"\D", '1')
tnym[t] = [get(tnym, t, String[]), w]
end
return tnym
end
|
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use | Text processing/Max licenses in use | A company currently pays a fixed sum for the use of a particular licensed software package. In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file.
Assume the software's licensing daemon faithfully records a checkout event when a copy of the software starts and a checkin event when the software finishes to its log file.
An example of checkout and checkin events are:
License OUT @ 2008/10/03_23:51:05 for job 4974
...
License IN @ 2008/10/04_00:18:22 for job 4974
Task
Save the 10,000 line log file from here into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
Mirror of log file available as a zip here (offsite mirror).
| #Clojure | Clojure | (defn delta [entry]
(case (second (re-find #"\ (.*)\ @" entry))
"IN " -1
"OUT" 1
(throw (Exception. (str "Invalid entry:" entry)))))
(defn t [entry]
(second (re-find #"@\ (.*)\ f" entry)))
(let [entries (clojure.string/split (slurp "mlijobs.txt") #"\n")
in-use (reductions + (map delta entries))
m (apply max in-use)
times (map #(nth (map t entries) %)
(keep-indexed #(when (= m %2) %1) in-use))]
(println "Maximum simultaneous license use is" m "at the following times:")
(map println times)) |
http://rosettacode.org/wiki/Text_processing/2 | Text processing/2 | The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
The fields (from the left) are:
DATESTAMP [ VALUEn FLAGn ] * 24
i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
A sample from the full data file readings.txt, which is also used in the Text processing/1 task, follows:
Data is no longer available at that link. Zipped mirror available here
1991-03-30 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1
1991-03-31 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 10.000 1 20.000 1 20.000 1 20.000 1 35.000 1 50.000 1 60.000 1 40.000 1 30.000 1 30.000 1 30.000 1 25.000 1 20.000 1 20.000 1 20.000 1 20.000 1 20.000 1 35.000 1
1991-03-31 40.000 1 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2 0.000 -2
1991-04-01 0.000 -2 13.000 1 16.000 1 21.000 1 24.000 1 22.000 1 20.000 1 18.000 1 29.000 1 44.000 1 50.000 1 43.000 1 38.000 1 27.000 1 27.000 1 24.000 1 23.000 1 18.000 1 12.000 1 13.000 1 14.000 1 15.000 1 13.000 1 10.000 1
1991-04-02 8.000 1 9.000 1 11.000 1 12.000 1 12.000 1 12.000 1 27.000 1 26.000 1 27.000 1 33.000 1 32.000 1 31.000 1 29.000 1 31.000 1 25.000 1 25.000 1 24.000 1 21.000 1 17.000 1 14.000 1 15.000 1 12.000 1 12.000 1 10.000 1
1991-04-03 10.000 1 9.000 1 10.000 1 10.000 1 9.000 1 10.000 1 15.000 1 24.000 1 28.000 1 24.000 1 18.000 1 14.000 1 12.000 1 13.000 1 14.000 1 15.000 1 14.000 1 15.000 1 13.000 1 13.000 1 13.000 1 12.000 1 10.000 1 10.000 1
Task
Confirm the general field format of the file.
Identify any DATESTAMPs that are duplicated.
Report the number of records that have good readings for all instruments.
| #Fortran | Fortran |
Crunches a set of hourly data. Starts with a date, then 24 pairs of value,indicator for that day, on one line.
INTEGER Y,M,D !Year, month, and day.
INTEGER GOOD(24,2) !The indicators.
REAL*8 V(24,2) !The grist.
CHARACTER*10 DATE(2) !Along with the starting date.
INTEGER IT,TI !A flipper and its antiflipper.
INTEGER NV !Number of entirely good records.
INTEGER I,NREC,HIC !Some counters.
LOGICAL INGOOD !State flipper for the runs of data.
INTEGER IN,MSG !I/O mnemonics.
CHARACTER*666 ACARD !Scratchpad, of sufficient length for all expectation.
IN = 10 !Unit number for the input file.
MSG = 6 !Output.
OPEN (IN,FILE="Readings1.txt", FORM="FORMATTED", !This should be a function.
1 STATUS ="OLD",ACTION="READ") !Returning success, or failure.
NV = 0 !No pure records seen.
NREC = 0 !No records read.
HIC = 0 !Provoking no complaints.
DATE = "snargle" !No date should look like this!
IT = 2 !Syncopation for the 1-2 flip flop.
Chew into the file.
10 READ (IN,11,END=100,ERR=666) L,ACARD(1:MIN(L,LEN(ACARD))) !With some protection.
NREC = NREC + 1 !So, a record has been read.
11 FORMAT (Q,A) !Obviously, Q ascertains the length of the record being read.
READ (ACARD,12,END=600,ERR=601) Y,M,D !The date part is trouble, as always.
12 FORMAT (I4,2(1X,I2)) !Because there are no delimiters between the parts.
TI = IT !Thus finger the previous value.
IT = 3 - IT !Flip between 1 and 2.
DATE(IT) = ACARD(1:10) !Save the date field.
READ (ACARD(11:L),*,END=600,ERR=601) (V(I,IT),GOOD(I,IT),I = 1,24) !But after the date, delimiters abound.
Comparisons. Should really convert the date to a daynumber, check it by reversion, and then check for + 1 day only.
20 IF (DATE(IT).EQ.DATE(TI)) THEN !Same date?
IF (ALL(V(:,IT) .EQ.V(:,TI)) .AND. !Yes. What about the data?
1 ALL(GOOD(:,IT).EQ.GOOD(:,TI))) THEN !This disregards details of the spacing of the data.
WRITE (MSG,21) NREC,DATE(IT),"same." !Also trailing zeroes, spurious + signs, blah blah.
21 FORMAT ("Record",I8," Duplicate date field (",A,"), data ",A) !Say it.
ELSE !But if they're not all equal,
WRITE (MSG,21) NREC,DATE(IT),"different!" !They're different!
END IF !So much for comparing the data.
END IF !So much for just comparing the date's text.
IF (ALL(GOOD(:,IT).GT.0)) NV = NV + 1 !A fully healthy record, either way?
GO TO 10 !More! More! I want more!!
Complaints. Should really distinguish between trouble in the date part and in the data part.
600 WRITE (MSG,*) '"END" declared - insufficient data?' !Not enough numbers, presumably.
GO TO 602 !Reveal the record.
601 WRITE (MSG,*) '"ERR" declared - improper number format?' !Ah, but which number?
602 WRITE (MSG,603) NREC,L,ACARD(1:L) !Anyway, reveal the uninterpreted record.
603 FORMAT("Record",I8,", length ",I0," reads ",A) !Just so.
HIC = HIC + 1 !This may grow into a habit.
IF (HIC.LE.12) GO TO 10 !But if not yet, try the next record.
STOP "Enough distaste." !Or, give up.
666 WRITE (MSG,101) NREC,"format error!" !For A-style data? Should never happen!
GO TO 900 !But if it does, give up!
Closedown.
100 WRITE (MSG,101) NREC,"then end-of-file" !Discovered on the next attempt.
101 FORMAT ("Record",I8,": ",A) !A record number plus a remark.
WRITE (MSG,102) NV !The overall results.
102 FORMAT (" with",I8," having all values good.") !This should do.
900 CLOSE(IN) !Done.
END !Spaghetti rules.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.