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/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
import Data.List (maximumBy, sort, unfoldr)
import Data.Ord (comparing)
import qualified Data.Map as M
import qualified Data.Set as S
-- Lists of words grouped by their "signatures". A signature is a sorted
-- list of characters. Duplicate words stored in sets.
groupBySig :: [String] -> [(String, S.Set String)]
groupBySig = map ((,) . sort <*> S.singleton)
-- Groups as lists of equivalent words.
equivs :: [(String, S.Set String)] -> [[String]]
equivs = map (S.toList . snd) . M.toList . M.fromListWith S.union
-- True if a pair of words differs in all character positions.
isDerangement :: (String, String) -> Bool
isDerangement (a, b) = and $ zipWith (/=) a b
-- All pairs of elements, ignoring order.
pairs :: [t] -> [(t, t)]
pairs = concat . unfoldr step
where
step (x:xs) = Just (map (x, ) xs, xs)
step [] = Nothing
-- All anagram pairs in the input string.
anagrams :: [String] -> [(String, String)]
anagrams = concatMap pairs . equivs . groupBySig
-- The pair of words forming the longest deranged anagram.
maxDerangedAnagram :: [String] -> Maybe (String, String)
maxDerangedAnagram = maxByLen . filter isDerangement . anagrams
where
maxByLen [] = Nothing
maxByLen xs = Just $ maximumBy (comparing (length . fst)) xs
main :: IO ()
main = do
input <- readFile "unixdict.txt"
case maxDerangedAnagram $ words input of
Nothing -> putStrLn "No deranged anagrams were found."
Just (a, b) -> putStrLn $ "Longest deranged anagrams: " <> a <> " and " <> b |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Fortran | Fortran | integer function fib(n)
integer, intent(in) :: n
if (n < 0 ) then
write (*,*) 'Bad argument: fib(',n,')'
stop
else
fib = purefib(n)
end if
contains
recursive pure integer function purefib(n) result(f)
integer, intent(in) :: n
if (n < 2 ) then
f = n
else
f = purefib(n-1) + purefib(n-2)
end if
end function purefib
end function fib |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Python | Python | PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize2rad(a):
while a < 0: a += TWO_PI
while a >= TWO_PI: a -= TWO_PI
return a
def deg2grad(a): return a * 10.0 / 9.0
def deg2mil(a): return a * 160.0 / 9.0
def deg2rad(a): return a * PI / 180.0
def grad2deg(a): return a * 9.0 / 10.0
def grad2mil(a): return a * 16.0
def grad2rad(a): return a * PI / 200.0
def mil2deg(a): return a * 9.0 / 160.0
def mil2grad(a): return a / 16.0
def mil2rad(a): return a * PI / 3200.0
def rad2deg(a): return a * 180.0 / PI
def rad2grad(a): return a * 200.0 / PI
def rad2mil(a): return a * 3200.0 / PI |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #D | D | void main() @safe /*@nogc*/ {
import std.stdio, std.algorithm, std.range, std.typecons, std.array;
immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ =>
iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0);
enum rangeMax = 20_000;
auto n2d = iota(1, rangeMax + 1).map!(n => properDivs(n).sum);
foreach (immutable n, immutable divSum; n2d.enumerate(1))
if (n < divSum && divSum <= rangeMax && n2d[divSum - 1] == n)
writefln("Amicable pair: %d and %d with proper divisors:\n %s\n %s",
n, divSum, properDivs(n), properDivs(divSum));
} |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #JavaScript_.2B_HTML | JavaScript + HTML | <html> <head>
<title>RC: Basic Animation</title>
<script type="text/javascript">
function animate(id) {
var element = document.getElementById(id);
var textNode = element.childNodes[0]; // assuming no other children
var text = textNode.data;
var reverse = false;
element.onclick = function () { reverse = !reverse; };
setInterval(function () {
if (reverse)
text = text.substring(1) + text[0];
else
text = text[text.length - 1] + text.substring(0, text.length - 1);
textNode.data = text;
}, 100);
}
</script>
</head> <body onload="animate('target')">
<pre id="target">Hello World! </pre>
</body> </html> |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Euler_Math_Toolbox | Euler Math Toolbox | >g=gearth$; l=1m;
>function f(x,y) := [y[2],-g*sin(y[1])/l]
>function h(a) := ode("f",linspace(0,a,100),[0,2])[1,-1]
>period=solve("h",2)
2.06071780729
>t=linspace(0,period,30); s=ode("f",t,[0,2])[1];
>function anim (t,s) ...
$ setplot(-1,1,-1,1);
$ markerstyle("o#");
$ repeat
$ for i=1 to cols(t)-1;
$ clg;
$ hold on;
$ plot([0,sin(s[i])],[1,1-cos(s[i])]);
$ mark([0,sin(s[i])],[1,1-cos(s[i])]);
$ hold off;
$ wait(t[i+1]-t[i]);
$ end;
$ until testkey();
$ end
$endfunction
>anim(t,s);
>
|
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #dc | dc | [* factorial *]sz
[ 1 Sp [ d lp * sp 1 - d 1 <f ]Sf d 1 <f Lfsz sz Lp ]sF
[* nth integral term *]sz
[ sn 32 6 ln * lFx 532 ln * ln * 126 ln * + 9 + * * 3 ln lFx 6 ^ * / ]sI
[* nth exponent of 10 *]sz
[ 1 + 6 * 3 r - ]sE
[* nth term in series *]sz
[ d lIx r 10 r lEx _1 * ^ / ]sA
[* sum of the first n terms *]sz
[ [li lAx ls + ss li 1 - d si 0 r !<L]sL si 0ss lLx ls]sS
[* approximation of pi after n terms *]sz
[ lSx 1 r / v ]sP
[* count digits in a number *]sz
[sn 0 sd lCx ld]sD
[ld 1 + sd ln 10 0k / d sn 0 !=C]sC
[* print a number in a given column width *]sz
[sw d lDx si lw li <T n]sW
[[ ]n li 1 + si lw li <T]sT
[* main loop: print values for first 10 terms *]sz
[N. Integral part of Nth term .................. × 10^ =Actual value of Nth term]p
0 sj
[
lj n [. ]n
lj lIx 0k 1 / 44 lWx [ ]n
lj lEx 4 lWx [ ]n
lj 99k lAx 50k 1 / p
lj 1 + d sj 10 >M
] sM
lMx
[]p
[* print resulting value of pi to 70 places *]sz
[Pi after ]n 52n [ iterations:]p
99k 52 lPx 70k 1 / p |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Erlang | Erlang |
-mode(compile).
% Integer math routines: factorial, power, square root, integer logarithm.
%
fac(N) -> fac(N, 1).
fac(N, A) when N < 2 -> A;
fac(N, A) -> fac(N - 1, N*A).
pow(_, N) when N < 0 -> pow_domain_error;
pow(2, N) -> 1 bsl N;
pow(A, N) -> ipow(A, N).
ipow(_, 0) -> 1;
ipow(A, 1) -> A;
ipow(A, 2) -> A*A;
ipow(A, N) ->
case N band 1 of
0 -> X = ipow(A, N bsr 1), X*X;
1 -> A * ipow(A, N - 1)
end.
% integer logarithm, based on Zeckendorf representations of integers.
% https://www.keithschwarz.com/interesting/code/?dir=zeckendorf-logarithm
% we need this, since the exponents get larger than IEEE-754 double can handle.
lognext({A, B, S, T}) -> {B, A+B, T, S*T}.
logprev({A, B, S, T}) -> {B-A, A, T div S, S}.
ilog(A, B) when (A =< 0) or (B < 2) -> ilog_domain_error;
ilog(A, B) ->
UBound = bracket(A, {0, 1, 1, B}),
backlog(A, UBound, 0).
bracket(A, State = {_, _, _, T}) when T > A -> State;
bracket(A, State) -> bracket(A, lognext(State)).
backlog(_, {0, _, 1, _}, Log) -> Log;
backlog(N, State = {A, _, S, _}, Log) when S =< N ->
backlog(N div S, logprev(State), Log + A);
backlog(N, State, Log) -> backlog(N, logprev(State), Log).
isqrt(N) when N < 0 -> isqrt_domain_error;
isqrt(N) ->
X0 = pow(2, ilog(N, 2) div 2),
iterate(N, newton(X0, N), N).
iterate(A, B, _) when A =< B -> A;
iterate(_, B, N) -> iterate(B, newton(B, N), N).
newton(X, N) -> (X + N div X) div 2.
% With this out of the way, we can get down to some serious calculation.
%
term(N) -> { % returns numerator and log10 of the denominator.
(fac(6*N)*(N*(532*N + 126) + 9) bsl 5) div (3*pow(fac(N), 6)),
6*N + 3
}.
neg_term({N, D}) -> {-N, D}.
abs_term({N, D}) -> {abs(N), D}.
add_term(T1 = {_, D1}, T2 = {_, D2}) when D1 > D2 -> add_term(T2, T1);
add_term({N1, D1}, {N2, D2}) ->
Scale = pow(10, D2 - D1),
{N1*Scale + N2, D2}.
calculate(Prec) -> calculate(Prec, {0, 0}, 0).
calculate(Prec, T0, K) ->
T1 = add_term(T0, term(K)),
{N, D} = abs_term(add_term(neg_term(T1), T0)),
Accuracy = D - ilog(N, 10),
if
Accuracy < Prec -> calculate(Prec, T1, K + 1);
true -> T1
end.
get_pi(Prec) ->
{N0, D0} = calculate(Prec),
% from the term, t = n0/10^d0, calculate 1/√t
% if the denominator is an odd power of 10, add 1 to the denominator and multiply the numerator by 10.
{N, D} = case D0 band 1 of
0 -> {N0, D0};
1 -> {10*N0, D0 + 1}
end,
[Three|Rest] = lists:sublist(
integer_to_list(pow(10, D) div isqrt(N)), Prec),
[Three, $. | Rest].
show_term({A, Decimals}) ->
Str = integer_to_list(A),
[$0, $.] ++ lists:duplicate(Decimals - length(Str), $0) ++ Str.
main(_) ->
Terms = [term(N) || N <- lists:seq(0, 9)],
io:format("The first 10 terms as scaled decimals are:~n"),
[io:format(" ~s~n", [show_term(T)]) || T <- Terms],
io:format("~nThe sum of these terms (pi^-2) is ~s~n",
[show_term(lists:foldl(fun add_term/2, {0, 0}, Terms))]),
Pi70 = get_pi(71),
io:format("~npi to 70 decimal places:~n"),
io:format("~s~n", [Pi70]).
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #11l | 11l | F k_prime(k, =n)
V f = 0
V p = 2
L f < k & p * p <= n
L n % p == 0
n /= p
f++
p++
R f + (I n > 1 {1} E 0) == k
F primes(k, n)
V i = 2
[Int] list
L list.len < n
I k_prime(k, i)
list [+]= i
i++
R list
L(k) 1..5
print(‘k = ’k‘: ’primes(k, 10)) |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Factor | Factor | USING: combinators generalizations kernel math prettyprint ;
IN: rosetta-code.bearings
: delta-bearing ( x y -- z )
swap - 360 mod {
{ [ dup 180 > ] [ 360 - ] }
{ [ dup -180 < ] [ 360 + ] }
[ ]
} cond ;
: bearings-demo ( -- )
20 45
-45 45
-85 90
-95 90
-45 125
-45 145
29.4803 -88.6381
-78.3251 -159.036
-70099.74233810938 29840.67437876723
-165313.6666297357 33693.9894517456
1174.8380510598456 -154146.66490124757
60175.77306795546 42213.07192354373
[ delta-bearing . ] 2 12 mnapply ;
MAIN: bearings-demo |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Icon_and_Unicon | Icon and Unicon | link strings # for csort() procedure
procedure main()
anagrams := table() # build lists of anagrams
every *(word := !&input) > 1 do {
canon := csort(word)
/anagrams[canon] := []
put(anagrams[canon], word)
}
longest := 1 # find a longest derangement
every *(aList := !anagrams) > 1 do
if derangement := derange(aList) then
if longest <:= *derangement[1] then long := derangement
every writes((!\long||" ")|"\n") # show longest
end
procedure derange(aList) # Return a single derangement from this list
while aWord := get(aList) do return noMatch(aWord, !aList)
end
procedure noMatch(s1,s2) # Produce pair only if s1,s2 are deranged.
every i := 1 to *s1 do if s1[i] == s2[i] then fail
return [s1,s2]
end |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Lang "fblite"
Option Gosub '' enables Gosub to be used
' Using gosub to simulate a nested function
Function fib(n As UInteger) As UInteger
Gosub nestedFib
Exit Function
nestedFib:
fib = IIf(n < 2, n, fib(n - 1) + fib(n - 2))
Return
End Function
' This function simulates (rather messily) gosub by using 2 gotos and would therefore work
' even in the default dialect
Function fib2(n As UInteger) As UInteger
Goto nestedFib
exitFib:
Exit Function
nestedFib:
fib2 = IIf(n < 2, n, fib2(n - 1) + fib2(n - 2))
Goto exitFib
End Function
For i As Integer = 1 To 12
Print fib(i); " ";
Next
Print
For j As Integer = 1 To 12
Print fib2(j); " ";
Next
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Racket | Racket | #lang racket
(define (rem n m)
(let* ((m (abs m)) (-m (- m)))
(let recur ((n n))
(cond [(< n -m) (recur (+ n m))]
[(>= n m) (recur (- n m))]
[else n]))))
(define 2.pi (* 2 pi))
(define (deg->deg a) (rem a 360))
(define (grad->grad a) (rem a 400))
(define (mil->mil a) (rem a 6400))
(define (rad->rad a) (rem a 2.pi))
(define (deg->grad a) (grad->grad (* (/ a 360) 400)))
(define (deg->rad a) (rad->rad (* (/ a 360) 2.pi)))
(define (deg->mil a) (mil->mil (* (/ a 360) 6400)))
(define (grad->deg a) (deg->deg (* (/ a 400) 360)))
(define (grad->rad a) (rad->rad (* (/ a 400) 2.pi)))
(define (grad->mil a) (mil->mil (* (/ a 400) 6400)))
(define (mil->deg a) (deg->deg (* (/ a 6400) 360)))
(define (mil->grad a) (grad->grad (* (/ a 6400) 400)))
(define (mil->rad a) (rad->rad (* (/ a 6400) 2.pi)))
(define (rad->deg a) (deg->deg (* (/ a 2.pi) 360)))
(define (rad->grad a) (grad->grad (* (/ a 2.pi) 400)))
(define (rad->mil a) (mil->mil (* (/ a 2.pi) 6400)))
(define (tabulate #:fmt (fmt (λ (v) (~a (exact->inexact v) #:align 'right #:width 15))) head . vs)
(string-join (cons (~a #:width 6 head) (map fmt vs)) " | "))
(define (report-angle a)
(string-join
(list
(tabulate #:fmt (λ (x) (~a x #:width 15 #:align 'center)) "UNIT" "VAL*" "DEG" "GRAD" "MIL" "RAD")
(tabulate "Deg" a (deg->deg a) (deg->grad a) (deg->mil a) (deg->rad a))
(tabulate "Grad" a (grad->deg a) (grad->grad a) (grad->mil a) (grad->rad a))
(tabulate "Mil" a (mil->deg a) (mil->grad a) (mil->mil a) (mil->rad a))
(tabulate "Rad" a (rad->deg a) (rad->grad a) (rad->mil a) (rad->rad a)))
"\n"))
(module+ test
(displayln
(string-join (map report-angle '(-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000))
"\n\n"))) |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Raku | Raku |
my @units =
{ code => 'd', name => 'degrees' , number => 360 },
{ code => 'g', name => 'gradians', number => 400 },
{ code => 'm', name => 'mills' , number => 6400 },
{ code => 'r', name => 'radians' , number => tau },
;
my Code %cvt = (@units X @units).map: -> ($a, $b) {
"{$a.<code>}2{$b.<code>}" => sub ($angle) {
my $norm = $angle % $a.<number>
- ( $a.<number> if $angle < 0 );
$norm * $b.<number> / $a.<number>
}
}
say ' Angle Unit ', @units».<name>».tc.fmt('%11s');
for -2, -1, 0, 1, 2, tau, 16, 360/tau, 360-1, 400-1, 6400-1, 1_000_000 -> $angle {
say '';
for @units -> $from {
my @sub_keys = @units.map: { "{$from.<code>}2{.<code>}" };
my @results = %cvt{@sub_keys}».($angle);
say join ' ', $angle .fmt('%10g'),
$from.<name>.fmt('%-8s'),
@results .fmt('%11g');
}
} |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Delphi | Delphi | /* Fill a given array such that for each N,
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
word i, j, max;
max := dim(p,1)-1;
for i from 0 upto max do p[i] := 0 od;
for i from 1 upto max/2 do
for j from i*2 by i upto max do
p[j] := p[j] + i
od
od
corp
/* Find all amicable pairs between 0 and 20,000 */
proc nonrec main() void:
word MAX = 20000;
word i, j;
[MAX] word p;
propdivs(p);
for i from 1 upto MAX-1 do
for j from i+1 upto MAX-1 do
if p[i]=j and p[j]=i then
writeln(i:5, ", ", j:5)
fi
od
od
corp |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #JavaScript_.2B_SVG | JavaScript + SVG | <svg xmlns="http://www.w3.org/2000/svg"
width="100" height="40">
<script type="text/javascript">
function animate(element) {
var textNode = element.childNodes[0]; // assuming no other children
var text = textNode.data;
var reverse = false;
element.onclick = function () { reverse = !reverse; };
setInterval(function () {
if (reverse)
text = text.substring(1) + text[0];
else
text = text[text.length - 1] + text.substring(0, text.length - 1);
textNode.data = text;
}, 100);
}
</script>
<rect width="100" height="40" fill="yellow"/>
<text x="2" y="20" onload="animate(this);">Hello World! </text>
</svg> |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Euphoria | Euphoria | include graphics.e
include misc.e
constant dt = 1E-3
constant g = 50
sequence vc
sequence suspension
atom len
procedure draw_pendulum(atom color, atom len, atom alfa)
sequence point
point = (len*{sin(alfa),cos(alfa)} + suspension)
draw_line(color, {suspension, point})
ellipse(color,0,point-{10,10},point+{10,10})
end procedure
function wait()
atom t0
t0 = time()
while time() = t0 do
if get_key() != -1 then
return 1
end if
end while
return 0
end function
procedure animation()
atom alfa, omega, epsilon
if graphics_mode(18) then
end if
vc = video_config()
suspension = {vc[VC_XPIXELS]/2,vc[VC_YPIXELS]/2}
len = vc[VC_YPIXELS]/2-20
alfa = PI/2
omega = 0
while 1 do
draw_pendulum(BRIGHT_WHITE,len,alfa)
if wait() then
exit
end if
draw_pendulum(BLACK,len,alfa)
epsilon = -len*sin(alfa)*g
omega += dt*epsilon
alfa += dt*omega
end while
if graphics_mode(-1) then
end if
end procedure
animation() |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #F.23 | F# |
// Almkvist-Giullera formula for pi. Nigel Galloway: August 17th., 2021
let factorial(n:bigint)=MathNet.Numerics.SpecialFunctions.Factorial n
let fN g=(532I*g*g+126I*g+9I)*(factorial(6I*g))/(3I*(factorial g)**6)
[0..9]|>Seq.iter(bigint>>fN>>(*)32I>>printfn "%A\n")
let _,n=Seq.unfold(fun(n,g)->let n=n*(10I**6)+fN g in Some(Isqrt((10I**(145+6*(int g)))/(32I*n)),(n,g+1I)))(0I,0I)|>Seq.pairwise|>Seq.find(fun(n,g)->n=g)
printfn $"""pi to 70 decimal places is %s{(n.ToString()).Insert(1,".")}"""
|
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Factor | Factor | USING: continuations formatting io kernel locals math
math.factorials math.functions sequences ;
:: integer-term ( n -- m )
32 6 n * factorial * 532 n sq * 126 n * + 9 + *
n factorial 6 ^ 3 * / ;
: exponent-term ( n -- m ) 6 * 3 + neg ;
: nth-term ( n -- x )
[ integer-term ] [ exponent-term 10^ * ] bi ;
! Factor doesn't have an arbitrary-precision square root afaik,
! so make one using Heron's method.
: sqrt-approx ( r x -- r' x ) [ over / + 2 / ] keep ;
:: almkvist-guillera ( precision -- x )
0 0 :> ( summed! next-add! )
[
100,000,000 <iota> [| n |
summed n nth-term + next-add!
next-add summed - abs precision neg 10^ <
[ return ] when
next-add summed!
] each
] with-return
next-add ;
CONSTANT: 1/pi 113/355 ! Use as initial guess for square root approximation
: pi ( -- )
1/pi 70 almkvist-guillera 5 [ sqrt-approx ] times
drop recip "%.70f\n" printf ;
! Task
"N Integer Portion Pow Nth Term (33 dp)" print
89 CHAR: - <repetition> print
10 [
dup [ integer-term ] [ exponent-term ] [ nth-term ] tri
"%d %44d %3d %.33f\n" printf
] each-integer nl
"Pi to 70 decimal places:" print pi |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Action.21 | Action! | BYTE FUNC IsAlmostPrime(INT num BYTE k)
INT f,p,v
f=0 p=2 v=num
WHILE f<k AND p*p<=num
DO
WHILE v MOD p=0
DO
v==/p f==+1
OD
p==+1
OD
IF v>1 THEN
f==+1
FI
IF f=k THEN
RETURN (1)
FI
RETURN (0)
PROC Main()
BYTE count,k
INT i
FOR k=1 TO 5
DO
PrintF("k=%B:",k)
count=0 i=2
WHILE count<10
DO
IF IsAlmostPrime(i,k) THEN
PrintF(" %I",i)
count==+1
FI
i==+1
OD
PutE()
OD
RETURN |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Ada | Ada | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10; -- 10 k-th almost primes
N: Positive; -- the "current number" to be checked
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop; -- now N is Kth almost prime;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime; |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Forth | Forth |
: Angle-Difference-stack ( b1 b2 - a +/-180)
\ Algorithm with stack manipulation without branches ( s. Frotran Groovy)
fswap f- \ Delta angle
360e fswap fover fmod \ mod 360
fover 1.5e f* f+ \ + 540
fover fmod \ mod 360
fswap f2/ f- \ - 180
;
: Angle-Difference-const ( b1 b2 - a +/-180)
\ Algorithm without Branches ( s. Fotran Groovy)
fswap f-
360e fmod
540e f+
360e fmod
180e f-
;
\ Test Word for requested tests
: test-ad ( b1 b2 -- )
fover fover
Angle-Difference-stack f.
Angle-Difference-const f.
;
|
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J | #words=: 'b' freads 'unixdict.txt'
25104
#anagrams=: (#~ 1 < #@>) (</.~ /:~&>) words
1303
#maybederanged=: (#~ (1 -.@e. #@~."1)@|:@:>&>) anagrams
432
#longest=: (#~ [: (= >./) #@>@{.@>) maybederanged
1
longest
┌───────────────────────┐
│┌──────────┬──────────┐│
││excitation│intoxicate││
│└──────────┴──────────┘│
└───────────────────────┘ |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func main() {
for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
f, ok := arFib(n)
if ok {
fmt.Printf("fib %d = %d\n", n, f)
} else {
fmt.Println("fib undefined for negative numbers")
}
}
}
func arFib(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n < 2:
return n, true
}
return yc(func(recurse fn) fn {
return func(left, term1, term2 int) int {
if left == 0 {
return term1+term2
}
return recurse(left-1, term1+term2, term1)
}
})(n-2, 1, 0), true
}
type fn func(int, int, int) int
type ff func(fn) fn
type fx func(fx) fn
func yc(f ff) fn {
return func(x fx) fn {
return x(x)
}(func(x fx) fn {
return f(func(a1, a2, a3 int) int {
return x(x)(a1, a2, a3)
})
})
} |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #REXX | REXX | /*REXX pgm normalizes an angle (in a scale), or converts angles from a scale to another.*/
numeric digits length( pi() ) - length(.) /*use the "length" of pi for precision.*/
parse arg x /*obtain optional arguments from the CL*/
if x='' | x="," then x= '-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000'
w= 20; w7= w+7 /*W: # dec digits past the dec. point.*/
@deg = 'degrees'; @grd= "gradians"; @mil = 'mils'; @rad = "radians"
# = words(x)
call hdr @deg @grd @mil @rad
do j=1 for #; y= word(x,j)
say shw(y) fmt(d2d(y)) fmt(d2g(y)) fmt(d2m(y)) fmt(d2r(y))
end /*j*/
call hdr @grd @deg @mil @rad
do j=1 for #; y= word(x,j)
say shw(y) fmt(g2g(y)) fmt(g2d(y)) fmt(g2m(y)) fmt(g2r(y))
end /*j*/
call hdr @mil @deg @grd @rad
do j=1 for #; y= word(x,j)
say shw(y) fmt(m2m(y)) fmt(m2d(y)) fmt(m2g(y)) fmt(m2r(y))
end /*j*/
call hdr @rad @deg @grd @mil
do j=1 for #; y= word(x,j)
say shw(y) fmt(r2r(y)) fmt(r2d(y)) fmt(r2g(y)) fmt(r2m(y))
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fmt: _= format(arg(1), 6,w); L= length(_); return left(format(_/1, 6),L) /*align a #*/
shw: _= format(arg(1),12,9); L= length(_); return left(format(_/1,12),L) /* " " "*/
pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078; return pi
d2g: return d2d(arg(1)) * 10 / 9 /*convert degrees ───► gradians. */
d2m: return d2d(arg(1)) * 160 / 9 /*convert degrees ───► mils. */
d2r: return d2d(arg(1)) * pi() / 180 /*convert degrees ───► radians. */
g2d: return g2g(arg(1)) * 0.9 /*convert gradians ───► degrees. */
g2m: return g2g(arg(1)) * 16 /*convert gradians ───► mils. */
g2r: return g2g(arg(1)) * pi() * 0.005 /*convert gradians ───► radians. */
m2d: return m2m(arg(1)) * 9 * 0.00625 /*convert mils ───► degrees. */
m2g: return m2m(arg(1)) / 16 /*convert mils ───► gradians. */
m2r: return m2m(arg(1)) * pi() / 3200 /*convert mils ───► radians. */
r2d: return r2r(arg(1)) * 180 / pi() /*convert radians ───► degrees. */
r2g: return r2r(arg(1)) * 200 / pi() /*convert radians ───► gradians. */
r2m: return r2r(arg(1)) * 3200 / pi() /*convert radians ───► mils. */
d2d: return arg(1) // 360 /*normalize degrees ───► a unit circle.*/
g2g: return arg(1) // 400 /*normalize gradians───► a unit circle.*/
m2m: return arg(1) // 6400 /*normalize mils ───► a unit circle.*/
r2r: return arg(1) // (pi() * 2) /*normalize radians ───► a unit circle.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
hdr: parse arg #o #a #b #c .; _= '═'; say /* [↓] the header line*/
@n = 'normalized'
say center(#o,23 ) center(@n #o,w7) center(#a,w7 ) center(#b,w7 ) center(#c,w7 )
say center('',23,_) center('',w7, _) center('',w7,_) center('',w7,_) center('',w7,_)
return /* '↑' seperator line.*/ |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Draco | Draco | /* Fill a given array such that for each N,
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
word i, j, max;
max := dim(p,1)-1;
for i from 0 upto max do p[i] := 0 od;
for i from 1 upto max/2 do
for j from i*2 by i upto max do
p[j] := p[j] + i
od
od
corp
/* Find all amicable pairs between 0 and 20,000 */
proc nonrec main() void:
word MAX = 20000;
word i, j;
[MAX] word p;
propdivs(p);
for i from 1 upto MAX-1 do
for j from i+1 upto MAX-1 do
if p[i]=j and p[j]=i then
writeln(i:5, ", ", j:5)
fi
od
od
corp |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Julia | Julia |
using Tk
const frameinterval = 0.12 # partial seconds between change on screen display
function windowanim(stepinterval::Float64)
wind = Window("Animation", 300, 100)
frm = Frame(wind)
hello = "Hello World! "
but = Button(frm, width=30, text=hello)
rightward = true
callback(s) = (rightward = !rightward)
bind(but, "command", callback)
pack(frm, expand=true, fill = "both")
pack(but, expand=true, fill = "both")
permut = [hello[i:end] * hello[1:i-1] for i in length(hello)+1:-1:2]
ppos = 1
pmod = length(permut)
while true
but[:text] = permut[ppos]
sleep(stepinterval)
if rightward
ppos += 1
if ppos > pmod
ppos = 1
end
else
ppos -= 1
if ppos < 1
ppos = pmod
end
end
end
end
windowanim(frameinterval)
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Kotlin | Kotlin | // version 1.1.0
import java.awt.Dimension
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.JFrame
import javax.swing.JLabel
class Rotate : JFrame() {
val text = "Hello World! "
val label = JLabel(text)
var rotRight = true
var startIdx = 0
init {
preferredSize = Dimension(96, 64)
label.addMouseListener(object: MouseAdapter() {
override fun mouseClicked(evt: MouseEvent) {
rotRight = !rotRight
}
})
add(label)
pack()
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
isVisible = true
}
}
fun getRotatedText(text: String, startIdx: Int): String {
val ret = StringBuilder()
var i = startIdx
do {
ret.append(text[i++])
i %= text.length
}
while (i != startIdx)
return ret.toString()
}
fun main(args: Array<String>) {
val rot = Rotate()
val task = object : TimerTask() {
override fun run() {
if (rot.rotRight) {
if (--rot.startIdx < 0) rot.startIdx += rot.text.length
}
else {
if (++rot.startIdx >= rot.text.length) rot.startIdx -= rot.text.length
}
rot.label.text = getRotatedText(rot.text, rot.startIdx)
}
}
Timer(false).schedule(task, 0, 500)
} |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #F.23 | F# | open System
open System.Drawing
open System.Windows.Forms
// define units of measurement
[<Measure>] type m; // metres
[<Measure>] type s; // seconds
// a pendulum is represented as a record of physical quantities
type Pendulum =
{ length : float<m>
gravity : float<m/s^2>
velocity : float<m/s>
angle : float
}
// calculate the next state of a pendulum
let next pendulum deltaT : Pendulum =
let k = -pendulum.gravity / pendulum.length
let acceleration = k * Math.Sin pendulum.angle * 1.0<m>
let newVelocity = pendulum.velocity + acceleration * deltaT
let newAngle = pendulum.angle + newVelocity * deltaT / 1.0<m>
{ pendulum with velocity = newVelocity; angle = newAngle }
// paint a pendulum (using hard-coded screen coordinates)
let paint pendulum (gr: System.Drawing.Graphics) =
let homeX = 160
let homeY = 50
let length = 140.0
// draw plate
gr.DrawLine( new Pen(Brushes.Gray, width=2.0f), 0, homeY, 320, homeY )
// draw pivot
gr.FillEllipse( Brushes.Gray, homeX-5, homeY-5, 10, 10 )
gr.DrawEllipse( new Pen(Brushes.Black), homeX-5, homeY-5, 10, 10 )
// draw the pendulum itself
let x = homeX + int( length * Math.Sin pendulum.angle )
let y = homeY + int( length * Math.Cos pendulum.angle )
// draw rod
gr.DrawLine( new Pen(Brushes.Black, width=3.0f), homeX, homeY, x, y )
// draw bob
gr.FillEllipse( Brushes.Yellow, x-15, y-15, 30, 30 )
gr.DrawEllipse( new Pen(Brushes.Black), x-15, y-15, 30, 30 )
// defines an operator "-?" that calculates the time from t2 to t1
// where t2 is optional
let (-?) (t1: DateTime) (t2: DateTime option) : float<s> =
match t2 with
| None -> 0.0<s> // only one timepoint given -> difference is 0
| Some t -> (t1 - t).TotalSeconds * 1.0<s>
// our main window is double-buffered form that reacts to paint events
type PendulumForm() as self =
inherit Form(Width=325, Height=240, Text="Pendulum")
let mutable pendulum = { length = 1.0<m>;
gravity = 9.81<m/s^2>
velocity = 0.0<m/s>
angle = Math.PI / 2.0
}
let mutable lastPaintedAt = None
let updateFreq = 0.01<s>
do self.DoubleBuffered <- true
self.Paint.Add( fun args ->
let now = DateTime.Now
let deltaT = now -? lastPaintedAt |> min 0.01<s>
lastPaintedAt <- Some now
pendulum <- next pendulum deltaT
let gr = args.Graphics
gr.Clear( Color.LightGray )
paint pendulum gr
// initiate a new paint event after a while (non-blocking)
async { do! Async.Sleep( int( 1000.0 * updateFreq / 1.0<s> ) )
self.Invalidate()
}
|> Async.Start
)
[<STAThread>]
Application.Run( new PendulumForm( Visible=true ) ) |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Go | Go | package main
import (
"fmt"
"math/big"
"strings"
)
func factorial(n int64) *big.Int {
var z big.Int
return z.MulRange(1, n)
}
var one = big.NewInt(1)
var three = big.NewInt(3)
var six = big.NewInt(6)
var ten = big.NewInt(10)
var seventy = big.NewInt(70)
func almkvistGiullera(n int64, print bool) *big.Rat {
t1 := big.NewInt(32)
t1.Mul(factorial(6*n), t1)
t2 := big.NewInt(532*n*n + 126*n + 9)
t3 := new(big.Int)
t3.Exp(factorial(n), six, nil)
t3.Mul(t3, three)
ip := new(big.Int)
ip.Mul(t1, t2)
ip.Quo(ip, t3)
pw := 6*n + 3
t1.SetInt64(pw)
tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil))
if print {
fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33))
}
return tm
}
func main() {
fmt.Println("N Integer Portion Pow Nth Term (33 dp)")
fmt.Println(strings.Repeat("-", 89))
for n := int64(0); n < 10; n++ {
almkvistGiullera(n, true)
}
sum := new(big.Rat)
prev := new(big.Rat)
pow70 := new(big.Int).Exp(ten, seventy, nil)
prec := new(big.Rat).SetFrac(one, pow70)
n := int64(0)
for {
term := almkvistGiullera(n, false)
sum.Add(sum, term)
z := new(big.Rat).Sub(sum, prev)
z.Abs(z)
if z.Cmp(prec) < 0 {
break
}
prev.Set(sum)
n++
}
sum.Inv(sum)
pi := new(big.Float).SetPrec(256).SetRat(sum)
pi.Sqrt(pi)
fmt.Println("\nPi to 70 decimal places is:")
fmt.Println(pi.Text('f', 70))
} |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #ALGOL_68 | ALGOL 68 | BEGIN
INT examples=10, classes=5;
MODE SEMIPRIME = STRUCT ([examples]INT data, INT count);
[classes]SEMIPRIME semi primes;
PROC num facs = (INT n) INT :
COMMENT
Return number of not necessarily distinct prime factors of n.
Not very efficient for large n ...
COMMENT
BEGIN
INT tf := 2, residue := n, count := 1;
WHILE tf < residue DO
INT remainder = residue MOD tf;
( remainder = 0 | count +:= 1; residue %:= tf | tf +:= 1 )
OD;
count
END;
PROC update table = (REF []SEMIPRIME table, INT i) BOOL :
COMMENT
Add i to the appropriate row of the table, if any, unless that row
is already full. Return a BOOL which is TRUE when all of the table
is full.
COMMENT
BEGIN
INT k := num facs(i);
IF k <= classes
THEN
INT c = 1 + count OF table[k];
( c <= examples | (data OF table[k])[c] := i; count OF table[k] := c )
FI;
INT sum := 0;
FOR i TO classes DO sum +:= count OF table[i] OD;
sum < classes * examples
END;
FOR i TO classes DO count OF semi primes[i] := 0 OD;
FOR i FROM 2 WHILE update table (semi primes, i) DO SKIP OD;
FOR i TO classes
DO
printf (($"k = ", d, ":", n(examples)(xg(0))l$, i, data OF semi primes[i]))
OD
END |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Fortran | Fortran | SUBROUTINE BDIFF (B1,B2) !Difference B2 - B1, as bearings. All in degrees, not radians.
REAL*8 B1,B2 !Maximum precision, for large-angle folding.
COMPLEX*16 CIS,Z1,Z2,Z !Scratchpads.
CIS(T) = CMPLX(COSD(T),SIND(T)) !Convert an angle into a unit vector.
Z1 = CIS(90 - B1) !Bearings run clockwise from north (y) around to east (x).
Z2 = CIS(90 - B2) !Mathematics runs counterclockwise from x (east).
Z = Z1*CONJG(Z2) !(Z1x,Z1y)(Z2x,-Z2y) = (Z1x.Z2x + Z1y.Z2y, Z1y.Z2x - Z1x.Z2y)
T = ATAN2D(AIMAG(Z),REAL(Z)) !Madly, arctan(x,y) is ATAN(Y,X)!
WRITE (6,10) B1,Z1,B2,Z2,T !Two sets of numbers, and a result.
10 FORMAT (2(F14.4,"(",F9.6,",",F9.6,")"),F9.3) !Two lots, and a tail.
END SUBROUTINE BDIFF !Having functions in degrees saves some bother.
PROGRAM ORIENTED
REAL*8 B(24) !Just prepare a wad of values.
DATA B/20D0,45D0, -45D0,45D0, -85D0,90D0, -95D0,90D0, !As specified.
1 -45D0,125D0, -45D0,145D0, 29.4803D0,-88.6381D0,
2 -78.3251D0, -159.036D0,
3 -70099.74233810938D0, 29840.67437876723D0,
4 -165313.6666297357D0, 33693.9894517456D0,
5 1174.8380510598456D0, -154146.66490124757D0,
6 60175.77306795546D0, 42213.07192354373D0/
WRITE (6,1) ("B",I,"x","y", I = 1,2) !Or, one could just list them twice.
1 FORMAT (28X,"Bearing calculations, in degrees"//
* 2(A13,I1,"(",A9,",",A9,")"),A9) !Compare format 10, above.
DO I = 1,23,2 !Step through the pairs.
CALL BDIFF(B(I),B(I + 1))
END DO
END |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DerangedAnagrams {
public static void main(String[] args) throws IOException {
List<String> words = Files.readAllLines(new File("unixdict.txt").toPath());
printLongestDerangedAnagram(words);
}
private static void printLongestDerangedAnagram(List<String> words) {
words.sort(Comparator.comparingInt(String::length).reversed().thenComparing(String::toString));
Map<String, ArrayList<String>> map = new HashMap<>();
for (String word : words) {
char[] chars = word.toCharArray();
Arrays.sort(chars);
String key = String.valueOf(chars);
List<String> anagrams = map.computeIfAbsent(key, k -> new ArrayList<>());
for (String anagram : anagrams) {
if (isDeranged(word, anagram)) {
System.out.printf("%s %s%n", anagram, word);
return;
}
}
anagrams.add(word);
}
System.out.println("no result");
}
private static boolean isDeranged(String word1, String word2) {
for (int i = 0; i < word1.length(); i++) {
if (word1.charAt(i) == word2.charAt(i)) {
return false;
}
}
return true;
}
} |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Go | Go | package main
import "fmt"
func main() {
for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} {
f, ok := arFib(n)
if ok {
fmt.Printf("fib %d = %d\n", n, f)
} else {
fmt.Println("fib undefined for negative numbers")
}
}
}
func arFib(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n < 2:
return n, true
}
return yc(func(recurse fn) fn {
return func(left, term1, term2 int) int {
if left == 0 {
return term1+term2
}
return recurse(left-1, term1+term2, term1)
}
})(n-2, 1, 0), true
}
type fn func(int, int, int) int
type ff func(fn) fn
type fx func(fx) fn
func yc(f ff) fn {
return func(x fx) fn {
return x(x)
}(func(x fx) fn {
return f(func(a1, a2, a3 int) int {
return x(x)(a1, a2, a3)
})
})
} |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Ruby | Ruby | module Angles
BASES = {"d" => 360, "g" => 400, "m" => 6400, "r" => Math::PI*2 ,"h" => 24 }
def self.method_missing(meth, angle)
from, to = BASES.values_at(*meth.to_s.split("2"))
raise NoMethodError, meth if (from.nil? or to.nil?)
mod = (angle.to_f * to / from) % to
angle < 0 ? mod - to : mod
end
end
#Demo
names = Angles::BASES.keys
puts " " + "%12s "*names.size % names
test = [-2, -1, 0, 1, 2*Math::PI, 16, 360/(2*Math::PI), 360-1, 400-1, 6400-1, 1_000_000]
test.each do |n|
names.each do |first|
res = names.map{|last| Angles.send((first + "2" + last).to_sym, n)}
puts first + "%12g "*names.size % res
end
puts
end
|
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #EchoLisp | EchoLisp |
;; using (sum-divisors) from math.lib
(lib 'math)
(define (amicable N)
(define n 0)
(for/list ((m (in-range 2 N)))
(set! n (sum-divisors m))
#:continue (>= n (* 1.5 m)) ;; assume n/m < 1.5
#:continue (<= n m) ;; prevent perfect numbers
#:continue (!= (sum-divisors n) m)
(cons m n)))
(amicable 20000)
→ ((220 . 284) (1184 . 1210) (2620 . 2924) (5020 . 5564) (6232 . 6368) (10744 . 10856) (12285 . 14595) (17296 . 18416))
(amicable 1_000_000) ;; 42 pairs
→ (... (802725 . 863835) (879712 . 901424) (898216 . 980984) (947835 . 1125765) (998104 . 1043096))
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #LabVIEW | LabVIEW | txt$ = "Hello World! "
txtLength = len(txt$)
direction=1
NoMainWin
open "Rosetta Task: Animation" for graphics_nsb as #demo
#demo "Trapclose [quit]"
#demo "down"
#demo "Font Verdana 20 Bold"
#demo "When leftButtonUp [changedirection]"
timer 150 , [draw]
wait
[draw]
if direction then
txt$ = right$(txt$, 1);left$(txt$, txtLength - 1)
else
txt$ = right$(txt$, txtLength - 1);left$(txt$, 1)
end if
#demo "discard"
#demo "place 50 100"
#demo "\";txt$
wait
[changedirection]
direction = not(direction)
wait
[quit]
timer 0
close #demo
end |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Factor | Factor | USING: accessors alarms arrays calendar colors.constants kernel
locals math math.constants math.functions math.rectangles
math.vectors opengl sequences system ui ui.gadgets ui.render ;
IN: pendulum
CONSTANT: g 9.81
CONSTANT: l 20
CONSTANT: theta0 0.5
: current-time ( -- time ) nano-count -9 10^ * ;
: T0 ( -- T0 ) 2 pi l g / sqrt * * ;
: omega0 ( -- omega0 ) 2 pi * T0 / ;
: theta ( -- theta ) current-time omega0 * cos theta0 * ;
: relative-xy ( theta l -- xy )
swap [ sin * ] [ cos * ] 2bi 2array ;
: theta-to-xy ( origin theta l -- xy ) relative-xy v+ ;
TUPLE: pendulum-gadget < gadget alarm ;
: O ( gadget -- origin ) rect-bounds [ drop ] [ first 2 / ] bi* 0 2array ;
: window-l ( gadget -- l ) rect-bounds [ drop ] [ second ] bi* ;
: gadget-xy ( gadget -- xy ) [ O ] [ drop theta ] [ window-l ] tri theta-to-xy ;
M: pendulum-gadget draw-gadget*
COLOR: black gl-color
[ O ] [ gadget-xy ] bi gl-line ;
M:: pendulum-gadget graft* ( gadget -- )
[ gadget relayout-1 ]
20 milliseconds every gadget (>>alarm) ;
M: pendulum-gadget ungraft* alarm>> cancel-alarm ;
: <pendulum-gadget> ( -- gadget )
pendulum-gadget new
{ 500 500 } >>pref-dim ;
: pendulum-main ( -- )
[ <pendulum-gadget> "pendulum" open-window ] with-ui ;
MAIN: pendulum-main
|
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Haskell | Haskell | import Control.Monad
import Data.Number.CReal
import GHC.Integer
import Text.Printf
iterations = 52
main = do
printf "N. %44s %4s %s\n"
"Integral part of Nth term" "×10^" "=Actual value of Nth term"
forM_ [0..9] $ \n ->
printf "%d. %44d %4d %s\n" n
(almkvistGiulleraIntegral n)
(tenExponent n)
(showCReal 50 (almkvistGiullera n))
printf "\nPi after %d iterations:\n" iterations
putStrLn $ showCReal 70 $ almkvistGiulleraPi iterations
-- The integral part of the Nth term in the Almkvist-Giullera series
almkvistGiulleraIntegral n =
let polynomial = (532 `timesInteger` n `timesInteger` n) `plusInteger` (126 `timesInteger` n) `plusInteger` 9
numerator = 32 `timesInteger` (facInteger (6 `timesInteger` n)) `timesInteger` polynomial
denominator = 3 `timesInteger` (powInteger (facInteger n) 6)
in numerator `divInteger` denominator
-- The exponent for 10 in the Nth term of the series
tenExponent n = 3 `minusInteger` (6 `timesInteger` (1 `plusInteger` n))
-- The Nth term in the series (integral * 10^tenExponent)
almkvistGiullera n = fromInteger (almkvistGiulleraIntegral n) / fromInteger (powInteger 10 (abs (tenExponent n)))
-- The sum of the first N terms
almkvistGiulleraSum n = sum $ map almkvistGiullera [0 .. n]
-- The approximation of pi from the first N terms
almkvistGiulleraPi n = sqrt $ 1 / almkvistGiulleraSum n
-- Utility: factorial for arbitrary-precision integers
facInteger n = if n `leInteger` 1 then 1 else n `timesInteger` facInteger (n `minusInteger` 1)
-- Utility: exponentiation for arbitrary-precision integers
powInteger 1 _ = 1
powInteger _ 0 = 1
powInteger b 1 = b
powInteger b e = b `timesInteger` powInteger b (e `minusInteger` 1)
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #ALGOL-M | ALGOL-M | begin
integer function mod(a, b);
integer a, b;
mod := a-(a/b)*b;
integer function kprime(n, k);
integer n, k;
begin
integer p, f;
f := 0;
p := 2;
while f < k and p*p <= n do
begin
while mod(n,p) = 0 do
begin
n := n / p;
f := f + 1;
end;
p := p + 1;
end;
if n > 1 then f := f + 1;
if f = k then kprime := 1 else kprime := 0;
end;
integer i, c, k;
for k := 1 step 1 until 5 do
begin
write("k =");
writeon(k);
writeon(": ");
c := 0;
i := 2;
while c < 10 do
begin
if kprime(i, k) <> 0 then
begin
writeon(i);
c := c + 1;
end;
i := i + 1;
end;
end;
end |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #FreeBASIC | FreeBASIC | ' version 28-01-2019
' compile with: fbc -s console
#Include "string.bi"
Function frmt(num As Double) As String
Dim As String temp = Format(num, "#######.#############")
Dim As Integer i = Len(temp) -1
If temp[i] = Asc(".") Then temp[i] = 32
If InStr(temp, ".") = 0 Then
Return Right(Space(10) + temp, 9) + Space(13)
End If
temp = Space(10) + temp + Space(13)
Return Mid(temp, InStr(temp, ".") -8, 22)
End Function
' ------=< MAIN >=------
Dim As Double b1, b2, bb1, bb2, diff
Print
Print " b1 b2 difference"
Print " -----------------------------------------------------------"
Do
Read b1, b2
If b1 = 0 And b2 = 0 Then Exit Do
diff = b2 - b1
diff = diff - Int(diff / 360) * 360
If diff > 180 Then diff -= 360
Print frmt(b1); frmt(b2); frmt(diff)
Loop
Data 20,45, -45,45, -85,90
Data -95,90, -45,125, -45,145
Data 29.4803,-88.6381, -78.3251,-159.036
Data -70099.74233810938, 29840.67437876723
Data -165313.6666297357, 33693.9894517456
Data 1174.8380510598456, -154146.66490124757
Data 60175.77306795546, 42213.07192354373
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #JavaScript | JavaScript | #!/usr/bin/env js
function main() {
var wordList = read('unixdict.txt').split(/\s+/);
var anagrams = findAnagrams(wordList);
var derangedAnagrams = findDerangedAnagrams(anagrams);
var longestPair = findLongestDerangedPair(derangedAnagrams);
print(longestPair.join(' '));
}
function findLongestDerangedPair(danas) {
var longestLen = danas[0][0].length;
var longestPair = danas[0];
for (var i in danas) {
if (danas[i][0].length > longestLen) {
longestLen = danas[i][0].length;
longestPair = danas[i];
}
}
return longestPair;
}
function findDerangedAnagrams(anagrams) {
var deranged = [];
function isDeranged(w1, w2) {
for (var c = 0; c < w1.length; c++) {
if (w1[c] == w2[c]) {
return false;
}
}
return true;
}
function findDeranged(anas) {
for (var a = 0; a < anas.length; a++) {
for (var b = a + 1; b < anas.length; b++) {
if (isDeranged(anas[a], anas[b])) {
deranged.push([anas[a], anas[b]]);
}
}
}
}
for (var a in anagrams) {
var anas = anagrams[a];
findDeranged(anas);
}
return deranged;
}
function findAnagrams(wordList) {
var anagrams = {};
for (var wordNum in wordList) {
var word = wordList[wordNum];
var key = word.split('').sort().join('');
if (!(key in anagrams)) {
anagrams[key] = [];
}
anagrams[key].push(word);
}
for (var a in anagrams) {
if (anagrams[a].length < 2) {
delete(anagrams[a]);
}
}
return anagrams;
}
main(); |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Groovy | Groovy | def fib = {
assert it > -1
{i -> i < 2 ? i : {j -> owner.call(j)}(i-1) + {k -> owner.call(k)}(i-2)}(it)
} |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Rust | Rust | use std::{
marker::PhantomData,
f64::consts::PI,
};
pub trait AngleUnit: Copy {
const TURN: f64;
const NAME: &'static str;
}
macro_rules! unit {
($name:ident, $value:expr, $string:expr) => (
#[derive(Debug, Copy, Clone)]
struct $name;
impl AngleUnit for $name {
const TURN: f64 = $value;
const NAME: &'static str = $string;
}
);
}
unit!(Degrees, 360.0, "Degrees");
unit!(Radians, PI * 2.0, "Radians");
unit!(Gradians, 400.0, "Gradians");
unit!(Mils, 6400.0, "Mils");
#[derive(Copy, Clone, PartialEq, PartialOrd)]
struct Angle<T: AngleUnit>(f64, PhantomData<T>);
impl<T: AngleUnit> Angle<T> {
pub fn new(val: f64) -> Self {
Self(val, PhantomData)
}
pub fn normalize(self) -> Self {
Self(self.0 % T::TURN, PhantomData)
}
pub fn val(self) -> f64 {
self.0
}
pub fn convert<U: AngleUnit>(self) -> Angle<U> {
Angle::new(self.0 * U::TURN / T::TURN)
}
pub fn name(self) -> &'static str {
T::NAME
}
}
fn print_angles<T: AngleUnit>() {
let angles = [-2.0, -1.0, 0.0, 1.0, 2.0, 6.2831853, 16.0, 57.2957795, 359.0, 399.0, 6399.0, 1000000.0];
println!("{:<12} {:<12} {:<12} {:<12} {:<12} {:<12}", "Angle", "Unit", "Degrees", "Gradians", "Mils", "Radians");
for &angle in &angles {
let deg = Angle::<T>::new(angle).normalize();
println!("{:<12} {:<12} {:<12.4} {:<12.4} {:<12.4} {:<12.4}",
angle,
deg.name(),
deg.convert::<Degrees>().val(),
deg.convert::<Gradians>().val(),
deg.convert::<Mils>().val(),
deg.convert::<Radians>().val(),
);
}
println!();
}
fn main() {
print_angles::<Degrees>();
print_angles::<Gradians>();
print_angles::<Mils>();
print_angles::<Radians>();
} |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Swift | Swift | import Foundation
func normalize(_ f: Double, N: Double) -> Double {
var a = f
while a < -N { a += N }
while a >= N { a -= N }
return a
}
func normalizeToDeg(_ f: Double) -> Double {
return normalize(f, N: 360)
}
func normalizeToGrad(_ f: Double) -> Double {
return normalize(f, N: 400)
}
func normalizeToMil(_ f: Double) -> Double {
return normalize(f, N: 6400)
}
func normalizeToRad(_ f: Double) -> Double {
return normalize(f, N: 2 * .pi)
}
func d2g(_ f: Double) -> Double { f * 10 / 9 }
func d2m(_ f: Double) -> Double { f * 160 / 9 }
func d2r(_ f: Double) -> Double { f * .pi / 180 }
func g2d(_ f: Double) -> Double { f * 9 / 10 }
func g2m(_ f: Double) -> Double { f * 16 }
func g2r(_ f: Double) -> Double { f * .pi / 200 }
func m2d(_ f: Double) -> Double { f * 9 / 160 }
func m2g(_ f: Double) -> Double { f / 16 }
func m2r(_ f: Double) -> Double { f * .pi / 3200 }
func r2d(_ f: Double) -> Double { f * 180 / .pi }
func r2g(_ f: Double) -> Double { f * 200 / .pi }
func r2m(_ f: Double) -> Double { f * 3200 / .pi }
let angles = [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000]
let names = ["Degrees", "Gradians", "Mils", "Radians"]
let fmt = { String(format: "%.4f", $0) }
let normal = [normalizeToDeg, normalizeToGrad, normalizeToMil, normalizeToRad]
let convert = [
[{ $0 }, d2g, d2m, d2r],
[g2d, { $0 }, g2m, g2r],
[m2d, m2g, { $0 }, m2r],
[r2d, r2g, r2m, { $0 }]
]
let ans =
angles.map({ angle in
(0..<4).map({ ($0, normal[$0](angle)) }).map({
(fmt(angle),
fmt($0.1),
names[$0.0],
fmt(convert[$0.0][0]($0.1)),
fmt(convert[$0.0][1]($0.1)),
fmt(convert[$0.0][2]($0.1)),
fmt(convert[$0.0][3]($0.1))
)
})
})
print("angle", "normalized", "unit", "degrees", "grads", "mils", "radians")
for res in ans {
for unit in res {
print(unit)
}
print()
} |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Ela | Ela | open monad io number list
divisors n = filter ((0 ==) << (n `mod`)) [1..(n `div` 2)]
range = [1 .. 20000]
divs = zip range $ map (sum << divisors) range
pairs = [(n, m) \\ (n, nd) <- divs, (m, md) <- divs | n < m && nd == m && md == n]
do putLn pairs ::: IO |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Liberty_BASIC | Liberty BASIC | txt$ = "Hello World! "
txtLength = len(txt$)
direction=1
NoMainWin
open "Rosetta Task: Animation" for graphics_nsb as #demo
#demo "Trapclose [quit]"
#demo "down"
#demo "Font Verdana 20 Bold"
#demo "When leftButtonUp [changedirection]"
timer 150 , [draw]
wait
[draw]
if direction then
txt$ = right$(txt$, 1);left$(txt$, txtLength - 1)
else
txt$ = right$(txt$, txtLength - 1);left$(txt$, 1)
end if
#demo "discard"
#demo "place 50 100"
#demo "\";txt$
wait
[changedirection]
direction = not(direction)
wait
[quit]
timer 0
close #demo
end |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #FBSL | FBSL | #INCLUDE <Include\Windows.inc>
FBSLSETTEXT(ME, "Pendulum")
FBSL.SETTIMER(ME, 1000, 10)
RESIZE(ME, 0, 0, 300, 200)
CENTER(ME)
SHOW(ME)
BEGIN EVENTS
SELECT CASE CBMSG
CASE WM_TIMER
' Request redraw
InvalidateRect(ME, NULL, FALSE)
RETURN 0
CASE WM_PAINT
Swing()
CASE WM_CLOSE
FBSL.KILLTIMER(ME, 1000)
END SELECT
END EVENTS
SUB Swing()
TYPE RECT: %rcLeft, %rcTop, %rcRight, %rcBottom: END TYPE
STATIC rc AS RECT, !!acceleration, !!velocity, !!angle = M_PI_2, %pendulum = 100
GetClientRect(ME, @rc)
' Recalculate
DIM headX = rc.rcRight / 2, headY = rc.rcBottom / 4
DIM tailX = headX + SIN(angle) * pendulum
DIM tailY = headY + COS(angle) * pendulum
acceleration = -9.81 / pendulum * SIN(angle)
INCR(velocity, acceleration * 0.1)(angle, velocity * 0.1)
' Create backbuffer
CreateCompatibleDC(GetDC(ME))
SelectObject(CreateCompatibleDC, CreateCompatibleBitmap(GetDC, rc.rcRight, rc.rcBottom))
' Draw to backbuffer
FILLSTYLE(FILL_SOLID): FILLCOLOR(RGB(200, 200, 0))
LINE(CreateCompatibleDC, 0, 0, rc.rcRight, rc.rcBottom, GetSysColor(COLOR_BTNHILIGHT), TRUE, TRUE)
LINE(CreateCompatibleDC, 0, headY, rc.rcRight, headY, GetSysColor(COLOR_3DSHADOW))
DRAWWIDTH(3)
LINE(CreateCompatibleDC, headX, headY, tailX, tailY, RGB(200, 0, 0))
DRAWWIDTH(1)
CIRCLE(CreateCompatibleDC, headX, headY, 2, GetSysColor, 0, 360, 1, TRUE)
CIRCLE(CreateCompatibleDC, tailX, tailY, 10, GetSysColor, 0, 360, 1, FALSE)
' Blit to window
BitBlt(GetDC, 0, 0, rc.rcRight, rc.rcBottom, CreateCompatibleDC, 0, 0, SRCCOPY)
ReleaseDC(ME, GetDC)
' Delete backbuffer
DeleteObject(SelectObject(CreateCompatibleDC, SelectObject))
DeleteDC(CreateCompatibleDC)
END SUB |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #J | J |
numerator =: monad define "0
(3 * (! x: y)^6) %~ 32 * (!6x*y) * (y*(126 + 532*y)) + 9x
)
term =: numerator % 10x ^ 3 + 6&*
echo 'The first 10 numerators are:'
echo ,. numerator i.10
echo ''
echo 'The sum of the first 10 terms (pi^-2) is ', 0j15 ": +/ term i.10
heron =: [: -: ] + %
sqrt =: dyad define NB. usage: x0 tolerance sqrt x
NB. e.g.: (1, %10^100x) sqrt 2 -> √2 to 100 decimals as a ratio p/q
x0 =. }: x
eps =. }. x
x1 =. y heron x0
while. (| x1 - x0) > eps do.
x2 =. y heron x1
x0 =. x1
x1 =. x2
end.
x1
)
pi70 =. (355r113, %10^70x) sqrt % +/ term i.53
echo ''
echo 'pi to 70 decimals: ', 0j70 ": pi70
exit ''
|
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #JavaScript | JavaScript | import esMain from 'es-main';
import { BigFloat, set_precision as SetPrecision } from 'bigfloat-esnext';
const Iterations = 52;
export const demo = function() {
SetPrecision(-75);
console.log("N." + "Integral part of Nth term".padStart(45) + " ×10^ =Actual value of Nth term");
for (let i=0; i<10; i++) {
let line = `${i}. `;
line += `${integral(i)} `.padStart(45);
line += `${tenExponent(i)} `.padStart(5);
line += nthTerm(i);
console.log(line);
}
let pi = approximatePi(Iterations);
SetPrecision(-70);
pi = pi.dividedBy(100000).times(100000);
console.log(`\nPi after ${Iterations} iterations: ${pi}`)
}
export const bigFactorial = n => n <= 1n ? 1n : n * bigFactorial(n-1n);
// the nth integer term
export const integral = function(i) {
let n = BigInt(i);
const polynomial = 532n * n * n + 126n * n + 9n;
const numerator = 32n * bigFactorial(6n * n) * polynomial;
const denominator = 3n * bigFactorial(n) ** 6n;
return numerator / denominator;
}
// the exponent for 10 in the nth term of the series
export const tenExponent = n => 3n - 6n * (BigInt(n) + 1n);
// the nth term of the series
export const nthTerm = n =>
new BigFloat(integral(n)).dividedBy(new BigFloat(10n ** -tenExponent(n)))
// the sum of the first n terms
export const sumThrough = function(n) {
let sum = new BigFloat(0);
for (let i=0; i<=n; ++i) {
sum = sum.plus(nthTerm(i));
}
return sum;
}
// the approximation to pi after n terms
export const approximatePi = n =>
new BigFloat(1).dividedBy(sumThrough(n)).sqrt();
if (esMain(import.meta))
demo();
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #ALGOL_W | ALGOL W | begin
logical procedure kPrime( integer value nv, k ) ;
begin
integer p, f, n;
n := nv;
f := 0;
while f <= k and not odd( n ) do begin
n := n div 2;
f := f + 1
end while_not_odd_n ;
p := 3;
while f <= k and p * p <= n do begin
while n rem p = 0 do begin
n := n div p;
f := f + 1
end while_n_rem_p_eq_0 ;
p := p + 2
end while_f_le_k_and_p_is_a_factor ;
if n > 1 then f := f + 1;
f = k
end kPrime ;
begin
for k := 1 until 5 do begin
integer c, i;
write( i_w := 1, s_w := 0, "k = ", k , ": " );
c := 0;
i := 2;
while c < 10 do begin
if kPrime( i, k ) then begin
writeon( i_w := 3, s_w := 0, " ", i );
c := c + 1
end if_kPrime_i_k ;
i := i + 1
end while_c_lt_10
end for_k
end
end. |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #APL | APL | f←{↑r⊣⍵∘{r,∘⊂←⍺↑∪{⍵[⍋⍵]},f∘.×⍵}⍣(⍺-1)⊃r←⊂f←pco¨⍳⍵} |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Go | Go | package main
import "fmt"
type bearing float64
var testCases = []struct{ b1, b2 bearing }{
{20, 45},
{-45, 45},
{-85, 90},
{-95, 90},
{-45, 125},
{-45, 145},
{29.4803, -88.6381},
{-78.3251, -159.036},
}
func main() {
for _, tc := range testCases {
fmt.Println(tc.b2.Sub(tc.b1))
}
}
func (b2 bearing) Sub(b1 bearing) bearing {
switch d := b2 - b1; {
case d < -180:
return d + 360
case d > 180:
return d - 360
default:
return d
}
} |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq | # Input: an array of strings
# Output: a stream of arrays
def anagrams:
reduce .[] as $word (
{table: {}, max: 0}; # state
($word | explode | sort | implode) as $hash
| .table[$hash] += [ $word ]
| .max = ([ .max, ( .table[$hash] | length) ] | max ) )
| .table | .[] | select(length>1);
# Check whether the input and y are deranged,
# on the assumption that they are anagrams:
def deranged(y):
explode as $x # explode is fast
| (y | explode) as $y
| all( range(0;length); $x[.] != $y[.] );
# The task: loop through the anagrams,
# retaining only the best set of deranged anagrams so far.
split("\n") | select(length>0) # read all the words as an array
| reduce anagrams as $words ([]; # loop through all the anagrams
reduce $words[] as $v (.;
reduce ($words - [$v])[] as $w (.; # $v and $w are distinct members of $words
if $v|deranged($w)
then if length == 0 then [$v,$w]
elif ($v|length) == (.[0]|length) then . + [$v,$w]
elif ($v|length) > (.[0]|length) then [$v,$w]
else .
end
else .
end) ) )
| unique |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Haskell | Haskell | fib :: Integer -> Maybe Integer
fib n
| n < 0 = Nothing
| otherwise = Just $ real n
where real 0 = 1
real 1 = 1
real n = real (n-1) + real (n-2) |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Vlang | Vlang | import math
import strconv
fn d2d(d f64) f64 { return math.mod(d, 360) }
fn g2g(g f64) f64 { return math.mod(g, 400) }
fn m2m(m f64) f64 { return math.mod(m, 6400) }
fn r2r(r f64) f64 { return math.mod(r, 2*math.pi) }
fn d2g(d f64) f64 { return d2d(d) * 400 / 360 }
fn d2m(d f64) f64 { return d2d(d) * 6400 / 360 }
fn d2r(d f64) f64 { return d2d(d) * math.pi / 180 }
fn g2d(g f64) f64 { return g2g(g) * 360 / 400 }
fn g2m(g f64) f64 { return g2g(g) * 6400 / 400 }
fn g2r(g f64) f64 { return g2g(g) * math.pi / 200 }
fn m2d(m f64) f64 { return m2m(m) * 360 / 6400 }
fn m2g(m f64) f64 { return m2m(m) * 400 / 6400 }
fn m2r(m f64) f64 { return m2m(m) * math.pi / 3200 }
fn r2d(r f64) f64 { return r2r(r) * 180 / math.pi }
fn r2g(r f64) f64 { return r2r(r) * 200 / math.pi }
fn r2m(r f64) f64 { return r2r(r) * 3200 / math.pi }
fn s(f f64) string {
wf := strconv.format_fl(f, strconv.BF_param{
len0: 15
len1: 7
positive: f>=0
}).split('.')
if wf[1] == '0000000' {
return "${wf[0]:7} "
}
mut le := wf[1].len
if le > 7 {
le = 7
}
return "${wf[0]:7}.${wf[1][..le]:-7}"
}
fn main() {
angles := [-2.0, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
println(" degrees normalized degs gradians mils radians")
for a in angles {
println('${s(a)} ${s(d2d(a))} ${s(d2g(a))} ${s(d2m(a))} ${s(d2r(a))}')
}
println("\n gradians normalized grds degrees mils radians")
for a in angles {
println('${s(a)} ${s(g2g(a))} ${s(g2d(a))} ${s(g2m(a))} ${s(g2r(a))}')
}
println("\n mils normalized mils degrees gradians radians")
for a in angles {
println('${s(a)} ${s(m2m(a))} ${s(m2d(a))} ${s(m2g(a))} ${s(m2r(a))}')
}
println("\n radians normalized rads degrees gradians mils ")
for a in angles {
println('${s(a)} ${s(r2r(a))} ${s(r2d(a))} ${s(r2g(a))} ${s(r2m(a))}')
}
} |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #Wren | Wren | import "/fmt" for Fmt
var d2d = Fn.new { |d| d % 360 }
var g2g = Fn.new { |g| g % 400 }
var m2m = Fn.new { |m| m % 6400 }
var r2r = Fn.new { |r| r % (2*Num.pi) }
var d2g = Fn.new { |d| d2d.call(d) * 400 / 360 }
var d2m = Fn.new { |d| d2d.call(d) * 6400 / 360 }
var d2r = Fn.new { |d| d2d.call(d) * Num.pi / 180 }
var g2d = Fn.new { |g| g2g.call(g) * 360 / 400 }
var g2m = Fn.new { |g| g2g.call(g) * 6400 / 400 }
var g2r = Fn.new { |g| g2g.call(g) * Num.pi / 200 }
var m2d = Fn.new { |m| m2m.call(m) * 360 / 6400 }
var m2g = Fn.new { |m| m2m.call(m) * 400 / 6400 }
var m2r = Fn.new { |m| m2m.call(m) * Num.pi / 3200 }
var r2d = Fn.new { |r| r2r.call(r) * 180 / Num.pi }
var r2g = Fn.new { |r| r2r.call(r) * 200 / Num.pi }
var r2m = Fn.new { |r| r2r.call(r) * 3200 / Num.pi }
var f1 = "$15m $15m $15m $15m $15m"
var f2 = "$15.7g $15.7g $15.7g $15.7g $15.7g"
var angles = [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
Fmt.print(f1, "degrees", "normalized degs", "gradians", "mils", "radians")
for (a in angles) {
Fmt.print(f2, a, d2d.call(a), d2g.call(a), d2m.call(a), d2r.call(a))
}
f1 = "\n" + f1
Fmt.print(f1, "gradians", "normalized grds", "degrees", "mils", "radians")
for (a in angles) {
Fmt.print(f2, a, g2g.call(a), g2d.call(a), g2m.call(a), g2r.call(a))
}
Fmt.print(f1, "mils", "normalized mils", "degrees", "gradians", "radians")
for (a in angles) {
Fmt.print(f2, a, m2m.call(a), m2d.call(a), m2g.call(a), m2r.call(a))
}
Fmt.print(f1, "radians", "normalized rads", "degrees", "gradians", "mils")
for (a in angles) {
Fmt.print(f2, a, r2r.call(a), r2d.call(a), r2g.call(a), r2m.call(a))
} |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Elena | Elena | import extensions;
import system'routines;
const int N = 20000;
extension op
{
ProperDivisors
= Range.new(1,self / 2).filterBy:(n => self.mod:n == 0);
get AmicablePairs()
{
var divsums := Range
.new(0, self + 1)
.selectBy:(i => i.ProperDivisors.summarize(Integer.new()))
.toArray();
^ 1.repeatTill(divsums.Length)
.filterBy:(i)
{
var ii := i;
var sum := divsums[i];
^ (i < sum) && (sum < divsums.Length) && (divsums[sum] == i)
}
.selectBy:(i => new { Item1 = i; Item2 = divsums[i]; })
}
}
public program()
{
N.AmicablePairs.forEach:(pair)
{
console.printLine(pair.Item1, " ", pair.Item2)
}
} |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Logo | Logo | to rotate.left :thing
output lput first :thing butfirst :thing
end
to rotate.right :thing
output fput last :thing butlast :thing
end
make "text "|Hello World! |
make "right? "true
to step.animation
label :text ; graphical
; type char 13 type :text ; textual
wait 6 ; 1/10 second
if button <> 0 [make "right? not :right?]
make "text ifelse :right? [rotate.right :text] [rotate.left :text]
end
hideturtle
until [key?] [step.animation] |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Lua | Lua | function love.load()
text = "Hello World! "
length = string.len(text)
update_time = 0.3
timer = 0
right_direction = true
local width, height = love.graphics.getDimensions( )
local size = 100
local font = love.graphics.setNewFont( size )
local twidth = font:getWidth( text )
local theight = font:getHeight( )
x = width/2 - twidth/2
y = height/2-theight/2
end
function love.update(dt)
timer = timer + dt
if timer > update_time then
timer = timer - update_time
if right_direction then
text = string.sub(text, 2, length) .. string.sub(text, 1, 1)
else
text = string.sub(text, length, length) .. string.sub(text, 1, length-1)
end
end
end
function love.draw()
love.graphics.print (text, x, y)
end
function love.keypressed(key, scancode, isrepeat)
if false then
elseif key == "escape" then
love.event.quit()
end
end
function love.mousepressed( x, y, button, istouch, presses )
right_direction = not right_direction
end |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Fortran | Fortran |
!Implemented by Anant Dixit (October, 2014)
program animated_pendulum
implicit none
double precision, parameter :: pi = 4.0D0*atan(1.0D0), l = 1.0D-1, dt = 1.0D-2, g = 9.8D0
integer :: io
double precision :: s_ang, c_ang, p_ang, n_ang
write(*,*) 'Enter starting angle (in degrees):'
do
read(*,*,iostat=io) s_ang
if(io.ne.0 .or. s_ang.lt.-90.0D0 .or. s_ang.gt.90.0D0) then
write(*,*) 'Please enter an angle between 90 and -90 degrees:'
else
exit
end if
end do
call execute_command_line('cls')
c_ang = s_ang*pi/180.0D0
p_ang = c_ang
call display(c_ang)
do
call next_time_step(c_ang,p_ang,g,l,dt,n_ang)
if(abs(c_ang-p_ang).ge.0.05D0) then
call execute_command_line('cls')
call display(c_ang)
end if
end do
end program
subroutine next_time_step(c_ang,p_ang,g,l,dt,n_ang)
double precision :: c_ang, p_ang, g, l, dt, n_ang
n_ang = (-g*sin(c_ang)/l)*2.0D0*dt**2 + 2.0D0*c_ang - p_ang
p_ang = c_ang
c_ang = n_ang
end subroutine
subroutine display(c_ang)
double precision :: c_ang
character (len=*), parameter :: cfmt = '(A1)'
double precision :: rx, ry
integer :: x, y, i, j
rx = 45.0D0*sin(c_ang)
ry = 22.5D0*cos(c_ang)
x = int(rx)+51
y = int(ry)+2
do i = 1,32
do j = 1,100
if(i.eq.y .and. j.eq.x) then
write(*,cfmt,advance='no') 'O'
else if(i.eq.y .and. (j.eq.(x-1).or.j.eq.(x+1))) then
write(*,cfmt,advance='no') 'G'
else if(j.eq.x .and. (i.eq.(y-1).or.i.eq.(y+1))) then
write(*,cfmt,advance='no') 'G'
else if(i.eq.y .and. (j.eq.(x-2).or.j.eq.(x+2))) then
write(*,cfmt,advance='no') '#'
else if(j.eq.x .and. (i.eq.(y-2).or.i.eq.(y+2))) then
write(*,cfmt,advance='no') 'G'
else if((i.eq.(y+1).and.j.eq.(x+1)) .or. (i.eq.(y-1).and.j.eq.(x-1))) then
write(*,cfmt,advance='no') '#'
else if((i.eq.(y+1).and.j.eq.(x-1)) .or. (i.eq.(y-1).and.j.eq.(x+1))) then
write(*,cfmt,advance='no') '#'
else if(j.eq.50) then
write(*,cfmt,advance='no') '|'
else if(i.eq.2) then
write(*,cfmt,advance='no') '-'
else
write(*,cfmt,advance='no') ' '
end if
end do
write(*,*)
end do
end subroutine
|
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #jq | jq | # A reminder to include the "rational" module:
# include "rational";
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
def factorial:
if . < 2 then 1
else reduce range(2;.+1) as $i (1; .*$i)
end; |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Julia | Julia | using Formatting
setprecision(BigFloat, 300)
function integerterm(n)
p = BigInt(532) * n * n + BigInt(126) * n + 9
return (p * BigInt(2)^5 * factorial(BigInt(6) * n)) ÷ (3 * factorial(BigInt(n))^6)
end
exponentterm(n) = -(6n + 3)
nthterm(n) = integerterm(n) * big"10.0"^exponentterm(n)
println(" N Integer Term Power of 10 Nth Term")
println("-"^90)
for n in 0:9
println(lpad(n, 3), lpad(integerterm(n), 48), lpad(exponentterm(n), 4),
lpad(format("{1:22.19e}", nthterm(n)), 35))
end
function AlmkvistGuillera(floatprecision)
summed = nthterm(0)
for n in 1:10000000
next = summed + nthterm(n)
if abs(next - summed) < big"10.0"^(-floatprecision)
return next
end
summed = next
end
end
println("\nπ to 70 digits is ", format(big"1.0" / sqrt(AlmkvistGuillera(70)), precision=70))
println("Computer π is ", format(π + big"0.0", precision=70))
|
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[numerator, denominator]
numerator[n_] := (2^5) ((6 n)!) (532 n^2 + 126 n + 9)/(3 (n!)^6)
denominator[n_] := 10^(6 n + 3)
numerator /@ Range[0, 9]
val = 1/Sqrt[Total[numerator[#]/denominator[#] & /@ Range[0, 100]]];
N[val, 70] |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program kprime.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ MAXI, 10
.equ MAXIK, 5
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessDeb: .ascii "k="
sMessValeurDeb: .fill 11, 1, ' ' @ size => 11
sMessResult: .ascii " "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r3,#1 @ k
1: @ start loop k
mov r0,r3
ldr r1,iAdrsMessValeurDeb
bl conversion10 @ call conversion decimal
ldr r0,iAdrsMessValeurDeb
mov r1,#':'
strb r1,[r0,#2] @ write : after k value
mov r1,#0
strb r1,[r0,#3] @ final zéro
ldr r0,iAdrsMessDeb
bl affichageMess @ display message
mov r4,#2 @ n
mov r5,#0 @ result counter
2: @ start loop n
mov r0,r4
mov r1,r3
bl kprime @ is kprine ?
cmp r0,#0
beq 3f @ no
mov r0,r4
ldr r1,iAdrsMessValeur
bl conversion10 @ call conversion decimal
ldr r0,iAdrsMessValeur
mov r1,#0
strb r1,[r0,#4] @ final zéro
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r5,#1 @ increment counter
3:
add r4,#1 @ increment n
cmp r5,#MAXI @ maxi ?
blt 2b @ no -> loop
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display carriage return
add r3,#1 @ increment k
cmp r3,#MAXIK @ maxi ?
ble 1b @ no -> loop
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrsMessValeurDeb: .int sMessValeurDeb
iAdrsMessDeb: .int sMessDeb
/******************************************************************/
/* compute kprime (n,k) */
/******************************************************************/
/* r0 contains n */
/* r1 contains k */
kprime:
push {r1-r7,lr} @ save registers
mov r5,r0 @ save n
mov r7,r1 @ save k
mov r4,#0 @ counter product
mov r1,#2 @ divisor
1: @ start loop
cmp r4,r7 @ counter >= k
bge 4f @ yes -> end
mul r6,r1,r1 @ compute product
cmp r6,r5 @ > n
bgt 4f @ yes -> end
2: @ start loop division
mov r0,r5 @ dividende
bl division @ by r1
cmp r3,#0 @ remainder = 0 ?
bne 3f @ no
mov r5,r2 @ yes -> n = n / r1
add r4,#1 @ increment counter
b 2b @ and loop
3:
add r1,#1 @ increment divisor
b 1b @ and loop
4: @ end compute
cmp r5,#1 @ n > 1
addgt r4,#1 @ yes increment counter
cmp r4,r7 @ counter = k ?
movne r0,#0 @ no -> no kprime
moveq r0,#1 @ yes -> kprime
100:
pop {r1-r7,lr} @ restaur registers
bx lr @return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
/***************************************************/
/* integer division unsigned */
/***************************************************/
division:
/* r0 contains dividend */
/* r1 contains divisor */
/* r2 returns quotient */
/* r3 returns remainder */
push {r4, lr}
mov r2, #0 @ init quotient
mov r3, #0 @ init remainder
mov r4, #32 @ init counter bits
b 2f
1: @ loop
movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C
cmp r3, r1 @ compute r3 - r1 and update cpsr
subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1
adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C
2:
subs r4, r4, #1 @ r4 <- r4 - 1
bpl 1b @ if r4 >= 0 (N=0) then loop
pop {r4, lr}
bx lr
|
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | DefaultDict[String, Array[String]] anagram
L(word) File(‘unixdict.txt’).read().split("\n")
anagram[sorted(word).join(‘’)].append(word)
V count = max(anagram.values().map(ana -> ana.len))
L(ana) anagram.values()
I ana.len == count
print(ana) |
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Groovy | Groovy | def angleDifferenceA(double b1, double b2) {
r = (b2 - b1) % 360.0
(r > 180.0 ? r - 360.0
: r <= -180.0 ? r + 360.0
: r)
} |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia | using Base.isless
# Let's define the less than operator for any two vectors that have the same type:
# This does lexicographic comparison, we use it on vectors of chars in this task.
function Base.isless(t1, t2)
for (a, b) in zip(t1, t2) # zip only to the shorter length
if !isequal(a, b)
return isless(a, b)
end
end
return length(t1) < length(t2)
end
# The sort function of Julia doesn't work on strings, so we write one:
# This returns a sorted vector of the chars of the given string
sortchars(s::AbstractString) = sort(collect(Char, s))
# Custom comparator function for sorting the loaded wordlist
sortanagr(s1::AbstractString, s2::AbstractString) =
if length(s1) != length(s2) length(s1) < length(s2) else sortchars(s1) < sortchars(s2) end
# Tests if two strings are deranged anagrams, returns a bool:
# in our case s2 is never longer than s1
function deranged(s1::AbstractString, s2::AbstractString)
# Tests for derangement first
for (a, b) in zip(s1, s2)
if a == b return false end
end
# s1 and s2 are deranged, but are they anagrams at all?
return sortchars(s1) == sortchars(s2)
end
# Task starts here, we load the wordlist line by line, strip eol char, and sort the wordlist
# in a way that ensures that longer words come first and anagrams go next to each other
words = sort(open(readlines, "./data/unixdict.txt"), rev = true, lt = sortanagr)
# Now we just look for deranged anagrams in the neighbouring words of the sorted wordlist
for i in 1:length(words)-1
if deranged(words[i], words[i+1])
# The first match is guaranteed to be the longest due to the custom sorting
println("The longest deranged anagrams are $(words[i]) and $(words[i+1])")
break
end
end |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every write("fib(",a := numeric(!A),")=",fib(a))
end
procedure fib(n)
local source, i
static cache
initial {
cache := table()
cache[0] := 0
cache[1] := 1
}
if type(n) == "integer" & n >= 0 then
return n @ makeProc {{
i := @(source := &source) # 1
/cache[i] := ((i-1)@makeProc(^¤t)+(i-2)@makeProc(^¤t)) # 2
cache[i] @ source # 3
}}
end
procedure makeProc(A)
A := if type(A) == "list" then A[1]
return (@A, A) # prime and return
end |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #XPL0 | XPL0 | def Pi = 3.14159265358979323846, N=12, Tab=9;
func real D2D; real D; return Mod(D, 360.);
func real G2G; real G; return Mod(G, 400.);
func real M2M; real M; return Mod(M, 6400.);
func real R2R; real R; return Mod(R, 2.*Pi);
func real D2G; real D; return 400. * D2D(D) / 360.;
func real D2M; real D; return 6400.* D2D(D) / 360.;
func real D2R; real D; return 2.*Pi* D2D(D) / 360.;
func real G2D; real G; return 360. * G2G(G) / 400.;
func real G2M; real G; return 6400.* G2G(G) / 400.;
func real G2R; real G; return 2.*Pi* G2G(G) / 400.;
func real M2D; real M; return 360. * M2M(M) / 6400.;
func real M2G; real M; return 400. * M2M(M) / 6400.;
func real M2R; real M; return 2.*Pi* M2M(M) / 6400.;
func real R2D; real R; return 360. * R2R(R) / (2.*Pi);
func real R2G; real R; return 400. * R2R(R) / (2.*Pi);
func real R2M; real R; return 6400.* R2R(R) / (2.*Pi);
real Angle; int I;
[Angle:=
[-2., -1., 0., 1., 2., 6.2831853, 16., 57.2957795, 359., 399., 6399., 1000000.];
Format(7, 7);
Text(0, "
Degrees Normalized Gradians Mils Radians
");
for I:= 0 to N-1 do
[RlOut(0, Angle(I)); ChOut(0, Tab);
RlOut(0, D2D(Angle(I))); ChOut(0, Tab);
RlOut(0, D2G(Angle(I))); ChOut(0, Tab);
RlOut(0, D2M(Angle(I))); ChOut(0, Tab);
RlOut(0, D2R(Angle(I))); CrLf(0);
];
Text(0, "
Gradians Normalized Degrees Mils Radians
");
for I:= 0 to N-1 do
[RlOut(0, Angle(I)); ChOut(0, Tab);
RlOut(0, G2G(Angle(I))); ChOut(0, Tab);
RlOut(0, G2D(Angle(I))); ChOut(0, Tab);
RlOut(0, G2M(Angle(I))); ChOut(0, Tab);
RlOut(0, G2R(Angle(I))); CrLf(0);
];
Text(0, "
Mils Normalized Degrees Gradians Radians
");
for I:= 0 to N-1 do
[RlOut(0, Angle(I)); ChOut(0, Tab);
RlOut(0, M2M(Angle(I))); ChOut(0, Tab);
RlOut(0, M2D(Angle(I))); ChOut(0, Tab);
RlOut(0, M2G(Angle(I))); ChOut(0, Tab);
RlOut(0, M2R(Angle(I))); CrLf(0);
];
Text(0, "
Radians Normalized Degrees Gradians Mils
");
for I:= 0 to N-1 do
[RlOut(0, Angle(I)); ChOut(0, Tab);
RlOut(0, R2R(Angle(I))); ChOut(0, Tab);
RlOut(0, R2D(Angle(I))); ChOut(0, Tab);
RlOut(0, R2G(Angle(I))); ChOut(0, Tab);
RlOut(0, R2M(Angle(I))); CrLf(0);
];
] |
http://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion | Angles (geometric), normalization and conversion | This task is about the normalization and/or conversion of (geometric) angles using
some common scales.
The angular scales that will be used in this task are:
degree
gradian
mil
radian
Definitions
The angular scales used or referenced here:
turn is a full turn or 360 degrees, also shown as 360º
degree is 1/360 of a turn
gradian is 1/400 of a turn
mil is 1/6400 of a turn
radian is 1/2
π
{\displaystyle \pi }
of a turn (or 0.5/
π
{\displaystyle \pi }
of a turn)
Or, to put it another way, for a full circle:
there are 360 degrees
there are 400 gradians
there are 6,400 mils
there are 2
π
{\displaystyle \pi }
radians (roughly equal to 6.283+)
A mil is approximately equal to a milliradian (which is 1/1000 of a radian).
There is another definition of a mil which
is 1/1000 of a radian ─── this
definition won't be used in this Rosetta Code task.
Turns are sometimes known or shown as:
turn(s)
360 degrees
unit circle
a (full) circle
Degrees are sometimes known or shown as:
degree(s)
deg
º (a symbol)
° (another symbol)
Gradians are sometimes known or shown as:
gradian(s)
grad(s)
grade(s)
gon(s)
metric degree(s)
(Note that centigrade was used for 1/100th of a grade, see the note below.)
Mils are sometimes known or shown as:
mil(s)
NATO mil(s)
Radians are sometimes known or shown as:
radian(s)
rad(s)
Notes
In continental Europe, the French term centigrade was used
for 1/100 of a grad (grade); this was
one reason for the adoption of the term Celsius to
replace centigrade as the name of a temperature scale.
Gradians were commonly used in civil engineering.
Mils were normally used for artillery (elevations of the gun barrel for ranging).
Positive and negative angles
Although the definition of the measurement of an angle doesn't support the
concept of a negative angle, it's frequently useful to impose a convention that
allows positive and negative angular values to represent orientations and/or rotations
in opposite directions relative to some reference. It is this reason that
negative angles will keep their sign and not be normalized to positive angles.
Normalization
Normalization (for this Rosetta Code task) will keep the same
sign, but it will reduce the magnitude to less than a full circle; in
other words, less than 360º.
Normalization shouldn't change -45º to 315º,
An angle of 0º, +0º, 0.000000, or -0º should be
shown as 0º.
Task
write a function (or equivalent) to do the normalization for each scale
Suggested names:
d2d, g2g, m2m, and r2r
write a function (or equivalent) to convert one scale to another
Suggested names for comparison of different computer language function names:
d2g, d2m, and d2r for degrees
g2d, g2m, and g2r for gradians
m2d, m2g, and m2r for mils
r2d, r2g, and r2m for radians
normalize all angles used (except for the "original" or "base" angle)
show the angles in every scale and convert them to all other scales
show all output here on this page
For the (above) conversions, use these dozen numbers (in the order shown):
-2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000
| #zkl | zkl | var [const]
tau=(0.0).pi*2,
units=Dictionary( // code:(name, units in circle)
"d", T("degrees", 360.0), "g",T("gradians",400.0),
"m", T("mills", 6400.0), "r",T("radians", tau) ),
cvtNm="%s-->%s".fmt,
cvt= // "d-->r":fcn(angle){}, "r-->d":fcn(angle){} ...
Walker.cproduct(units.keys,units.keys).pump(Dictionary(),fcn([(a,b)]){
return(cvtNm(a,b), // "d-->r"
'wrap(angle){ angle=angle.toFloat();
u:=units[a][1];
(angle%u)*units[b][1] / u
})
})
; |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Elixir | Elixir | defmodule Proper do
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
defp divisors(k,_n,q) when k>q, do: []
defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q)
defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)]
defp divisors(k,n,q) , do: [k,div(n,k) | divisors(k+1,n,q)]
end
map = Map.new(1..20000, fn n -> {n, Proper.divisors(n) |> Enum.sum} end)
Enum.filter(map, fn {n,sum} -> map[sum] == n and n < sum end)
|> Enum.sort
|> Enum.each(fn {i,j} -> IO.puts "#{i} and #{j}" end) |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #M2000_Interpreter | M2000 Interpreter |
Module UseBlink {
Def boolean direction=True
rotating$ =lambda$ a$="Hello World! " (direction as boolean)->{
=a$
a$=if$(direction->right$(a$,1)+mid$(a$,1, len(a$)-1), mid$(a$,2)+left$(a$,1))
}
Declare MyForm Form
Declare MyButton Button Form MyForm
With MyButton, "Caption" as MyButtonCaption$, "Blink", 200
Method MyForm,"Move", 1000,1000,6000,4000
Method MyButton,"Move", 1000,1700,4000,600
Function MyButton.Blink {
Rem Stack : Refresh ' to refresh the console window
MyButtonCaption$=rotating$(direction)
}
Function MyButton.Click {
direction~
}
Function MyForm.Click {
direction~
}
With MyForm, "Title", "Animation"
Method MyForm, "Show", 1
Threads Erase
}
UseBlink
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Maple | Maple |
ScrollText(GP("Text",value),"Forward",65);
|
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Groovy | Groovy |
import java.awt.*;
import javax.swing.*;
class Pendulum extends JPanel implements Runnable {
private angle = Math.PI / 2;
private length;
Pendulum(length) {
this.length = length;
setDoubleBuffered(true);
}
@Override
void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
def ballX = anchorX + (Math.sin(angle) * length) as int;
def ballY = anchorY + (Math.cos(angle) * length) as int;
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
}
void run() {
def angleAccel, angleVelocity = 0, dt = 0.1;
while (true) {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try { Thread.sleep(15); } catch (InterruptedException ex) {}
}
}
@Override
Dimension getPreferredSize() {
return new Dimension(2 * length + 50, (length / 2 * 3) as int);
}
static void main(String[] args) {
def f = new JFrame("Pendulum");
def p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
}
|
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Nim | Nim | import strformat, strutils
import decimal
proc fact(n: int): DecimalType =
result = newDecimal(1)
if n < 2: return
for i in 2..n:
result *= i
proc almkvistGiullera(n: int): DecimalType =
## Return the integer portion of the nth term of Almkvist-Giullera sequence.
let t1 = fact(6 * n) * 32
let t2 = 532 * n * n + 126 * n + 9
let t3 = fact(n) ^ 6 * 3
result = t1 * t2 / t3
let One = newDecimal(1)
setPrec(78)
echo "N Integer portion"
echo repeat('-', 47)
for n in 0..9:
echo &"{n} {almkvistGiullera(n):>44}"
echo()
echo "Pi to 70 decimal places:"
var
sum = newDecimal(0)
prev = newDecimal(0)
prec = One.scaleb(newDecimal(-70))
n = 0
while true:
sum += almkvistGiullera(n) / One.scaleb(newDecimal(6 * n + 3))
if abs(sum - prev) < prec: break
prev = sum.clone
inc n
let pi = 1 / sqrt(sum)
echo ($pi)[0..71] |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Perl | Perl | use strict;
use warnings;
use feature qw(say);
use Math::AnyNum qw(:overload factorial);
sub almkvist_giullera_integral {
my($n) = @_;
(32 * (14*$n * (38*$n + 9) + 9) * factorial(6*$n)) / (3*factorial($n)**6);
}
sub almkvist_giullera {
my($n) = @_;
almkvist_giullera_integral($n) / (10**(6*$n + 3));
}
sub almkvist_giullera_pi {
my ($prec) = @_;
local $Math::AnyNum::PREC = 4*($prec+1);
my $sum = 0;
my $target = '';
for (my $n = 0; ; ++$n) {
$sum += almkvist_giullera($n);
my $curr = ($sum**-.5)->as_dec;
return $target if ($curr eq $target);
$target = $curr;
}
}
say 'First 10 integer portions: ';
say "$_ " . almkvist_giullera_integral($_) for 0..9;
my $precision = 70;
printf("π to %s decimal places is:\n%s\n",
$precision, almkvist_giullera_pi($precision)); |
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #Arturo | Arturo | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10] |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8th | 8th |
\
\ anagrams.8th
\ Rosetta Code - Anagrams problem
\ Using the word list at:
\ http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
\ find the sets of words that share the same characters
\ that contain the most words in them.
\
ns: anagrams
m:new var, anamap
a:new var, anaptr
0 var, analen
\ sort a string
: s:sort \ s -- s \
null s:/ \ a
' s:cmpi a:sort \ a
"" a:join \ s
;
: process-words \ word -- \ word
s:lc \ word
dup \ word word
>r \ word | word
\ 1. we create a sorted version of the curret word (sword)
s:sort \ sword | word
\ We check if sword can be found in map anamap
anamap @ \ sword anamap | word
over \ sword anamap sword | word
m:exists? \ sword anamap boolean | word
if \ sword anamap | word
\ If sword already exists in anamap:
\ - get mapvalue, which is an array
\ - add the original word to that array
\ - store the array in the map with key sword
over \ sword anamap sword | word
m:@ \ sword anamap array | word
r> \ sword anamap array word
a:push \ sword anamap array
rot \ anamap array sword
swap \ anamap sword array
m:! \ anamap
else \ sword anamap | word
\ If sword does not yet exist in anamap:
\ - create empty array
\ - put the original word into that array
\ - store the array in the map with key sword
swap \ anamap sword | word
a:new \ anamap sword array | word
r> \ anamap sword array word
a:push \ anamap sword array
m:! \ anamap
then
drop \
;
\ Read and check all words in array analist
: read-and-check-words \ -- \
"analist.txt" \ fname
f:open-ro \ f
' process-words f:eachline \ f
f:close \
;
: len< \ key array arraylen -- \ key array arraylen
2drop \ key
drop \
;
: len= \ key array arraylen -- \ key array arraylen
2drop \ key
anaptr @ \ key anaptr
swap \ anaptr key
a:push \ anaptr
drop \
;
: len> \ key array arraylen -- \ key array arraylen
analen \ key array arraylen analen
! \ key array
drop \ key
anaptr @ \ key anaptr
a:clear \ key anaptr
swap \ anaptr key
a:push \ anaptr
drop \
;
: fetch-longest-list \ key array -- \ key array
a:len \ key array arraylen
analen @ \ key array arraylen analen
2dup \ key array arraylen analen arraylen analen
n:cmp \ key array arraylen analen value
1 n:+ \ key array arraylen analen value
nip \ key array arraylen value
[ ' len< , ' len= , ' len> ] \ key array arraylen value swarr
swap \ key array arraylen swarr value
caseof \
;
: list-words-1 \ ix value -- \ ix value
nip \ value
"\t" . . \
;
: list-words \ ix value -- \ ix value
nip \ value
anamap @ \ value anamap
swap \ anamap value
m:@ \ anamap array
nip \ array
' list-words-1 a:each \ array
cr \ array
drop \
;
: app:main
\ Create a map, where the values are arrays, containing all words
\ which are the same when sorted (sword); sword is used as key
read-and-check-words
\ Create an array that holds the keys for anamap, for which the value,
\ which is the array of anagrams, has the biggest length found.
anamap @ ' fetch-longest-list m:each
\ Dump the resulting words to the console
anaptr @ ' list-words a:each drop
bye
;
|
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #Haskell | Haskell | import Control.Monad (join)
import Data.Bifunctor (bimap)
import Text.Printf (printf)
type Radians = Float
type Degrees = Float
---------- ANGLE DIFFERENCE BETWEEN TWO BEARINGS ---------
bearingDelta :: (Radians, Radians) -> Radians
bearingDelta (a, b) -- sign * dot-product
=
sign * acos ((ax * bx) + (ay * by))
where
(ax, ay) = (sin a, cos a)
(bx, by) = (sin b, cos b)
sign
| ((ay * bx) - (by * ax)) > 0 = 1
| otherwise = -1
angleBetweenDegrees :: (Degrees, Degrees) -> Degrees
angleBetweenDegrees =
degrees
. bearingDelta
. join bimap radians
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn . unlines $
fmap
( uncurry (printf "%6.2f° - %6.2f° -> %7.2f°")
<*> angleBetweenDegrees
)
[ (20.0, 45.0),
(-45.0, 45.0),
(-85.0, 90.0),
(-95.0, 90.0),
(-45.0, 125.0),
(-45.0, 145.0)
]
------------------------- GENERIC ------------------------
degrees :: Radians -> Degrees
degrees = (/ pi) . (180 *)
radians :: Degrees -> Radians
radians = (/ 180) . (pi *) |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #K | K | / anagram clusters
a:{x g@&1<#:'g:={x@<x}'x}@0:"unixdict.txt";
/ derangements in these clusters
b@&c=|/c:{#x[0]}'b:a@&{0=+//{x=y}':x}'a
("excitation"
"intoxicate") |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #Io | Io | fib := method(x,
if(x < 0, Exception raise("Negative argument not allowed!"))
fib2 := method(n,
if(n < 2, n, fib2(n-1) + fib2(n-2))
)
fib2(x floor)
) |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #Erlang | Erlang |
-module(properdivs).
-export([amicable/1,divs/1,sumdivs/1]).
amicable(Limit) -> amicable(Limit,[],3,2).
amicable(Limit,List,_Current,Acc) when Acc >= Limit -> List;
amicable(Limit,List,Current,Acc) when Current =< Acc/2 ->
amicable(Limit,List,Acc,Acc+1);
amicable(Limit,List,Current,Acc) ->
CS = sumdivs(Current),
AS = sumdivs(Acc),
if
CS == Acc andalso AS == Current andalso Acc =/= Current ->
io:format("A: ~w, B: ~w, ~nL: ~w~w~n", [Current,Acc,divs(Current),divs(Acc)]),
NL = List ++ [{Current,Acc}],
amicable(Limit,NL,Acc+1,Acc+1);
true ->
amicable(Limit,List,Current-1,Acc) end.
divs(0) -> [];
divs(1) -> [];
divs(N) -> lists:sort(divisors(1,N)).
divisors(1,N) ->
[1] ++ divisors(2,N,math:sqrt(N)).
divisors(K,_N,Q) when K > Q -> [];
divisors(K,N,_Q) when N rem K =/= 0 ->
[] ++ divisors(K+1,N,math:sqrt(N));
divisors(K,N,_Q) when K * K == N ->
[K] ++ divisors(K+1,N,math:sqrt(N));
divisors(K,N,_Q) ->
[K, N div K] ++ divisors(K+1,N,math:sqrt(N)).
sumdivs(N) -> lists:sum(divs(N)).
|
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | mystring = "Hello World! ";
Scroll[str_, dir_] := StringJoin @@ RotateLeft[str // Characters, dir];
GiveString[dir_] := (mystring = Scroll[mystring, dir]);
CreateDialog[{
DynamicModule[{direction = -1},
EventHandler[
Dynamic[TextCell[
Refresh[GiveString[direction], UpdateInterval -> 1/8]],
TrackedSymbols -> {}], {"MouseClicked" :> (direction *= -1)}]]
}]; |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #MAXScript | MAXScript |
try destroydialog animGUI catch ()
global userDirection = "right"
fn reverseStr str: direction: =
(
local lastChar = str[str.count]
local firstChar = str[1]
local newStr = ""
local dir
if direction == unsupplied then dir = "left" else dir = direction
case dir of
(
"right": (newstr = lastChar + (substring str 1 (str.count-1)))
"left": (newstr = (substring str 2 (str.count))+firstChar)
)
return newstr
)
rollout animGUI "Hello World" width:200
(
button switchToLeft "<--" pos:[40,0] height:15
label HelloWorldLabel "Hello World! " pos:[80,0]
button switchToRight "-->" pos:[150,0] height:15
timer activeTimer interval:70 active:true
on activeTimer tick do
(
HelloWorldLabel.text = reverseStr str:(HelloWorldLabel.text) direction:userDirection
)
on switchToLeft pressed do
(
userDirection = "left"
)
on switchToRight pressed do
(
userDirection = "right"
)
)
createdialog animGUI
|
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Go | Go | package main
import (
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/math"
"github.com/google/gxui/themes/dark"
omath "math"
"time"
)
//Two pendulums animated
//Top: Mathematical pendulum with small-angle approxmiation (not appropiate with PHI_ZERO=pi/2)
//Bottom: Simulated with differential equation phi'' = g/l * sin(phi)
const (
ANIMATION_WIDTH int = 480
ANIMATION_HEIGHT int = 320
BALL_RADIUS float32 = 25.0
METER_PER_PIXEL float64 = 1.0 / 20.0
PHI_ZERO float64 = omath.Pi * 0.5
)
var (
l float64 = float64(ANIMATION_HEIGHT) * 0.5
freq float64 = omath.Sqrt(9.81 / (l * METER_PER_PIXEL))
)
type Pendulum interface {
GetPhi() float64
}
type mathematicalPendulum struct {
start time.Time
}
func (p *mathematicalPendulum) GetPhi() float64 {
if (p.start == time.Time{}) {
p.start = time.Now()
}
t := float64(time.Since(p.start).Nanoseconds()) / omath.Pow10(9)
return PHI_ZERO * omath.Cos(t*freq)
}
type numericalPendulum struct {
currentPhi float64
angAcc float64
angVel float64
lastTime time.Time
}
func (p *numericalPendulum) GetPhi() float64 {
dt := 0.0
if (p.lastTime != time.Time{}) {
dt = float64(time.Since(p.lastTime).Nanoseconds()) / omath.Pow10(9)
}
p.lastTime = time.Now()
p.angAcc = -9.81 / (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)
p.angVel += p.angAcc * dt
p.currentPhi += p.angVel * dt
return p.currentPhi
}
func draw(p Pendulum, canvas gxui.Canvas, x, y int) {
attachment := math.Point{X: ANIMATION_WIDTH/2 + x, Y: y}
phi := p.GetPhi()
ball := math.Point{X: x + ANIMATION_WIDTH/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}
line := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}
canvas.DrawLines(line, gxui.DefaultPen)
m := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}
rect := math.Rect{ball.Sub(m), ball.Add(m)}
canvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))
}
func appMain(driver gxui.Driver) {
theme := dark.CreateTheme(driver)
window := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, "Pendulum")
window.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))
image := theme.CreateImage()
ticker := time.NewTicker(time.Millisecond * 15)
pendulum := &mathematicalPendulum{}
pendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}
go func() {
for _ = range ticker.C {
canvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})
canvas.Clear(gxui.White)
draw(pendulum, canvas, 0, 0)
draw(pendulum2, canvas, 0, ANIMATION_HEIGHT)
canvas.Complete()
driver.Call(func() {
image.SetCanvas(canvas)
})
}
}()
window.AddChild(image)
window.OnClose(ticker.Stop)
window.OnClose(driver.Terminate)
}
func main() {
gl.StartDriver(appMain)
} |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Phix | Phix | with javascript_semantics
requires("1.0.0")
include mpfr.e
mpfr_set_default_precision(-70)
function almkvistGiullera(integer n, bool bPrint)
mpz {t1,t2,ip} = mpz_inits(3)
mpz_fac_ui(t1,6*n)
mpz_mul_si(t1,t1,32) -- t1:=2^5*(6n)!
mpz_fac_ui(t2,n)
mpz_pow_ui(t2,t2,6)
mpz_mul_si(t2,t2,3) -- t2:=3*(n!)^6
mpz_mul_si(ip,t1,532*n*n+126*n+9) -- ip:=t1*(532n^2+126n+9)
mpz_fdiv_q(ip,ip,t2) -- ip:=ip/t2
integer pw := 6*n+3
mpz_ui_pow_ui(t1,10,pw) -- t1 := 10^(6n+3)
mpq tm = mpq_init_set_z(ip,t1) -- tm := rat(ip/t1)
if bPrint then
string ips = mpz_get_str(ip),
tms = mpfr_get_fixed(mpfr_init_set_q(tm),50)
tms = trim_tail(tms,"0")
printf(1,"%d %44s %3d %s\n", {n, ips, -pw, tms})
end if
return tm
end function
constant hdr = "N --------------- Integer portion ------------- Pow ----------------- Nth term (50 dp) -----------------"
printf(1,"%s\n%s\n",{hdr,repeat('-',length(hdr))})
for n=0 to 9 do
{} = almkvistGiullera(n, true)
end for
mpq {res,prev,z} = mpq_inits(3),
prec = mpq_init_set_str(sprintf("1/1%s",repeat('0',70)))
integer n = 0
while true do
mpq term := almkvistGiullera(n, false)
mpq_add(res,res,term)
mpq_sub(z,res,prev)
mpq_abs(z,z)
if mpq_cmp(z,prec) < 0 then exit end if
mpq_set(prev,res)
n += 1
end while
mpq_inv(res,res)
mpfr pi = mpfr_init_set_q(res)
mpfr_sqrt(pi,pi)
printf(1,"\nCalculation of pi took %d iterations using the Almkvist-Giullera formula.\n\n",n)
printf(1,"Pi to 70 d.p.: %s\n",mpfr_get_fixed(pi,70))
mpfr_const_pi(pi)
printf(1,"Pi (builtin) : %s\n",mpfr_get_fixed(pi,70))
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #ASIC | ASIC |
REM Almost prime
FOR K = 1 TO 5
S$ = STR$(K)
S$ = LTRIM$(S$)
S$ = "k = " + S$
S$ = S$ + ":"
PRINT S$;
I = 2
C = 0
WHILE C < 10
AN = I
GOSUB CHECKKPRIME:
IF ISKPRIME <> 0 THEN
PRINT I;
C = C + 1
ENDIF
I = I + 1
WEND
PRINT
NEXT K
END
CHECKKPRIME:
REM Check if N (AN) is a K prime (result: ISKPRIME)
F = 0
J = 2
LOOPFOR:
ANMODJ = AN MOD J
LOOPWHILE:
IF ANMODJ <> 0 THEN AFTERWHILE:
IF F = K THEN FEQK:
F = F + 1
AN = AN / J
ANMODJ = AN MOD J
GOTO LOOPWHILE:
AFTERWHILE:
J = J + 1
IF J <= AN THEN LOOPFOR:
IF F = K THEN
ISKPRIME = -1
ELSE
ISKPRIME = 0
ENDIF
RETURN
FEQK:
ISKPRIME = 0
RETURN
|
http://rosettacode.org/wiki/Almost_prime | Almost prime | A k-Almost-prime is a natural number
n
{\displaystyle n}
that is the product of
k
{\displaystyle k}
(possibly identical) primes.
Example
1-almost-primes, where
k
=
1
{\displaystyle k=1}
, are the prime numbers themselves.
2-almost-primes, where
k
=
2
{\displaystyle k=2}
, are the semiprimes.
Task
Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for
1
<=
K
<=
5
{\displaystyle 1<=K<=5}
.
Related tasks
Semiprime
Category:Prime Numbers
| #AutoHotkey | AutoHotkey | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results |
http://rosettacode.org/wiki/Anagrams | Anagrams | When two or more words are composed of the same characters, but in a different order, they are called anagrams.
Task[edit]
Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
find the sets of words that share the same characters that contain the most words in them.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program anagram64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI, 40000
.equ BUFFERSIZE, 300000
/*********************************/
/* Initialized data */
/*********************************/
.data
szFileName: .asciz "./listword.txt"
szMessErreur: .asciz "FILE ERROR."
szCarriageReturn: .asciz "\n"
szMessSpace: .asciz " "
ptBuffex1: .quad sBuffex1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
ptTabBuffer: .skip 8 * MAXI
ptTabAna: .skip 8 * MAXI
tbiCptAna: .skip 8 * MAXI
iNBword: .skip 8
sBuffer: .skip BUFFERSIZE
sBuffex1: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
mov x4,#0 // loop indice
mov x0,AT_FDCWD // current directory
ldr x1,qAdrszFileName // file name
mov x2,#O_RDWR // flags
mov x3,#0 // mode
mov x8,#OPEN //
svc 0
cmp x0,#0 // error open
ble 99f
mov x19,x0 // FD save Fd
ldr x1,qAdrsBuffer // buffer address
ldr x2,qSizeBuf // buffersize
mov x8, #READ
svc 0
cmp x0,#0 // error read ?
blt 99f
mov x5,x0 // save size read bytes
ldr x4,qAdrsBuffer // buffer address
ldr x0,qAdrsBuffer // start word address
mov x2,#0
mov x1,#0 // word length
1:
cmp x2,x5
bge 2f
ldrb w3,[x4,x2]
cmp w3,#0xD // end word ?
cinc x1,x1,ne // increment word length
cinc x2,x2,ne // increment indice
bne 1b // and loop
strb wzr,[x4,x2] // store final zero
bl anaWord // sort word letters
add x2,x2,#2 // jump OD and 0A
add x0,x4,x2 // new address begin word
mov x1,#0 // init length
b 1b // and loop
2:
strb wzr,[x4,x2] // zero final
bl anaWord // last word
mov x0,x19 // file Fd
mov x8, #CLOSE
svc 0
cmp x0,#0 // error close ?
blt 99f
ldr x0,qAdrptTabAna // address sorted string area
mov x1,#0 // first indice
ldr x2,qAdriNBword
ldr x2,[x2] // last indice
ldr x3,qAdrptTabBuffer // address sorted string area
bl triRapide // quick sort
ldr x4,qAdrptTabAna // address sorted string area
ldr x7,qAdrptTabBuffer // address sorted string area
ldr x10,qAdrtbiCptAna // address counter occurences
mov x9,x2 // size word array
mov x8,#0 // indice first occurence
ldr x3,[x4,x8,lsl #3] // load first value
mov x2,#1 // loop indice
mov x6,#0 // counter
mov x12,#0 // counter value max
3:
ldr x5,[x4,x2,lsl #3] // load next value
mov x0,x3
mov x1,x5
bl comparStrings
cmp x0,#0 // sorted strings equal ?
bne 4f
add x6,x6,#1 // yes increment counter
b 5f
4: // no
str x6,[x10,x8,lsl #3] // store counter in first occurence
cmp x6,x12 // counter > value max
csel x12,x6,x12,gt // yes counter -> value max
//movgt x12,x6 // yes counter -> value max
mov x6,#0 // raz counter
mov x8,x2 // init index first occurence
mov x3,x5 // init value first occurence
5:
add x2,x2,#1 // increment indice
cmp x2,x9 // end word array ?
blt 3b // no -> loop
mov x2,#0 // raz indice
6: // display loop
ldr x6,[x10,x2,lsl #3] // load counter
cmp x6,x12 // equal to max value ?
bne 8f
ldr x0,[x7,x2,lsl #3] // load address first word
bl affichageMess
add x3,x2,#1 // increment new indixe
mov x4,#0 // counter
7:
ldr x0,qAdrszMessSpace
bl affichageMess
ldr x0,[x7,x3,lsl #3] // load address other word
bl affichageMess
add x3,x3,#1 // increment indice
add x4,x4,#1 // increment counter
cmp x4,x6 // max value ?
blt 7b // no loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
8:
add x2,x2,#1 // increment indice
cmp x2,x9 // maxi ?
blt 6b // no -> loop
b 100f
99: // display error
ldr x0,qAdrszMessErreur
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszFileName: .quad szFileName
qAdrszMessErreur: .quad szMessErreur
qAdrsBuffer: .quad sBuffer
qSizeBuf: .quad BUFFERSIZE
qAdrszMessSpace: .quad szMessSpace
qAdrtbiCptAna: .quad tbiCptAna
/******************************************************************/
/* analizing word */
/******************************************************************/
/* x0 word address */
/* x1 word length */
anaWord:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x5,x0
mov x6,x1
ldr x1,qAdrptTabBuffer
ldr x2,qAdriNBword
ldr x3,[x2]
str x0,[x1,x3,lsl #3]
ldr x1,qAdrptTabAna
ldr x4,qAdrptBuffex1
ldr x0,[x4]
add x6,x6,x0
add x6,x6,#1
str x6,[x4]
str x0,[x1,x3,lsl #3]
add x3,x3,#1
str x3,[x2]
mov x1,x0
mov x0,x5
bl triLetters // sort word letters
mov x2,#0
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrptTabBuffer: .quad ptTabBuffer
qAdrptTabAna: .quad ptTabAna
qAdriNBword: .quad iNBword
qAdrptBuffex1: .quad ptBuffex1
/******************************************************************/
/* sort word letters */
/******************************************************************/
/* x0 address begin word */
/* x1 address recept array */
triLetters:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x2,#0
1:
ldrb w3,[x0,x2] // load letter
cmp w3,#0 // end word ?
beq 6f
cmp x2,#0 // first letter ?
bne 2f
strb w3,[x1,x2] // yes store in first position
add x2,x2,#1 // increment indice
b 1b // and loop
2:
mov x4,#0
3: // begin loop to search insertion position
ldrb w5,[x1,x4] // load letter
cmp w3,w5 // compare
blt 4f // to low -> insertion
add x4,x4,#1 // increment indice
cmp x4,x2 // compare to letters number in place
blt 3b // search loop
strb w3,[x1,x2] // else store in last position
add x2,x2,#1
b 1b // and loop
4: // move first letters in one position
sub x6,x2,#1 // start indice
5:
ldrb w5,[x1,x6] // load letter
add x7,x6,#1 // store indice - 1
strb w5,[x1,x7] // store letter
sub x6,x6,#1 // decrement indice
cmp x6,x4 // end ?
bge 5b // no loop
strb w3,[x1,x4] // else store letter in free position
add x2,x2,#1
b 1b // and loop
6:
strb wzr,[x1,x2] // final zéro
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/***************************************************/
/* Appel récursif Tri Rapide quicksort */
/***************************************************/
/* x0 contains the address of table */
/* x1 contains index of first item */
/* x2 contains the number of elements > 0 */
/* x3 contains the address of table 2 */
triRapide:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x6,x3
sub x2,x2,#1 // last item index
cmp x1,x2 // first > last ?
bge 100f // yes -> end
mov x4,x0 // save x0
mov x5,x2 // save x2
mov x3,x6
bl partition1 // cutting.quado 2 parts
mov x2,x0 // index partition
mov x0,x4 // table address
bl triRapide // sort lower part
mov x0,x4 // table address
add x1,x2,#1 // index begin = index partition + 1
add x2,x5,#1 // number of elements
bl triRapide // sort higter part
100: // end function
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Partition table elements */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains index of first item */
/* x2 contains index of last item */
/* x3 contains the address of table 2 */
partition1:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
stp x10,x12,[sp,-16]! // save registers
mov x8,x0 // save address table 2
mov x9,x1
ldr x10,[x8,x2,lsl #3] // load string address last index
mov x4,x9 // init with first index
mov x5,x9 // init with first index
1: // begin loop
ldr x6,[x8,x5,lsl #3] // load string address
mov x0,x6
mov x1,x10
bl comparStrings
cmp x0,#0
bge 2f
ldr x7,[x8,x4,lsl #3] // if < swap value table
str x6,[x8,x4,lsl #3]
str x7,[x8,x5,lsl #3]
ldr x7,[x3,x4,lsl #3] // swap array 2
ldr x12,[x3,x5,lsl #3]
str x7,[x3,x5,lsl #3]
str x12,[x3,x4,lsl #3]
add x4,x4,#1 // and increment index 1
2:
add x5,x5,#1 // increment index 2
cmp x5,x2 // end ?
blt 1b // no -> loop
ldr x7,[x8,x4,lsl #3] // swap value
str x10,[x8,x4,lsl #3]
str x7,[x8,x2,lsl #3]
ldr x7,[x3,x4,lsl #3] // swap array 2
ldr x12,[x3,x2,lsl #3]
str x7,[x3,x2,lsl #3]
str x12,[x3,x4,lsl #3]
mov x0,x4 // return index partition
100:
ldp x10,x12,[sp],16 // restaur 2 registers
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/************************************/
/* Strings case sensitive comparisons */
/************************************/
/* x0 et x1 contains the address of strings */
/* return 0 in x0 if equals */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparStrings:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x2,#0 // counter
1:
ldrb w3,[x0,x2] // byte string 1
ldrb w4,[x1,x2] // byte string 2
cmp w3,w4
blt 2f // small
bgt 3f // greather
cmp x3,#0 // 0 end string
beq 4f // end string
add x2,x2,#1 // else add 1 in counter
b 1b // and loop
2:
mov x0,#-1 // small
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equal
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Angle_difference_between_two_bearings | Angle difference between two bearings | Finding the angle between two bearings is often confusing.[1]
Task
Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings.
Input bearings are expressed in the range -180 to +180 degrees.
The result is also expressed in the range -180 to +180 degrees.
Compute the angle for the following pairs:
20 degrees (b1) and 45 degrees (b2)
-45 and 45
-85 and 90
-95 and 90
-45 and 125
-45 and 145
29.4803 and -88.6381
-78.3251 and -159.036
Optional extra
Allow the input bearings to be any (finite) value.
Test cases
-70099.74233810938 and 29840.67437876723
-165313.6666297357 and 33693.9894517456
1174.8380510598456 and -154146.66490124757
60175.77306795546 and 42213.07192354373
| #IS-BASIC | IS-BASIC | 100 INPUT PROMPT "1. angle: ":A1
110 INPUT PROMPT "2. angle: ":A2
120 LET B=MOD(A2-A1,360)
130 IF B>180 THEN LET B=B-360
140 IF B<-180 THEN LET B=B+360
150 PRINT "Difference: ";B |
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams | Anagrams/Deranged anagrams | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words.
Task[edit]
Use the word list at unixdict to find and display the longest deranged anagram.
Related tasks
Permutations/Derangements
Best shuffle
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | // version 1.0.6
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL
fun isDeranged(s1: String, s2: String): Boolean {
return (0 until s1.length).none { s1[it] == s2[it] }
}
fun main(args: Array<String>) {
val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
val isr = InputStreamReader(url.openStream())
val reader = BufferedReader(isr)
val anagrams = mutableMapOf<String, MutableList<String>>()
var count = 0
var word = reader.readLine()
while (word != null) {
val chars = word.toCharArray()
chars.sort()
val key = chars.joinToString("")
if (!anagrams.containsKey(key)) {
anagrams.put(key, mutableListOf<String>())
anagrams[key]!!.add(word)
}
else {
val deranged = anagrams[key]!!.any { isDeranged(it, word) }
if (deranged) {
anagrams[key]!!.add(word)
count = Math.max(count, word.length)
}
}
word = reader.readLine()
}
reader.close()
anagrams.values
.filter { it.size > 1 && it[0].length == count }
.forEach { println(it) }
} |
http://rosettacode.org/wiki/Anonymous_recursion | Anonymous recursion | While implementing a recursive function, it often happens that we must resort to a separate helper function to handle the actual recursion.
This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects, and/or the function doesn't have the right arguments and/or return values.
So we end up inventing some silly name like foo2 or foo_helper. I have always found it painful to come up with a proper name, and see some disadvantages:
You have to think up a name, which then pollutes the namespace
Function is created which is called from nowhere else
The program flow in the source code is interrupted
Some languages allow you to embed recursion directly in-place. This might work via a label, a local gosub instruction, or some special keyword.
Anonymous recursion can also be accomplished using the Y combinator.
Task
If possible, demonstrate this by writing the recursive version of the fibonacci function (see Fibonacci sequence) which checks for a negative argument before doing the actual recursion.
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Fibonacc.bas"
110 FOR I=0 TO 10
120 PRINT FIB(I);
130 NEXT
140 DEF FIB(K)
150 SELECT CASE K
160 CASE IS<0
170 PRINT "Negative parameter to Fibonacci.":STOP
180 CASE 0
190 LET FIB=0
200 CASE 1
210 LET FIB=1
220 CASE ELSE
230 LET FIB=FIB(K-1)+FIB(K-2)
240 END SELECT
250 END DEF |
http://rosettacode.org/wiki/Amicable_pairs | Amicable pairs | Two integers
N
{\displaystyle N}
and
M
{\displaystyle M}
are said to be amicable pairs if
N
≠
M
{\displaystyle N\neq M}
and the sum of the proper divisors of
N
{\displaystyle N}
(
s
u
m
(
p
r
o
p
D
i
v
s
(
N
)
)
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}
)
=
M
{\displaystyle =M}
as well as
s
u
m
(
p
r
o
p
D
i
v
s
(
M
)
)
=
N
{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}
.
Example
1184 and 1210 are an amicable pair, with proper divisors:
1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and
1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.
Task
Calculate and show here the Amicable pairs below 20,000; (there are eight).
Related tasks
Proper divisors
Abundant, deficient and perfect number classifications
Aliquot sequence classifications and its amicable classification.
| #ERRE | ERRE | PROGRAM AMICABLE
CONST LIMIT=20000
PROCEDURE SUMPROP(NUM->M)
IF NUM<2 THEN M=0 EXIT PROCEDURE
SUM=1
ROOT=SQR(NUM)
FOR I=2 TO ROOT-1 DO
IF (NUM=I*INT(NUM/I)) THEN
SUM=SUM+I+NUM/I
END IF
IF (NUM=ROOT*INT(NUM/ROOT)) THEN
SUM=SUM+ROOT
END IF
END FOR
M=SUM
END PROCEDURE
BEGIN
PRINT(CHR$(12);) ! CLS
PRINT("Amicable pairs < ";LIMIT)
FOR N=1 TO LIMIT DO
SUMPROP(N->M1)
SUMPROP(M1->M2)
IF (N=M2 AND N<M1) THEN PRINT(N,M1)
END FOR
END PROGRAM |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #MiniScript | MiniScript | clear
text.inverse = true
s = "Hello World! "
while not key.available
text.row = 12
text.column = 15
print " " + s + " "
wait 0.1
s = s[-1] + s[:-1]
end while
text.inverse = false
key.clear |
http://rosettacode.org/wiki/Animation | Animation |
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this.
Task
Create a window containing the string "Hello World! " (the trailing space is significant).
Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front.
When the user clicks on the (windowed) text, it should reverse its direction.
| #Nim | Nim | import gintro/[glib, gobject, gdk, gtk, gio]
type
# Scrolling direction.
ScrollDirection = enum toLeft, toRight
# Data transmitted to update callback.
UpdateData = ref object
label: Label
scrollDir: ScrollDirection
#---------------------------------------------------------------------------------------------------
proc update(data: UpdateData): gboolean =
## Update the text, scrolling to the right or to the left according to "data.scrollDir".
data.label.setText(if data.scrollDir == toRight: data.label.text[^1] & data.label.text[0..^2]
else: data.label.text[1..^1] & data.label.text[0])
result = gboolean(1)
#---------------------------------------------------------------------------------------------------
proc changeScrollingDir(evtBox: EventBox; event: EventButton; data: UpdateData): bool =
## Change scrolling direction.
data.scrollDir = ScrollDirection(1 - ord(data.scrollDir))
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
let window = app.newApplicationWindow()
window.setSizeRequest(150, 50)
window.setTitle("Animation")
# Create an event box to catch the button press event.
let evtBox = newEventBox()
window.add(evtBox)
# Create the label and add it to the event box.
let label = newLabel("Hello World! ")
evtBox.add(label)
# Create the update data.
let data = UpdateData(label: label, scrollDir: toRight)
# Connect the "button-press-event" to the callback to change scrolling direction.
discard evtBox.connect("button-press-event", changeScrollingDir, data)
# Create a timer to update the label and simulate scrolling.
timeoutAdd(200, update, data)
window.showAll()
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.animation")
discard app.connect("activate", activate)
discard app.run() |
http://rosettacode.org/wiki/Animate_a_pendulum | Animate a pendulum |
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display.
The classic such physical system is a simple gravity pendulum.
Task
Create a simple physical model of a pendulum and animate it.
| #Haskell | Haskell | import Graphics.HGL.Draw.Monad (Graphic, )
import Graphics.HGL.Draw.Picture
import Graphics.HGL.Utils
import Graphics.HGL.Window
import Graphics.HGL.Run
import Control.Exception (bracket, )
import Control.Arrow
toInt = fromIntegral.round
pendulum = runGraphics $
bracket
(openWindowEx "Pendulum animation task" Nothing (600,400) DoubleBuffered (Just 30))
closeWindow
(\w -> mapM_ ((\ g -> setGraphic w g >> getWindowTick w).
(\ (x, y) -> overGraphic (line (300, 0) (x, y))
(ellipse (x - 12, y + 12) (x + 12, y - 12)) )) pts)
where
dt = 1/30
t = - pi/4
l = 1
g = 9.812
nextAVT (a,v,t) = (a', v', t + v' * dt) where
a' = - (g / l) * sin t
v' = v + a' * dt
pts = map (\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi/2+0.6*t) )
$ iterate nextAVT (- (g / l) * sin t, t, 0) |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #PicoLisp | PicoLisp | (scl 70)
(de fact (N)
(if (=0 N)
1
(* N (fact (dec N))) ) )
(de almkvist (N)
(let
(A (* 32 (fact (* 6 N)))
B (+ (* 532 N N) (* 126 N) 9)
C (* (** (fact N) 6) 3) )
(/ (* A B) C) ) )
(de integral (N)
(*/
1.0
(almkvist N)
(** 10 (+ 3 (* 6 N))) ) )
(let (S 0 N -1)
(do 10
(println (inc 'N) (almkvist N)) )
(prinl)
(setq N -1)
(while (gt0 (integral (inc 'N)))
(inc 'S @) )
(setq S (sqrt (*/ 1.0 1.0 S) 1.0))
(prinl "Pi to 70 decimal places is:")
(prinl (format S *Scl)) ) |
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi | Almkvist-Giullera formula for pi | The Almkvist-Giullera formula for calculating 1/π2 is based on the Calabi-Yau
differential equations of order 4 and 5, which were originally used to describe certain manifolds
in string theory.
The formula is:
1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1
This formula can be used to calculate the constant π-2, and thus to calculate π.
Note that, because the product of all terms but the power of 1000 can be calculated as an integer,
the terms in the series can be separated into a large integer term:
(25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***)
multiplied by a negative integer power of 10:
10-(6n + 3)
Task
Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series.
Use the complete formula to calculate and print π to 70 decimal digits of precision.
Reference
Gert Almkvist and Jesús Guillera, Ramanujan-like series for 1/π2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
| #Python | Python | import mpmath as mp
with mp.workdps(72):
def integer_term(n):
p = 532 * n * n + 126 * n + 9
return (p * 2**5 * mp.factorial(6 * n)) / (3 * mp.factorial(n)**6)
def exponent_term(n):
return -(mp.mpf("6.0") * n + 3)
def nthterm(n):
return integer_term(n) * mp.mpf("10.0")**exponent_term(n)
for n in range(10):
print("Term ", n, ' ', int(integer_term(n)))
def almkvist_guillera(floatprecision):
summed, nextadd = mp.mpf('0.0'), mp.mpf('0.0')
for n in range(100000000):
nextadd = summed + nthterm(n)
if abs(nextadd - summed) < 10.0**(-floatprecision):
break
summed = nextadd
return nextadd
print('\nπ to 70 digits is ', end='')
mp.nprint(mp.mpf(1.0 / mp.sqrt(almkvist_guillera(70))), 71)
print('mpmath π is ', end='')
mp.nprint(mp.pi, 71)
|
http://rosettacode.org/wiki/Amb | Amb | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
"the" "that" "a"
"frog" "elephant" "thing"
"walked" "treaded" "grows"
"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| #11l | 11l | F amb(comp, options, prev = ‘’) -> Array[String]
I options.empty
R []
L(opt) options[0]
// If this is the base call, prev is empty and we need to continue.
I prev != ‘’ & !comp(prev, opt)
L.continue
// Take care of the case where we have no options left.
I options.len == 1
R [opt]
// Traverse into the tree.
V res = amb(comp, options[1..], opt)
// If it was a failure, try the next one.
if !res.empty
R opt [+] res // We have a match
R []
V sets = [[‘the’, ‘that’, ‘a’],
[‘frog’, ‘elephant’, ‘thing’],
[‘walked’, ‘treaded’, ‘grows’],
[‘slowly’, ‘quickly’]]
V result = amb((s, t) -> s.last == t[0], sets)
print(result.join(‘ ’)) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.