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 uni... | #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... |
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 f... | #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) + p... |
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º
... | #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 normaliz... |
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
... | #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 => properDi... |
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
Creat... | #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 =... |
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;
$ ... |
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 calcul... | #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
... |
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 calcul... | #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*... |
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
{\displaystyl... | #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.
... | #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
... |
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 uni... | #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 #... |
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 f... | #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 m... |
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º
... | #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 640... |
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º
... | #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.<... |
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
... | #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
... |
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
Creat... | #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.oncli... |
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}... |
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 calcul... | #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... |
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 calcul... | #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... |
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
{\displaystyl... | #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... |
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
{\displaystyl... | #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
... |
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.
... | #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- ... |
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 uni... | #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 f... | #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)... |
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º
... | #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... |
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
... | #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
... |
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
Creat... | #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)
rig... |
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
Creat... | #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
... |
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 ... |
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 calcul... | #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 b... |
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
{\displaystyl... | #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 ... |
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.
... | #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 ... |
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 uni... | #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 IOEx... |
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 f... | #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)... |
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º
... | #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... |
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
... | #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)
... |
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
Creat... | #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]
... |
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 )... |
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 calcul... | #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
(almkvistGiullera... |
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
{\displaystyl... | #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 ... |
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.
... | #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(Spac... |
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 uni... | #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 findLongestD... |
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 f... | #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º
... | #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 {
... |
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º
... | #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 no... |
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
... | #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
Creat... | #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]
... |
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, 10... |
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 calcul... | #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... |
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 calcul... | #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++) {
l... |
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
{\displaystyl... | #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
... |
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
{\displaystyl... | #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.
... | #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.Su... |
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 uni... | #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);
# Chec... |
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 f... | #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º
... | #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 d2... |
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º
... | #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 g... |
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
... | #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.Proper... |
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
Creat... | #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... |
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
Creat... | #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:getHe... |
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
... |
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 calcul... | #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
... |
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 calcul... | #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 ... |
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 calcul... | #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
{\displaystyl... | #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,... |
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
... | #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.
... | #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 uni... | #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 ... |
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 f... | #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) ... |
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º
... | #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 64... |
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º
... | #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... |
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
... | #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) ... |
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
Creat... | #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 My... |
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
Creat... | #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.WHIT... |
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 calcul... | #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 = 5... |
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 calcul... | #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));
... |
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
{\displaystyl... | #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... |
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
... | #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
... |
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.
... | #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 * ... |
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 uni... | #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 f... | #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
... | #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,Curre... |
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
Creat... | #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]],
Tr... |
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
Creat... | #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 + (subs... |
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: Simulat... |
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 calcul... | #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(t... |
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
{\displaystyl... | #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)... |
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
{\displaystyl... | #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"
... |
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
... | #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 "../includeConstantesARM6... |
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.
... | #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 uni... | #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")
... |
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 f... | #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 DE... |
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
... | #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
... |
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
Creat... | #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
Creat... | #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
#--------------------------------------------------------------------------------... |
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 tas... |
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 calcul... | #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 (... |
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 calcul... | #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")... |
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 v... | #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 ==... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.