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/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.
| #Dart | Dart | import 'package:flutter/material.dart';
import 'dart:async' show Timer;
void main() {
var timer = const Duration( milliseconds: 75 ); // How often to update i.e. how fast the animation is
runApp(MaterialApp (
home: Scaffold (
body: Center (
child: AnimatedText( timer )
)
)
));
}
class AnimatedText extends StatefulWidget {
final Duration period; // Time period for update
AnimatedText( this.period );
@override
_AnimatedText createState() => _AnimatedText( period );
}
class _AnimatedText extends State<AnimatedText> {
bool forward = true; // Text should go forward?
Timer timer; // Timer Objects allow us to do things based on a period of time
// We want to get an array of characters, but Dart does not have a char type
// Below is the equivalent code
var _text = 'Hello World! '.runes // .runes gives us the unicode number of each character
.map( (code) => String.fromCharCode(code) ) // Map all these codes to Strings containing the single character
.toList(); // Conver to a List
_AnimatedText( Duration period ){
timer = Timer.periodic( period , (_){
setState((){ // Set state forces the gui elements to be redrawn
shiftText();
});
});
}
String get text => _text.join(''); // Getter, joins the list of chars into a string
void shiftText() {
if (forward) { // If we should go forward
var last = _text.removeLast(); // Remove the last char
_text.insert( 0, last); // Insert it at the front
} else { // If we should go backward
var first = _text.removeAt(0); // Remove the first char
_text.insert( _text.length, first ); // Insert it at the end
}
}
@override
Widget build(BuildContext context) {
return GestureDetector( // GestureDetector lets us capture events
onTap: () => forward = !forward, // on Tap (Click in browser) invert the forward bool
child: Text(
text, // Call the text getter to get the shifted string
style: TextStyle( // Styling
fontSize: 50,
color: Colors.grey[600]
)
)
);
}
}
|
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.
| #Amazing_Hopper | Amazing Hopper |
#include <flow.h>
#include <flow-term.h>
DEF-MAIN(argv,argc)
SET( Pen, 0 )
LET( Pen := STR-TO-UTF8(CHAR(219)) )
CLR-SCR
HIDE-CURSOR
GOSUB( Animate a Pendulum )
SHOW-CURSOR
END
RUTINES
DEF-FUN( Animate a Pendulum )
MSET( accel, speed, bx, by )
SET( theta, M_PI_2 ) // pi/2 constant --> flow.h
SET( g, 9.81 )
SET( l, 1 )
SET( px, 65 )
SET( py, 7 )
LOOP( Animate All )
LET( bx := ADD( px, MUL( MUL( l, 23 ), SIN(theta) ) ) )
LET( by := SUB( py, MUL( MUL( l, 23 ), COS(theta) ) ) )
CLR-SCR
{px,py,bx,by} GOSUB( LINE )
{bx, by, 3} GOSUB( CIRCLE )
LET( accel := MUL(g, SIN(theta) DIV-INTO(l) DIV-INTO(4) ) )
LET( speed := ADD( speed, DIV(accel, 100) ) )
LET( theta := ADD( theta, speed ) )
LOCATE (1, 62) PRNL("PENDULUM")
LOCATE (2, 55) PRNL("Press any key to quit")
SLEEP( 0.1 )
BACK-IF ( NOT( KEY-PRESSED? ), Animate All )
RET
/* DDA Algorithm */
DEF-FUN(LINE, x1, y1, x2, y2)
MSET( x, y, dx, dy, paso, i, gm )
STOR( SUB(x2, x1) SUB(y2, y1), dx, dy )
LET( paso := IF( GE?( ABS(dx) » (DX), ABS(dy)»(DY) ), DX, DY ) )
// increment:
STOR( DIV(dx, paso) DIV(dy, paso), dx, dy )
// print line:
SET( i, 0 )
WHILE( LE?(i, paso), ++i )
LOCATE( y1, x1 ), PRNL( Pen )
STOR( ADD( x1, dx) ADD( y1, dy ), x1, y1 )
WEND
RET
DEF-FUN( Plot Points, xc, yc ,x1 ,y1 )
LOCATE( ADD(xc,x1), ADD( yc, y1) ), PRN( Pen )
LOCATE( SUB(xc,x1), ADD( yc, y1) ), PRN( Pen )
LOCATE( ADD(xc,x1), SUB( yc, y1) ), PRN( Pen )
LOCATE( SUB(xc,x1), SUB( yc, y1) ), PRN( Pen )
LOCATE( ADD(xc,y1), ADD( yc, x1) ), PRN( Pen )
LOCATE( SUB(xc,y1), ADD( yc, x1) ), PRN( Pen )
LOCATE( ADD(xc,y1), SUB( yc, x1) ), PRN( Pen )
LOCATE( SUB(xc,y1), SUB( yc, x1) ), PRNL( Pen )
RET
DEF-FUN( CIRCLE, xc, yc, ratio )
MSET( x, p )
SET( y, ratio )
LOCATE( yc,xc ), PRNL("O")
{yc, xc, y, x} GOSUB( Plot Points )
LET( p := SUB( 1, ratio ) )
LOOP( Print Circle )
++x
COND( LT?( p, 0 ) )
LET( p := ADD( p, MUL(2,x) ) PLUS(1) )
ELS
--y
LET( p := ADD( p, MUL(2, SUB(x,y))) PLUS(1) )
CEND
{yc, xc, y, x} GOSUB( Plot Points )
BACK-IF-LT( x, y, Print Circle )
RET
|
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
| #BASIC256 | BASIC256 | # Rosetta Code problem: http://rosettacode.org/wiki/Angle_difference_between_two_bearings
# by Jjuanhdez, 06/2022
print "Input in -180 to +180 range:"
call getDifference(20.0, 45.0)
call getDifference(-45.0, 45.0)
call getDifference(-85.0, 90.0)
call getDifference(-95.0, 90.0)
call getDifference(-45.0, 125.0)
call getDifference(-45.0, 145.0)
call getDifference(-45.0, 125.0)
call getDifference(-45.0, 145.0)
call getDifference(29.4803, -88.6381)
call getDifference(-78.3251, -159.036)
print
print "Input in wider range:"
call getDifference(-70099.74233810938, 29840.67437876723)
call getDifference(-165313.6666297357, 33693.9894517456)
call getDifference(1174.8380510598456, -154146.66490124757)
end
subroutine getDifference(b1, b2)
r = (b2 - b1) mod 360
if r >= 180.0 then r -= 360.0
print ljust(b1,16); ljust(b2,16); ljust(r,12)
end subroutine |
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
| #D | D | void main() {
import std.stdio, std.file, std.algorithm, std.string, std.array;
string[][dstring] anags;
foreach (const w; "unixdict.txt".readText.split)
anags[w.array.sort().release.idup] ~= w;
anags
.byValue
.map!(words => words.cartesianProduct(words)
.filter!q{ a[].equal!q{ a != b }})
.join
.minPos!q{ a[0].length > b[0].length }[0]
.writeln;
} |
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.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | Y f:
labda y:
labda:
f y @y
call dup
labda fib n:
if <= n 1:
1
else:
fib - n 1
fib - n 2
+
Y
set :fibo
for j range 0 10:
!print fibo j |
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
| #Factor | Factor | USING: accessors combinators formatting inverse kernel math
math.constants quotations qw sequences units.si ;
IN: rosetta-code.angles
ALIAS: degrees arc-deg
: gradiens ( n -- d ) 9/10 * degrees ;
: mils ( n -- d ) 9/160 * degrees ;
: normalize ( d -- d' ) [ 2 pi * mod ] change-value ;
CONSTANT: units { degrees gradiens mils radians }
: .row ( angle unit -- )
2dup "%-12u%-12s" printf ( x -- x ) execute-effect
normalize units [ 1quotation [undo] call( x -- x ) ] with
map "%-12.4f%-12.4f%-12.4f%-12.4f\n" vprintf ;
: .header ( -- )
qw{ angle unit } units append
"%-12s%-12s%-12s%-12s%-12s%-12s\n" vprintf ;
: angles ( -- )
.header
{ -2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000 }
units [ .row ] cartesian-each ;
MAIN: angles |
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
| #FreeBASIC | FreeBASIC | #define PI 3.1415926535897932384626433832795028842
#define INVALID -99999
function clamp( byval n as double, lo as double, hi as double ) as double
while n <= lo
n += (hi - lo)/2
wend
while n >= hi
n += (lo - hi)/2
wend
return n
end function
function anglenc( byval angle as double, byval source as string, byval targ as string ) as double
source = ucase(source)
targ = ucase(targ)
select case source
case "D":
angle = clamp(angle, -360, 360)
select case targ
case "D":
return angle
case "G":
return angle*10/9
case "M":
return angle*160/9
case "R":
return angle*PI/180
case "T":
return angle/360
case else
return INVALID
end select
case "G":
angle = clamp(angle, -400, 400)
select case targ
case "D":
return angle*9/10
case "G":
return angle
case "M":
return angle*16
case "R":
return angle*PI/200
case "T":
return angle/400
case else
return INVALID
end select
case "M":
angle = clamp(angle, -6400, 6400)
select case targ
case "D":
return angle*9/160
case "G":
return angle/16
case "M":
return angle
case "R":
return angle*PI/3200
case "T":
return angle/6400
case else
return INVALID
end select
case "R":
angle = clamp(angle, -2*PI, 2*PI)
select case targ
case "D":
return angle*180/PI
case "G":
return angle*200/PI
case "M":
return angle*3200/PI
case "R":
return angle
case "T":
return angle/(2*PI)
case else
return INVALID
end select
case "T":
angle = clamp(angle, -1, 1)
select case targ
case "D":
return angle*360
case "G":
return angle*400
case "M":
return angle*6400
case "R":
return angle*2*PI
case "T":
return angle
case else
return INVALID
end select
case else:
return INVALID
end select
end function
function clip( st as string, num as uinteger ) as string
if len(st)<num then return st
return left(st, num)
end function
dim as string scales = "DGMRT", source, targ
dim as double angles(12) = {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000}
print "Angle Normalised Unit | D G M R T"
for k as ubyte = 0 to 11
for i as ubyte = 1 to 5
source = mid(scales,i,1)
print angles(k), clip(str(anglenc(angles(k), source, source )), 10), source, "|",
for j as ubyte = 1 to 5
targ = mid(scales, j, 1)
print clip(str(anglenc(angles(k), source, targ )), 10),
next j
print
next i
next k
|
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.
| #AWK | AWK |
#!/bin/awk -f
function sumprop(num, i,sum,root) {
if (num < 2) return 0
sum=1
root=sqrt(num)
for ( i=2; i < root; i++) {
if (num % i == 0 )
{
sum = sum + i + num/i
}
}
if (num % root == 0)
{
sum = sum + root
}
return sum
}
BEGIN{
limit=20000
print "Amicable pairs < ",limit
for (n=1; n < limit+1; n++)
{
m=sumprop(n)
if (n == sumprop(m) && n < m) print n,m
}
}
} |
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.
| #Delphi | Delphi |
unit Main;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms,
Vcl.StdCtrls, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
lblAniText: TLabel;
tmrAniFrame: TTimer;
procedure lblAniTextClick(Sender: TObject);
procedure tmrAniFrameTimer(Sender: TObject);
end;
var
Form1: TForm1;
Reverse: boolean = false;
implementation
{$R *.dfm}
procedure TForm1.lblAniTextClick(Sender: TObject);
begin
Reverse := not Reverse;
end;
function Shift(text: string; direction: boolean): string;
begin
if direction then
result := text[text.Length] + text.Substring(0, text.Length - 1)
else
result := text.Substring(1, text.Length) + text[1];
end;
procedure TForm1.tmrAniFrameTimer(Sender: TObject);
begin
with lblAniText do
Caption := Shift(Caption, Reverse);
end;
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.
| #AutoHotkey | AutoHotkey | SetBatchlines,-1
;settings
SizeGUI:={w:650,h:400} ;Guisize
pendulum:={length:300,maxangle:90,speed:2,size:30,center:{x:Sizegui.w//2,y:10}} ;pendulum length, size, center, speed and maxangle
pendulum.maxangle:=pendulum.maxangle*0.01745329252
p_Token:=Gdip_Startup()
Gui,+LastFound
Gui,show,% "w" SizeGUI.w " h" SizeGUI.h
hwnd:=WinActive()
hdc:=GetDC(hwnd)
start:=A_TickCount/1000
G:=Gdip_GraphicsFromHDC(hdc)
pBitmap:=Gdip_CreateBitmap(650, 450)
G2:=Gdip_GraphicsFromImage(pBitmap)
Gdip_SetSmoothingMode(G2, 4)
pBrush := Gdip_BrushCreateSolid(0xff0000FF)
pBrush2 := Gdip_BrushCreateSolid(0xFF777700)
pPen:=Gdip_CreatePenFromBrush(pBrush2, 10)
SetTimer,Update,10
Update:
Gdip_GraphicsClear(G2,0xFFFFFFFF)
time:=start-(A_TickCount/1000*pendulum.speed)
angle:=sin(time)*pendulum.maxangle
x2:=sin(angle)*pendulum.length+pendulum.center.x
y2:=cos(angle)*pendulum.length+pendulum.center.y
Gdip_DrawLine(G2,pPen,pendulum.center.x,pendulum.center.y,x2,y2)
GDIP_DrawCircle(G2,pBrush,pendulum.center.x,pendulum.center.y,15)
GDIP_DrawCircle(G2,pBrush2,x2,y2,pendulum.size)
Gdip_DrawImage(G, pBitmap)
return
GDIP_DrawCircle(g,b,x,y,r){
Gdip_FillEllipse(g, b, x-r//2,y-r//2 , r, r)
}
GuiClose:
ExitApp |
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
| #Befunge | Befunge | 012pv1 2 3 4 5 6 7 8
>&:v >859**%:459**1-`#v_ >12g!:12p#v_\-:459**1-`#v_ >.>
>0`#^_8v >859**-^ >859**-^
^:+**95< > ^
|
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
| #Delphi | Delphi | program Anagrams_Deranged;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes,
System.Diagnostics;
function Sort(s: string): string;
var
c: Char;
i, j, aLength: Integer;
begin
aLength := s.Length;
if aLength = 0 then
exit('');
Result := s;
for i := 1 to aLength - 1 do
for j := i + 1 to aLength do
if result[i] > result[j] then
begin
c := result[i];
result[i] := result[j];
result[j] := c;
end;
end;
function IsAnagram(s1, s2: string): Boolean;
begin
if s1.Length <> s2.Length then
exit(False);
Result := Sort(s1) = Sort(s2);
end;
function CompareLength(List: TStringList; Index1, Index2: Integer): Integer;
begin
result := List[Index1].Length - List[Index2].Length;
if Result = 0 then
Result := CompareText(Sort(List[Index2]), Sort(List[Index1]));
end;
function IsDerangement(word1, word2: string): Boolean;
var
i: Integer;
begin
for i := 1 to word1.Length do
if word1[i] = word2[i] then
exit(False);
Result := True;
end;
var
Dict: TStringList;
Count, Index: Integer;
words: string;
StopWatch: TStopwatch;
begin
StopWatch := TStopwatch.Create;
StopWatch.Start;
Dict := TStringList.Create();
Dict.LoadFromFile('unixdict.txt');
Dict.CustomSort(CompareLength);
Index := Dict.Count - 1;
words := '';
Count := 1;
while Index - Count >= 0 do
begin
if IsAnagram(Dict[Index], Dict[Index - Count]) then
begin
if IsDerangement(Dict[Index], Dict[Index - Count]) then
begin
words := Dict[Index] + ' - ' + Dict[Index - Count];
Break;
end;
Inc(Count);
end
else
begin
Dec(Index, Count);
Count := 1;
end;
end;
StopWatch.Stop;
Writeln(Format('Time pass: %d ms [i7-4500U Windows 7]', [StopWatch.ElapsedMilliseconds]));
writeln(#10'Longest derangement words are:'#10#10, words);
Dict.Free;
Readln;
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.
| #Delphi | Delphi |
program AnonymousRecursion;
{$APPTYPE CONSOLE}
uses
SysUtils;
function Fib(X: Integer): integer;
function DoFib(N: Integer): Integer;
begin
if N < 2 then Result:=N
else Result:=DoFib(N-1) + DoFib(N-2);
end;
begin
if X < 0 then raise Exception.Create('Argument < 0')
else Result:=DoFib(X);
end;
var I: integer;
begin
for I:=-1 to 15 do
begin
try
WriteLn(I:3,' - ',Fib(I):3);
except WriteLn(I,' - Error'); end;
end;
WriteLn('Hit Any Key');
ReadLn;
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
| #Go | Go | package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func d2d(d float64) float64 { return math.Mod(d, 360) }
func g2g(g float64) float64 { return math.Mod(g, 400) }
func m2m(m float64) float64 { return math.Mod(m, 6400) }
func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }
func d2g(d float64) float64 { return d2d(d) * 400 / 360 }
func d2m(d float64) float64 { return d2d(d) * 6400 / 360 }
func d2r(d float64) float64 { return d2d(d) * math.Pi / 180 }
func g2d(g float64) float64 { return g2g(g) * 360 / 400 }
func g2m(g float64) float64 { return g2g(g) * 6400 / 400 }
func g2r(g float64) float64 { return g2g(g) * math.Pi / 200 }
func m2d(m float64) float64 { return m2m(m) * 360 / 6400 }
func m2g(m float64) float64 { return m2m(m) * 400 / 6400 }
func m2r(m float64) float64 { return m2m(m) * math.Pi / 3200 }
func r2d(r float64) float64 { return r2r(r) * 180 / math.Pi }
func r2g(r float64) float64 { return r2r(r) * 200 / math.Pi }
func r2m(r float64) float64 { return r2r(r) * 3200 / math.Pi }
// Aligns number to decimal point assuming 7 characters before and after.
func s(f float64) string {
wf := strings.Split(strconv.FormatFloat(f, 'g', 15, 64), ".")
if len(wf) == 1 {
return fmt.Sprintf("%7s ", wf[0])
}
le := len(wf[1])
if le > 7 {
le = 7
}
return fmt.Sprintf("%7s.%-7s", wf[0], wf[1][:le])
}
func main() {
angles := []float64{-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795,
359, 399, 6399, 1000000}
ft := "%s %s %s %s %s\n"
fmt.Printf(ft, " degrees ", "normalized degs", " gradians ", " mils ", " radians")
for _, a := range angles {
fmt.Printf(ft, s(a), s(d2d(a)), s(d2g(a)), s(d2m(a)), s(d2r(a)))
}
fmt.Printf(ft, "\n gradians ", "normalized grds", " degrees ", " mils ", " radians")
for _, a := range angles {
fmt.Printf(ft, s(a), s(g2g(a)), s(g2d(a)), s(g2m(a)), s(g2r(a)))
}
fmt.Printf(ft, "\n mils ", "normalized mils", " degrees ", " gradians ", " radians")
for _, a := range angles {
fmt.Printf(ft, s(a), s(m2m(a)), s(m2d(a)), s(m2g(a)), s(m2r(a)))
}
fmt.Printf(ft, "\n radians ", "normalized rads", " degrees ", " gradians ", " mils ")
for _, a := range angles {
fmt.Printf(ft, s(a), s(r2r(a)), s(r2d(a)), s(r2g(a)), s(r2m(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.
| #BASIC256 | BASIC256 | function SumProperDivisors(number)
if number < 2 then return 0
sum = 0
for i = 1 to number \ 2
if number mod i = 0 then sum += i
next i
return sum
end function
dim sum(20000)
for n = 1 to 19999
sum[n] = SumProperDivisors(n)
next n
print "The pairs of amicable numbers below 20,000 are :"
print
for n = 1 to 19998
f = sum[n]
if f <= n or f < 1 or f > 19999 then continue for
if f = sum[n] and n = sum[f] then
print rjust(string(n), 5); " and "; sum[n]
end if
next n
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.
| #E | E | # State
var text := "Hello World! "
var leftward := false
# Window
def w := <swing:makeJFrame>("RC: Basic Animation")
# Text in window
w.setContentPane(def l := <swing:makeJLabel>(text))
l.setOpaque(true) # repaints badly if not set!
l.addMouseListener(def mouseListener {
to mouseClicked(_) {
leftward := !leftward
}
match _ {}
})
# Animation
def anim := timer.every(100, fn _ { # milliseconds
def s := text.size()
l.setText(text := if (leftward) {
text(1, s) + text(0, 1)
} else {
text(s - 1, s) + text(0, s - 1)
})
})
# Set up window shape and close behavior
w.pack()
w.setLocationRelativeTo(null)
w.addWindowListener(def windowListener {
to windowClosing(_) { anim.stop() }
match _ {}
})
# Start everything
w.show()
anim.start() |
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.
| #BASIC | BASIC | MODE 8
*FLOAT 64
VDU 23,23,4;0;0;0; : REM Set line thickness
theta = RAD(40) : REM initial displacement
g = 9.81 : REM acceleration due to gravity
l = 0.50 : REM length of pendulum in metres
REPEAT
PROCpendulum(theta, l)
WAIT 1
PROCpendulum(theta, l)
accel = - g * SIN(theta) / l / 100
speed += accel / 100
theta += speed
UNTIL FALSE
END
DEF PROCpendulum(a, l)
LOCAL pivotX, pivotY, bobX, bobY
pivotX = 640
pivotY = 800
bobX = pivotX + l * 1000 * SIN(a)
bobY = pivotY - l * 1000 * COS(a)
GCOL 3,6
LINE pivotX, pivotY, bobX, bobY
GCOL 3,11
CIRCLE FILL bobX + 24 * SIN(a), bobY - 24 * COS(a), 24
ENDPROC |
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
| #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
void processFile(char* name){
int i,records;
double diff,b1,b2;
FILE* fp = fopen(name,"r");
fscanf(fp,"%d\n",&records);
for(i=0;i<records;i++){
fscanf(fp,"%lf%lf",&b1,&b2);
diff = fmod(b2-b1,360.0);
printf("\nDifference between b2(%lf) and b1(%lf) is %lf",b2,b1,(diff<-180)?diff+360:((diff>=180)?diff-360:diff));
}
fclose(fp);
}
int main(int argC,char* argV[])
{
double diff;
if(argC < 2)
printf("Usage : %s <bearings separated by a space OR full file name which contains the bearing list>",argV[0]);
else if(argC == 2)
processFile(argV[1]);
else{
diff = fmod(atof(argV[2])-atof(argV[1]),360.0);
printf("Difference between b2(%s) and b1(%s) is %lf",argV[2],argV[1],(diff<-180)?diff+360:((diff>=180)?diff-360:diff));
}
return 0;
}
|
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
| #EchoLisp | EchoLisp | (lib 'hash)
(lib 'struct)
(lib 'sql)
(lib 'words)
(define H (make-hash))
(define (deranged w1 w2)
(for ((a w1) (b w2))
#:break (string=? a b) => #f
#t))
(define (anagrams (normal) (name) (twins))
(for ((w *words*))
(set! name (word-name w))
(set! normal (list->string (list-sort string<? (string->list name))))
(set! twins (or (hash-ref H normal) null))
#:continue (member name twins)
#:when (or (null? twins) (for/or ((anagram twins)) (deranged name anagram)))
(hash-set H normal (cons name twins))))
(define (task (lmin 8))
(anagrams)
(for ((lw (hash-values H))) ;; lw = list of words
#:continue (= (length lw) 1)
#:continue (< (string-length (first lw)) lmin)
(set! lmin (string-length (first lw)))
(write lmin) (for-each write lw)
(writeln)))
|
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.
| #EchoLisp | EchoLisp |
(define (fib n)
(let _fib ((a 1) (b 1) (n n))
(if
(<= n 1) a
(_fib b (+ a b) (1- 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
| #Groovy | Groovy | import java.lang.reflect.Constructor
abstract class Angle implements Comparable<? extends Angle> {
double value
Angle(double value = 0) { this.value = normalize(value) }
abstract Number unitCircle()
abstract String unitName()
Number normalize(double n) { n % this.unitCircle() }
def <B extends Angle> B asType(Class<B> bClass){
if (bClass == this.class) return this
bClass.getConstructor(Number.class).newInstance(0).tap {
value = this.value * unitCircle() / this.unitCircle()
}
}
String toString() {
"${String.format('%14.8f',value)}${this.unitName()}"
}
int hashCode() {
value.hashCode() + 17 * unit().hashCode()
}
int compareTo(Angle that) {
this.value * that.unitCircle() <=> that.value * this.unitCircle()
}
boolean equals(that) {
this.is(that) ? true
: that instanceof Angle ? (this <=> that) == 0
: that instanceof Number ? this.value == this.normalize(that)
: super.equals(that)
}
}
class Degrees extends Angle {
static final int UNIT_CIRCLE = 360
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = "º "
String unitName() { UNIT }
Degrees(Number value = 0) { super(value) }
}
class Gradians extends Angle {
static final int UNIT_CIRCLE = 400
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = " grad"
String unitName() { UNIT }
Gradians(Number value = 0) { super(value) }
}
class Mils extends Angle {
static final int UNIT_CIRCLE = 6400
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = " mil "
String unitName() { UNIT }
Mils(Number value = 0) { super(value) }
}
class Radians extends Angle {
static final double UNIT_CIRCLE = Math.PI*2
Number unitCircle() { UNIT_CIRCLE }
static final String UNIT = " rad "
String unitName() { UNIT }
Radians(Number value = 0) { super(value) }
} |
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.
| #BCPL | BCPL | get "libhdr"
manifest $(
MAXIMUM = 20000
$)
// Calculate proper divisors for 1..N
let propDivSums(n) = valof
$( let v = getvec(n)
for i = 1 to n do v!i := 1
for i = 2 to n/2 do
$( let j = i*2
while j < n do
$( v!j := v!j + i
j := j + i
$)
$)
resultis v
$)
// Are A and B an amicable pair, given the list of sums of proper divisors?
let amicable(pdiv, a, b) = a = pdiv!b & b = pdiv!a
let start() be
$( let pds = propDivSums(MAXIMUM)
for x = 1 to MAXIMUM do
for y = x+1 to MAXIMUM do
if amicable(pds, x, y) do
writef("%N, %N*N", x, y)
$) |
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.
| #Elm | Elm | module Main exposing (..)
import Browser
import Html exposing (Html, div, pre, text)
import Html.Events exposing (onClick)
import Time
message : String
message =
"Hello World! "
main : Program () Model Msg
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type Direction
= Forwards
| Backwards
type alias Model =
{ time : Int
, direction : Direction
}
init : () -> ( Model, Cmd Msg )
init _ =
( { time = 0, direction = Forwards }, Cmd.none )
-- UPDATE
type Msg
= Tick
| SwitchDirection
switchDirection : Direction -> Direction
switchDirection d =
case d of
Forwards ->
Backwards
Backwards ->
Forwards
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
nextTime =
case model.direction of
Forwards ->
model.time - 1
Backwards ->
model.time + 1
in
case msg of
Tick ->
( { model | time = modBy (String.length message) nextTime }, Cmd.none )
SwitchDirection ->
( { model | direction = switchDirection model.direction }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Time.every 200 (\_ -> Tick)
-- VIEW
rotate : String -> Int -> String
rotate m x =
let
end =
String.slice x (String.length m) m
beginning =
String.slice 0 x m
in
end ++ beginning
view : Model -> Html Msg
view model =
div []
[ pre [ onClick SwitchDirection ]
[ text <| rotate message model.time ]
]
|
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.
| #F.23 | F# | open System.Windows
let str = "Hello world! "
let mutable i = 0
let mutable d = 1
[<System.STAThread>]
do
let button = Controls.Button()
button.Click.Add(fun _ -> d <- str.Length - d)
let update _ =
i <- (i + d) % str.Length
button.Content <- str.[i..] + str.[..i-1]
Media.CompositionTarget.Rendering.Add update
(Application()).Run(Window(Content=button)) |> ignore |
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.
| #C | C | #include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>
#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
/* don't let precision error go out of hand */
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow("Pendulum");
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
} |
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
| #C.23 | C# | using System;
namespace Angle_difference_between_two_bearings
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine("Hello World!");
Console.WriteLine();
// Calculate standard test cases
Console.WriteLine(Delta_Bearing( 20M,45));
Console.WriteLine(Delta_Bearing(-45M,45M));
Console.WriteLine(Delta_Bearing(-85M,90M));
Console.WriteLine(Delta_Bearing(-95M,90M));
Console.WriteLine(Delta_Bearing(-45M,125M));
Console.WriteLine(Delta_Bearing(-45M,145M));
Console.WriteLine(Delta_Bearing( 29.4803M,-88.6381M));
Console.WriteLine(Delta_Bearing(-78.3251M, -159.036M));
// Calculate optional test cases
Console.WriteLine(Delta_Bearing(-70099.74233810938M, 29840.67437876723M));
Console.WriteLine(Delta_Bearing(-165313.6666297357M, 33693.9894517456M));
Console.WriteLine(Delta_Bearing( 1174.8380510598456M, -154146.66490124757M));
Console.WriteLine(Delta_Bearing( 60175.77306795546M, 42213.07192354373M));
Console.WriteLine();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
static decimal Delta_Bearing(decimal b1, decimal b2)
{
/*
* Optimal solution
*
decimal d = 0;
d = (b2-b1)%360;
if(d>180)
d -= 360;
else if(d<-180)
d += 360;
return d;
*
*
*/
//
//
//
decimal d = 0;
// Convert bearing to W.C.B
if(b1<0)
b1 += 360;
if(b2<0)
b2 += 360;
///Calculate delta bearing
//and
//Convert result value to Q.B.
d = (b2 - b1)%360;
if(d>180)
d -= 360;
else if(d<-180)
d += 360;
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
| #Eiffel | Eiffel | class
ANAGRAMS_DERANGED
create
make
feature
make
-- Longest deranged anagram.
local
deranged_anagrams: LINKED_LIST [STRING]
count: INTEGER
do
read_wordlist
across
words as wo
loop
deranged_anagrams := check_list_for_deranged (wo.item)
if not deranged_anagrams.is_empty and deranged_anagrams [1].count > count then
count := deranged_anagrams [1].count
end
wo.item.wipe_out
wo.item.append (deranged_anagrams)
end
across
words as wo
loop
across
wo.item as w
loop
if w.item.count = count then
io.put_string (w.item + "%T")
io.new_line
end
end
end
end
original_list: STRING = "unixdict.txt"
feature {NONE}
check_list_for_deranged (list: LINKED_LIST [STRING]): LINKED_LIST [STRING]
-- Deranged anagrams in 'list'.
do
create Result.make
across
1 |..| list.count as i
loop
across
(i.item + 1) |..| list.count as j
loop
if check_for_deranged (list [i.item], list [j.item]) then
Result.extend (list [i.item])
Result.extend (list [j.item])
end
end
end
end
check_for_deranged (a, b: STRING): BOOLEAN
-- Are 'a' and 'b' deranged anagrams?
local
n: INTEGER
do
across
1 |..| a.count as i
loop
if a [i.item] = b [i.item] then
n := n + 1
end
end
Result := n = 0
end
read_wordlist
-- Hashtable 'words' with alphabetically sorted Strings used as key.
local
l_file: PLAIN_TEXT_FILE
sorted: STRING
empty_list: LINKED_LIST [STRING]
do
create l_file.make_open_read_write (original_list)
l_file.read_stream (l_file.count)
wordlist := l_file.last_string.split ('%N')
l_file.close
create words.make (wordlist.count)
across
wordlist as w
loop
create empty_list.make
sorted := sort_letters (w.item)
words.put (empty_list, sorted)
if attached words.at (sorted) as ana then
ana.extend (w.item)
end
end
end
wordlist: LIST [STRING]
sort_letters (word: STRING): STRING
--Alphabetically sorted.
local
letters: SORTED_TWO_WAY_LIST [STRING]
do
create letters.make
create Result.make_empty
across
1 |..| word.count as i
loop
letters.extend (word.at (i.item).out)
end
across
letters as s
loop
Result.append (s.item)
end
end
words: HASH_TABLE [LINKED_LIST [STRING], STRING]
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.
| #Ela | Ela | fib n | n < 0 = fail "Negative n"
| else = fix (\f n -> if n < 2 then n else f (n - 1) + f (n - 2)) 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
| #Haskell | Haskell | {-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Text.Printf
class (Num a, Fractional a, RealFrac a) => Angle a where
fullTurn :: a -- value of the whole turn
mkAngle :: Double -> a
value :: a -> Double
fromTurn :: Double -> a
toTurn :: a -> Double
normalize :: a -> a
-- conversion of angles to rotations in linear case
fromTurn t = angle t * fullTurn
toTurn a = value $ a / fullTurn
-- normalizer for linear angular unit
normalize a = a `modulo` fullTurn
where
modulo x r | x == r = r
| x < 0 = signum x * abs x `modulo` r
| x >= 0 = x - fromInteger (floor (x / r)) * r
-- smart constructor
angle :: Angle a => Double -> a
angle = normalize . mkAngle
-- Two transformers differ only in the order of type application.
from :: forall a b. (Angle a, Angle b) => a -> b
from = fromTurn . toTurn
to :: forall b a. (Angle a, Angle b) => a -> b
to = fromTurn . toTurn |
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.
| #Befunge | Befunge | v_@#-*8*:"2":$_:#!2#*8#g*#6:#0*#!:#-*#<v>*/.55+,
1>$$:28*:*:*%\28*:*:*/`06p28*:*:*/\2v %%^:*:<>*v
+|!:-1g60/*:*:*82::+**:*:<<>:#**#8:#<*^>.28*^8 :
:v>>*:*%/\28*:*:*%+\v>8+#$^#_+#`\:#0<:\`1/*:*2#<
2v^:*82\/*:*:*82:::_v#!%%*:*:*82\/*:*:*82::<_^#<
>>06p:28*:*:**1+01-\>1+::28*:*:*/\28*:*:*%:*\`!^ |
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.
| #Factor | Factor | USING: accessors timers calendar kernel models sequences ui
ui.gadgets ui.gadgets.labels ui.gestures ;
FROM: models => change-model ;
IN: rosetta.animation
CONSTANT: sentence "Hello World! "
TUPLE: animated-label < label-control reversed alarm ;
: <animated-label> ( model -- <animated-model> )
sentence animated-label new-label swap >>model
monospace-font >>font ;
: update-string ( str reverse -- str )
[ unclip-last prefix ] [ unclip suffix ] if ;
: update-model ( model reversed? -- )
[ update-string ] curry change-model ;
animated-label
H{
{ T{ button-down } [ [ not ] change-reversed drop ] }
} set-gestures
M: animated-label graft*
[ [ [ model>> ] [ reversed>> ] bi update-model ] curry 400 milliseconds every ] keep
alarm<< ;
M: animated-label ungraft*
alarm>> stop-timer ;
: main ( -- )
[ sentence <model> <animated-label> "Rosetta" open-window ] with-ui ;
MAIN: main |
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.
| #Fantom | Fantom |
using concurrent
using fwt
using gfx
const class RotateString : Actor
{
new make (Label label) : super (ActorPool ())
{
Actor.locals["rotate-label"] = label
Actor.locals["rotate-string"] = label.text
Actor.locals["direction"] = "forward"
sendLater (1sec, "update")
}
// responsible for calling appropriate methods to process each message
override Obj? receive (Obj? msg)
{
switch (msg)
{
case "update":
Desktop.callAsync |->| { update } // make sure we update GUI in event thread
sendLater (1sec, "update")
case "reverse":
Desktop.callAsync |->| { reverse }
}
return null
}
// change the stored string indicating the direction to rotate
Void reverse ()
{
Actor.locals["direction"] =
(Actor.locals["direction"] == "forward" ? "backward" : "forward")
}
// update the text on the label according to the stored direction
Void update ()
{
label := Actor.locals["rotate-label"] as Label
str := Actor.locals["rotate-string"] as Str
if (label != null)
{
newStr := ""
if (Actor.locals["direction"] == "forward")
newStr = str[1..-1] + str[0].toChar
else
newStr = str[-1].toChar + str[0..<-1]
label.text = newStr
Actor.locals["rotate-string"] = newStr
}
}
}
class Animate
{
public static Void main ()
{
label := Label
{
text = "Hello world! "
halign = Halign.center
}
ticker := RotateString (label)
label.onMouseDown.add |Event e|
{
ticker.send ("reverse")
}
Window
{
title = "Animate"
label,
}.open
}
}
|
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.
| #C.23 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
class CSharpPendulum
{
Form _form;
Timer _timer;
double _angle = Math.PI / 2,
_angleAccel,
_angleVelocity = 0,
_dt = 0.1;
int _length = 50;
[STAThread]
static void Main()
{
var p = new CSharpPendulum();
}
public CSharpPendulum()
{
_form = new Form() { Text = "Pendulum", Width = 200, Height = 200 };
_timer = new Timer() { Interval = 30 };
_timer.Tick += delegate(object sender, EventArgs e)
{
int anchorX = (_form.Width / 2) - 12,
anchorY = _form.Height / 4,
ballX = anchorX + (int)(Math.Sin(_angle) * _length),
ballY = anchorY + (int)(Math.Cos(_angle) * _length);
_angleAccel = -9.81 / _length * Math.Sin(_angle);
_angleVelocity += _angleAccel * _dt;
_angle += _angleVelocity * _dt;
Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);
Graphics g = Graphics.FromImage(dblBuffer);
Graphics f = Graphics.FromHwnd(_form.Handle);
g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));
g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);
g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);
f.Clear(Color.White);
f.DrawImage(dblBuffer, new Point(0, 0));
};
_timer.Start();
Application.Run(_form);
}
}
|
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
| #C.2B.2B | C++ | #include <cmath>
#include <iostream>
using namespace std;
double getDifference(double b1, double b2) {
double r = fmod(b2 - b1, 360.0);
if (r < -180.0)
r += 360.0;
if (r >= 180.0)
r -= 360.0;
return r;
}
int main()
{
cout << "Input in -180 to +180 range" << endl;
cout << getDifference(20.0, 45.0) << endl;
cout << getDifference(-45.0, 45.0) << endl;
cout << getDifference(-85.0, 90.0) << endl;
cout << getDifference(-95.0, 90.0) << endl;
cout << getDifference(-45.0, 125.0) << endl;
cout << getDifference(-45.0, 145.0) << endl;
cout << getDifference(-45.0, 125.0) << endl;
cout << getDifference(-45.0, 145.0) << endl;
cout << getDifference(29.4803, -88.6381) << endl;
cout << getDifference(-78.3251, -159.036) << endl;
cout << "Input in wider range" << endl;
cout << getDifference(-70099.74233810938, 29840.67437876723) << endl;
cout << getDifference(-165313.6666297357, 33693.9894517456) << endl;
cout << getDifference(1174.8380510598456, -154146.66490124757) << endl;
cout << getDifference(60175.77306795546, 42213.07192354373) << endl;
return 0;
} |
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
| #Elixir | Elixir | defmodule Anagrams do
def deranged(fname) do
File.read!(fname)
|> String.split
|> Enum.map(fn word -> to_charlist(word) end)
|> Enum.group_by(fn word -> Enum.sort(word) end)
|> Enum.filter(fn {_,words} -> length(words) > 1 end)
|> Enum.sort_by(fn {key,_} -> -length(key) end)
|> Enum.find(fn {_,words} -> find_derangements(words) end)
end
defp find_derangements(words) do
comb(words,2) |> Enum.find(fn [a,b] -> deranged?(a,b) end)
end
defp deranged?(a,b) do
Enum.zip(a, b) |> Enum.all?(fn {chr_a,chr_b} -> chr_a != chr_b end)
end
defp comb(_, 0), do: [[]]
defp comb([], _), do: []
defp comb([h|t], m) do
(for l <- comb(t, m-1), do: [h|l]) ++ comb(t, m)
end
end
case Anagrams.deranged("/work/unixdict.txt") do
{_, words} -> IO.puts "Longest derangement anagram: #{inspect words}"
_ -> IO.puts "derangement anagram: nothing"
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.
| #Elena | Elena | import extensions;
fib(n)
{
if (n < 0)
{ InvalidArgumentException.raise() };
^ (n)
{
if (n > 1)
{
^ this self(n - 2) + (this self(n - 1))
}
else
{
^ n
}
}(n)
}
public program()
{
for (int i := -1, i <= 10, i += 1)
{
console.print("fib(",i,")=");
try
{
console.printLine(fib(i))
}
catch(Exception e)
{
console.printLine:"invalid"
}
};
console.readChar()
} |
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
| #J | J |
TAU =: 2p1 NB. tauday.com
normalize =: * * 1 | | NB. signum times the fractional part of absolute value
TurnTo=: &*
as_turn =: 1 TurnTo
as_degree =: 360 TurnTo
as_gradian =: 400 TurnTo
as_mil =: 6400 TurnTo
as_radian =: TAU TurnTo
Turn =: adverb def 'normalize as_turn inv m'
Degree =: adverb def 'normalize as_degree inv m'
Gradian =: adverb def 'normalize as_gradian inv m'
Mil =: adverb def 'normalize as_mil inv m'
Radian =: adverb def 'normalize as_radian inv 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º
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
| #Java | Java | import java.text.DecimalFormat;
// Title: Angles (geometric), normalization and conversion
public class AnglesNormalizationAndConversion {
public static void main(String[] args) {
DecimalFormat formatAngle = new DecimalFormat("######0.000000");
DecimalFormat formatConv = new DecimalFormat("###0.0000");
System.out.printf(" degrees gradiens mils radians%n");
for ( double angle : new double[] {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000} ) {
for ( String units : new String[] {"degrees", "gradiens", "mils", "radians"}) {
double d = 0, g = 0, m = 0, r = 0;
switch (units) {
case "degrees":
d = d2d(angle);
g = d2g(d);
m = d2m(d);
r = d2r(d);
break;
case "gradiens":
g = g2g(angle);
d = g2d(g);
m = g2m(g);
r = g2r(g);
break;
case "mils":
m = m2m(angle);
d = m2d(m);
g = m2g(m);
r = m2r(m);
break;
case "radians":
r = r2r(angle);
d = r2d(r);
g = r2g(r);
m = r2m(r);
break;
}
System.out.printf("%15s %8s = %10s %10s %10s %10s%n", formatAngle.format(angle), units, formatConv.format(d), formatConv.format(g), formatConv.format(m), formatConv.format(r));
}
}
}
private static final double DEGREE = 360D;
private static final double GRADIAN = 400D;
private static final double MIL = 6400D;
private static final double RADIAN = (2 * Math.PI);
private static double d2d(double a) {
return a % DEGREE;
}
private static double d2g(double a) {
return a * (GRADIAN / DEGREE);
}
private static double d2m(double a) {
return a * (MIL / DEGREE);
}
private static double d2r(double a) {
return a * (RADIAN / 360);
}
private static double g2d(double a) {
return a * (DEGREE / GRADIAN);
}
private static double g2g(double a) {
return a % GRADIAN;
}
private static double g2m(double a) {
return a * (MIL / GRADIAN);
}
private static double g2r(double a) {
return a * (RADIAN / GRADIAN);
}
private static double m2d(double a) {
return a * (DEGREE / MIL);
}
private static double m2g(double a) {
return a * (GRADIAN / MIL);
}
private static double m2m(double a) {
return a % MIL;
}
private static double m2r(double a) {
return a * (RADIAN / MIL);
}
private static double r2d(double a) {
return a * (DEGREE / RADIAN);
}
private static double r2g(double a) {
return a * (GRADIAN / RADIAN);
}
private static double r2m(double a) {
return a * (MIL / RADIAN);
}
private static double r2r(double a) {
return a % RADIAN;
}
} |
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.
| #C | C | #include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint;
int main(int argc, char **argv)
{
uint top = atoi(argv[1]);
uint *divsum = malloc((top + 1) * sizeof(*divsum));
uint pows[32] = {1, 0};
for (uint i = 0; i <= top; i++) divsum[i] = 1;
// sieve
// only sieve within lower half , the modification starts at 2*p
for (uint p = 2; p+p <= top; p++) {
if (divsum[p] > 1) {
divsum[p] -= p;// subtract number itself from divisor sum ('proper')
continue;} // p not prime
uint x; // highest power of p we need
//checking x <= top/y instead of x*y <= top to avoid overflow
for (x = 1; pows[x - 1] <= top/p; x++)
pows[x] = p*pows[x - 1];
//counter where n is not a*p with a = ?*p, useful for most p.
//think of p>31 seldom divisions or p>sqrt(top) than no division is needed
//n = 2*p, so the prime itself is left unchanged => k=p-1
uint k= p-1;
for (uint n = p+p; n <= top; n += p) {
uint s=1+pows[1];
k--;
// search the right power only if needed
if ( k==0) {
for (uint i = 2; i < x && !(n%pows[i]); s += pows[i++]);
k = p; }
divsum[n] *= s;
}
}
//now correct the upper half
for (uint p = (top >> 1)+1; p <= top; p++) {
if (divsum[p] > 1){
divsum[p] -= p;}
}
uint cnt = 0;
for (uint a = 1; a <= top; a++) {
uint b = divsum[a];
if (b > a && b <= top && divsum[b] == a){
printf("%u %u\n", a, b);
cnt++;}
}
printf("\nTop %u count : %u\n",top,cnt);
return 0;
} |
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.
| #FBSL | FBSL | #INCLUDE <Include\Windows.inc>
FBSLSETTEXT(ME, "Hello world! ")
RESIZE(ME, 0, 0, 220, 0)
CENTER(ME)
SHOW(ME)
SetTimer(ME, 1000, 100, NULL)
BEGIN EVENTS
STATIC bForward AS BOOLEAN = TRUE
IF CBMSG = WM_TIMER THEN
Marquee(bForward)
RETURN 0
ELSEIF CBMSG = WM_NCLBUTTONDOWN THEN
IF CBWPARAM = HTCAPTION THEN bForward = NOT bForward
ELSEIF CBMSG = WM_CLOSE THEN
KillTimer(ME, 1000)
END IF
END EVENTS
SUB Marquee(BYVAL forward AS BOOLEAN)
STATIC caption AS STRING = FBSLGETTEXT(ME)
STATIC length AS INTEGER = STRLEN(caption)
IF forward THEN
caption = RIGHT(caption, 1) & LEFT(caption, length - 1)
ELSE
caption = MID(caption, 2) & LEFT(caption, 1)
END IF
FBSLSETTEXT(ME, caption)
END SUB |
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.
| #C.2B.2B | C++ |
#ifndef __wxPendulumDlg_h__
#define __wxPendulumDlg_h__
// ---------------------
/// @author Martin Ettl
/// @date 2013-02-03
// ---------------------
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/dialog.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/timer.h>
#include <wx/dcbuffer.h>
#include <cmath>
class wxPendulumDlgApp : public wxApp
{
public:
bool OnInit();
int OnExit();
};
class wxPendulumDlg : public wxDialog
{
public:
wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"),
const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);
virtual ~wxPendulumDlg();
// Event handler
void wxPendulumDlgPaint(wxPaintEvent& event);
void wxPendulumDlgSize(wxSizeEvent& event);
void OnTimer(wxTimerEvent& event);
private:
// a pointer to a timer object
wxTimer *m_timer;
unsigned int m_uiLength;
double m_Angle;
double m_AngleVelocity;
enum wxIDs
{
ID_WXTIMER1 = 1001,
ID_DUMMY_VALUE_
};
void OnClose(wxCloseEvent& event);
void CreateGUIControls();
DECLARE_EVENT_TABLE()
};
#endif // __wxPendulumDlg_h__
|
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
| #Clojure | Clojure | (defn angle-difference [a b]
(let [r (mod (- b a) 360)]
(if (>= r 180)
(- r 360)
r)))
(angle-difference 20 45) ; 25
(angle-difference -45 45) ; 90
(angle-difference -85 90) ; 175
(angle-difference -95 90) ; -175
(angle-difference -70099.74 29840.67) ; -139.59
|
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
| #Erlang | Erlang | -module( anagrams_deranged ).
-export( [task/0, words_from_url/1] ).
task() ->
find_unimplemented_tasks:init_http(),
Words = words_from_url( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" ),
Anagram_dict = anagrams:fetch( Words, dict:new() ),
Deranged_anagrams = deranged_anagrams( Anagram_dict ),
{_Length, Longest_anagrams} = dict:fold( fun keep_longest/3, {0, []}, Deranged_anagrams ),
Longest_anagrams.
words_from_url( URL ) ->
{ok, {{_HTTP, 200, "OK"}, _Headers, Body}} = httpc:request( URL ),
string:tokens( Body, "\n" ).
deranged_anagrams( Dict ) ->
Deranged_dict = dict:map( fun deranged_words/2, Dict ),
dict:filter( fun is_anagram/2, Deranged_dict ).
deranged_words( _Key, [H | T] ) ->
[{H, X} || X <- T, is_deranged_word(H, X)].
keep_longest( _Key, [{One, _} | _]=New, {Length, Acc} ) ->
keep_longest_new( erlang:length(One), Length, New, Acc ).
keep_longest_new( New_length, Acc_length, New, _Acc ) when New_length > Acc_length ->
{New_length, New};
keep_longest_new( New_length, Acc_length, New, Acc ) when New_length =:= Acc_length ->
{Acc_length, Acc ++ New};
keep_longest_new( _New_length, Acc_length, _New, Acc ) ->
{Acc_length, Acc}.
is_anagram( _Key, [] ) -> false;
is_anagram( _Key, _Value ) -> true.
is_deranged_word( Word1, Word2 ) ->
lists:all( fun is_deranged_char/1, lists:zip(Word1, Word2) ).
is_deranged_char( {One, Two} ) -> One =/= Two. |
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.
| #Elixir | Elixir |
fib = fn f -> (
fn x -> if x == 0, do: 0, else: (if x == 1, do: 1, else: f.(x - 1) + f.(x - 2)) end
)
end
y = fn x -> (
fn f -> f.(f)
end).(
fn g -> x.(fn z ->(g.(g)).(z) end)
end)
end
IO.inspect y.(&(fib.(&1))).(40)
|
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
| #JavaScript | JavaScript |
/*****************************************************************\
| Expects an angle, an origin unit and a unit to convert to, |
| where in/out units are: |
| --------------------------------------------------------------- |
| 'D'/'d' ..... degrees 'M'/'d' ..... mils | |
| 'G'/'g' ..... gradians 'R'/'r' ..... radians |
| --------------------------------------------------------------- |
| example: convert 150 degrees to radians: |
| angleConv(150, 'd', 'r') |
\*****************************************************************/
function angleConv(deg, inp, out) {
inp = inp.toLowerCase();
out = out.toLowerCase();
const D = 360,
G = 400,
M = 6400,
R = 2 * Math.PI;
// normalazation
let minus = (deg < 0); // boolean
deg = Math.abs(deg);
switch (inp) {
case 'd': deg %= D; break;
case 'g': deg %= G; break;
case 'm': deg %= M; break;
case 'r': deg %= R;
}
// we use an internal conversion to Turns (full circle) here
let t;
switch (inp) {
case 'd': t = deg / D; break;
case 'g': t = deg / G; break;
case 'm': t = deg / M; break;
case 'r': t = deg / R;
}
// converting
switch (out) {
case 'd': t *= D; break;
case 'g': t *= G; break;
case 'm': t *= M; break;
case 'r': t *= R;
}
if (minus) return 0 - t;
return t;
}
// mass testing
let nums = [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1e6],
units = 'dgmr'.split(''),
x, y, z;
for (x = 0; x < nums.length; x++) {
for (y = 0; y < units.length; y++) {
document.write(`
<p>
<b>${nums[x]}<sub>${units[y]}</sub></b><br>
`);
for (z = 0; z < units.length; z++)
document.write(`
= ${angleConv(nums[x], units[y], units[z])}<sub>${units[z]}</sub>
`);
}
}
|
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace RosettaCode.AmicablePairs
{
internal static class Program {
private const int Limit = 20000;
private static void Main()
{
foreach (var pair in GetPairs(Limit))
{
Console.WriteLine("{0} {1}", pair.Item1, pair.Item2);
}
}
private static IEnumerable<Tuple<int, int>> GetPairs(int max)
{
List<int> divsums =
Enumerable.Range(0, max + 1).Select(i => ProperDivisors(i).Sum()).ToList();
for(int i=1; i<divsums.Count; i++) {
int sum = divsums[i];
if(i < sum && sum <= divsums.Count && divsums[sum] == i) {
yield return new Tuple<int, int>(i, sum);
}
}
}
private static IEnumerable<int> ProperDivisors(int number)
{
return
Enumerable.Range(1, number / 2)
.Where(divisor => number % divisor == 0);
}
}
} |
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.
| #FreeBASIC | FreeBASIC | DIM C AS STRING = "Hello World! ", SIZE AS USHORT = LEN(C)
DIM DIRECTION AS BYTE = 0
DIM AS INTEGER X, Y, BTNS
DIM HELD AS BYTE = 0
SCREEN 19
DO
LOCATE 1, 1
PRINT C
GETMOUSE X, Y, , BTNS
IF BTNS <> 0 AND HELD = 0 THEN
'remember if it was pressed, to not react every frame
HELD = 1
IF X >= 0 AND X < SIZE * 8 AND Y >= 0 AND Y < 16 THEN
DIRECTION = 1 - DIRECTION
END IF
ELSE
HELD = 0
END IF
IF INKEY = CHR(255) + CHR(107) THEN EXIT DO
IF DIRECTION = 0 THEN
C = RIGHT(C, 1) + LEFT(C, SIZE - 1)
ELSE
C = RIGHT(C, SIZE - 1) + LEFT(C, 1)
END IF
SLEEP 100, 1
LOOP |
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.
| #Clojure | Clojure |
(ns pendulum
(:import
(javax.swing JFrame)
(java.awt Canvas Graphics Color)))
(def length 200)
(def width (* 2 (+ 50 length)))
(def height (* 3 (/ length 2)))
(def dt 0.1)
(def g 9.812)
(def k (- (/ g length)))
(def anchor-x (/ width 2))
(def anchor-y (/ height 8))
(def angle (atom (/ (Math/PI) 2)))
(defn draw [#^Canvas canvas angle]
(let [buffer (.getBufferStrategy canvas)
g (.getDrawGraphics buffer)
ball-x (+ anchor-x (* (Math/sin angle) length))
ball-y (+ anchor-y (* (Math/cos angle) length))]
(try
(doto g
(.setColor Color/BLACK)
(.fillRect 0 0 width height)
(.setColor Color/RED)
(.drawLine anchor-x anchor-y ball-x ball-y)
(.setColor Color/YELLOW)
(.fillOval (- anchor-x 3) (- anchor-y 4) 7 7)
(.fillOval (- ball-x 7) (- ball-y 7) 14 14))
(finally (.dispose g)))
(if-not (.contentsLost buffer)
(.show buffer)) ))
(defn start-renderer [canvas]
(->>
(fn [] (draw canvas @angle) (recur))
(new Thread)
(.start)))
(defn -main [& args]
(let [frame (JFrame. "Pendulum")
canvas (Canvas.)]
(doto frame
(.setSize width height)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setResizable false)
(.add canvas)
(.setVisible true))
(doto canvas
(.createBufferStrategy 2)
(.setVisible true)
(.requestFocus))
(start-renderer canvas)
(loop [v 0]
(swap! angle #(+ % (* v dt)))
(Thread/sleep 15)
(recur (+ v (* k (Math/sin @angle) dt)))) ))
(-main)
|
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
| #COBOL | COBOL |
******************************************************************
* COBOL solution to Angle difference challange
* The program was run on OpenCobolIDE
* I chose to read the input data from a .txt file that I
* created on my PC rather than to hard code it into the
* program or enter it as the program was executing.
******************************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. ANGLE-DIFFERENCE.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT IN-FILE ASSIGN TO 'C:\Both\Rosetta\Angle_diff.txt'
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD IN-FILE.
01 IN-RECORD.
05 ALPHA-BEARING-1 PIC X(20).
05 FILLER PIC X.
05 ALPHA-BEARING-2 PIC X(20).
WORKING-STORAGE SECTION.
01 SWITCHES.
05 EOF-SWITCH PIC X VALUE 'N'.
01 COUNTERS.
05 REC-CTR PIC 9(3) VALUE 0.
01 WS-ALPHA-BEARING.
05 WS-AB-SIGN PIC X.
88 WS-AB-NEGATIVE VALUE "-".
05 WS-AB-INTEGER-PART PIC X(6).
05 WS-AB-DEC-POINT PIC X.
05 WS-AB-DECIMAL-PART PIC X(12).
01 WS-BEARING-1 PIC S9(6)V9(12).
01 WS-BEARING-2 PIC S9(6)V9(12).
01 WS-BEARING PIC S9(6)V9(12).
01 FILLER REDEFINES WS-BEARING.
05 WSB-INTEGER-PART PIC X(6).
05 WSB-DECIMAL-PART PIC X9(12).
77 WS-RESULT PIC S9(6)V9(12).
77 WS-RESULT-POS PIC 9(6)V9(12).
77 WS-INTEGER-PART PIC 9(6).
77 WS-DECIMAL-PART PIC V9(12).
77 WS-RESULT-OUT PIC ------9.9999.
PROCEDURE DIVISION.
000-MAIN.
PERFORM 100-INITIALIZE.
PERFORM 200-PROCESS-RECORD
UNTIL EOF-SWITCH = 'Y'.
PERFORM 300-TERMINATE.
STOP RUN.
100-INITIALIZE.
OPEN INPUT IN-FILE.
PERFORM 150-READ-RECORD.
150-READ-RECORD.
READ IN-FILE
AT END
MOVE 'Y' TO EOF-SWITCH
NOT AT END
COMPUTE REC-CTR = REC-CTR + 1
END-READ.
200-PROCESS-RECORD.
MOVE ALPHA-BEARING-1 TO WS-ALPHA-BEARING.
PERFORM 250-CONVERT-DATA.
MOVE WS-BEARING TO WS-BEARING-1.
MOVE ALPHA-BEARING-2 TO WS-ALPHA-BEARING.
PERFORM 250-CONVERT-DATA.
MOVE WS-BEARING TO WS-BEARING-2.
COMPUTE WS-RESULT = WS-BEARING-2 - WS-BEARING-1.
MOVE WS-RESULT TO WS-RESULT-POS.
MOVE WS-RESULT-POS TO WS-INTEGER-PART.
COMPUTE WS-DECIMAL-PART = WS-RESULT-POS - WS-INTEGER-PART.
COMPUTE WS-INTEGER-PART = FUNCTION MOD(WS-INTEGER-PART 360).
IF WS-RESULT > 0
COMPUTE WS-RESULT = WS-INTEGER-PART + WS-DECIMAL-PART
ELSE
COMPUTE WS-RESULT =
(WS-INTEGER-PART + WS-DECIMAL-PART) * -1
END-IF.
IF WS-RESULT < -180
COMPUTE WS-RESULT = WS-RESULT + 360.
IF WS-RESULT > 180
COMPUTE WS-RESULT = WS-RESULT - 360.
COMPUTE WS-RESULT-OUT ROUNDED = WS-RESULT.
DISPLAY REC-CTR ' ' WS-RESULT-OUT.
PERFORM 150-READ-RECORD.
250-CONVERT-DATA.
MOVE WS-AB-INTEGER-PART TO WSB-INTEGER-PART.
MOVE WS-AB-DECIMAL-PART TO WSB-DECIMAL-PART.
IF WS-AB-NEGATIVE
SUBTRACT WS-BEARING FROM ZERO
GIVING WS-BEARING
END-IF.
300-TERMINATE.
DISPLAY 'RECORDS PROCESSED: ' REC-CTR.
CLOSE IN-FILE.
******************************************************************
* INPUT FILE ('Angle_diff.txt' stored on my PC at:
* 'C:\Both\Rosetta\Angle_diff.txt'
******************************************************************
* +000020.000000000000 +000045.000000000000
* -000045.000000000000 +000045.000000000000
* -000085.000000000000 +000090.000000000000
* -000095.000000000000 +000090.000000000000
* -000045.000000000000 +000125.000000000000
* -000045.000000000000 +000145.000000000000
* +000029.480300000000 -000088.638100000000
* -000078.325100000000 -000159.036000000000
* -070099.742338109380 +029840.674378767230
* -165313.666629735700 +033693.989451745600
* +001174.838051059846 -154146.664901247570
* +060175.773067955460 +042213.071923543730
******************************************************************
* OUTPUT:
******************************************************************
* 001 25.0000
* 002 90.0000
* 003 175.0000
* 004 -175.0000
* 005 170.0000
* 006 -170.0000
* 007 -118.1184
* 008 -80.7109
* 009 -139.5833
* 010 -72.3439
* 011 -161.5030
* 012 37.2989
******************************************************************
|
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
| #F.23 | F# | open System;
let keyIsSortedWord = Seq.sort >> Seq.toArray >> String
let isDeranged = Seq.forall2 (<>)
let rec pairs acc l = function
| [] -> acc
| x::rtail ->
pairs (acc @ List.fold (fun acc y -> (y, x)::acc) [] l) (x::l) rtail
[<EntryPoint>]
let main args =
System.IO.File.ReadAllLines("unixdict.txt")
|> Seq.groupBy keyIsSortedWord
|> Seq.fold (fun (len, found) (key, words) ->
if String.length key < len || Seq.length words < 2 then (len, found)
else
let d = List.filter (fun (a, b) -> isDeranged a b) (pairs [] [] (List.ofSeq words))
if List.length d = 0 then (len, found)
elif String.length key = len then (len, found @ d)
else (String.length key, d)
) (0, [])
|> snd
|> printfn "%A"
0 |
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.
| #Erlang | Erlang |
-module( anonymous_recursion ).
-export( [fib/1, fib_internal/1] ).
fib( N ) when N >= 0 ->
fib( N, 1, 0 ).
fib_internal( N ) when N >= 0 ->
Fun = fun (_F, 0, _Next, Acc ) -> Acc;
(F, N, Next, Acc) -> F( F, N - 1, Acc+Next, Next )
end,
Fun( Fun, N, 1, 0 ).
fib( 0, _Next, Acc ) -> Acc;
fib( N, Next, Acc ) -> fib( N - 1, Acc+Next, Next ).
|
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
| #jq | jq | ### Formatting
# Right-justify but do not truncate
def rjustify(n):
tostring | length as $length | if n <= $length then . else " " * (n-$length) + . end;
# Attempt to align decimals so integer part is in a field of width n
def align($n):
tostring
| index(".") as $ix
| if $ix
then if $n < $ix then .
elif $ix then (.[0:$ix]|rjustify($n)) +.[$ix:]
else rjustify($n)
end
else . + ".0" | align($n)
end ;
# number of decimal places ($n>=0)
def fround($n):
pow(10;$n) as $p
| (. * $p | round ) / $p
| tostring
| index(".") as $ix
| ("0" * $n) as $zeros
| if $ix then . + $zeros | .[0 : $ix + $n + 1]
else . + "." + $zeros
end;
def hide_trailing_zeros:
tostring
| (capture("(?<x>[^.]*[.].)(?<y>00*$)") // null) as $capture
| if $capture
then $capture | (.x + (.y|gsub("0"; " ")))
else .
end;
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
|
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
| #Julia | Julia | using Formatting
d2d(d) = d % 360
g2g(g) = g % 400
m2m(m) = m % 6400
r2r(r) = r % 2π
d2g(d) = d2d(d) * 10 / 9
d2m(d) = d2d(d) * 160 / 9
d2r(d) = d2d(d) * π / 180
g2d(g) = g2g(g) * 9 / 10
g2m(g) = g2g(g) * 16
g2r(g) = g2g(g) * π / 200
m2d(m) = m2m(m) * 9 / 160
m2g(m) = m2m(m) / 16
m2r(m) = m2m(m) * π / 3200
r2d(r) = r2r(r) * 180 / π
r2g(r) = r2r(r) * 200 / π
r2m(r) = r2r(r) * 3200 / π
fmt(x::Real, width=16) = Int(round(x)) == x ? rpad(Int(x), width) :
rpad(format(x, precision=7), width)
fmt(x::String, width=16) = rpad(x, width)
const t2u = Dict("degrees" => [d2d, d2g, d2m, d2r],
"gradians" => [g2d, g2g, g2m, g2r], "mils" => [m2d, m2g, m2m, m2r],
"radians" => [r2d, r2g, r2m, r2r])
function testconversions(arr)
println("Number Units Degrees Gradians Mils Radians")
for num in arr, units in ["degrees", "gradians", "mils", "radians"]
print(fmt(num), fmt(units))
for f in t2u[units]
print(fmt(f(num)))
end
println()
end
end
testconversions([-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000])
|
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.
| #C.2B.2B | C++ |
#include <vector>
#include <unordered_map>
#include <iostream>
int main() {
std::vector<int> alreadyDiscovered;
std::unordered_map<int, int> divsumMap;
int count = 0;
for (int N = 1; N <= 20000; ++N)
{
int divSumN = 0;
for (int i = 1; i <= N / 2; ++i)
{
if (fmod(N, i) == 0)
{
divSumN += i;
}
}
// populate map of integers to the sum of their proper divisors
if (divSumN != 1) // do not include primes
divsumMap[N] = divSumN;
for (std::unordered_map<int, int>::iterator it = divsumMap.begin(); it != divsumMap.end(); ++it)
{
int M = it->first;
int divSumM = it->second;
int divSumN = divsumMap[N];
if (N != M && divSumM == N && divSumN == M)
{
// do not print duplicate pairs
if (std::find(alreadyDiscovered.begin(), alreadyDiscovered.end(), N) != alreadyDiscovered.end())
break;
std::cout << "[" << M << ", " << N << "]" << std::endl;
alreadyDiscovered.push_back(M);
alreadyDiscovered.push_back(N);
count++;
}
}
}
std::cout << count << " amicable pairs discovered" << std::endl;
}
|
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.
| #Gambas | Gambas | 'This code will create the necessary controls on a GUI Form
hLabel As Label 'Label needed to display the 'Hello World! " message
hTimer As Timer 'Timer to rotate the display
bDirection As Boolean 'Used to control the direction of the text
'__________________________________________________
Public Sub Form_Open()
Dim hPanel As Panel '2 Panels used to centre the Label vertically on the Form
Dim hHBox As HBox 'Box to hold the Label
With Me 'Set the Form Properties
.Arrangement = Arrange.Vertical 'Arrange controls vertically
.Title = "Animation" 'Give the Form a Title
.Height = 75 'Set the Height of the Form
.Width = 225 'Set the Width of the Form
End With
hPanel = New Panel(Me) 'Add a Panel to the Form
HPanel.Expand = True 'Expand the Panel
hHBox = New HBox(Me) 'Add a HBox to the Form
hHBox.Height = 28 'Set the HBox Height
hLabel = New Label(hHBox) As "LabelAnimation" 'Add new Lable with Event name
With hLabel 'Change the hLabel properties
.Height = 35 'Set the Height of the Label
.Expand = True 'Expand the hLabel
.Font.Bold = True 'Set the Font to Bold
.Font.size = 20 'Set the Font Size
.Alignment = Align.Center 'Centre align the text
.Tooltip = "Click me to reverse direction" 'Add a Tooltip
.Border = Border.Plain 'Add a Border
.Text = "Hello World! " 'Add the Text
End With
hPanel = New Panel(Me) 'Add another Panel
HPanel.Expand = True 'Expand the Panel
hTimer = New Timer As "Timer1" 'Add a Timer
hTimer.delay = 500 'Set the Timer Delay
hTimer.Start 'Start the Timer
End
'__________________________________________________
Public Sub LabelAnimation_MouseDown() 'If the hLabel is clicked..
bDirection = Not bDirection 'Change the value of bDirection
End
'__________________________________________________
Public Sub Timer1_Timer() 'Timer
Dim sString As String = hLabel.Text 'To hold the text in the Label
Dim sTemp As String 'Temp string
If bDirection Then 'If the text is to rotate left then..
sTemp = Left(sString, 1) 'Get the first charater of the Label Text e.g 'H'
sString = Right(sString, -1) & sTemp 'Recreate sString with all the text less the 1st character e.g. 'ello World! ' and add the 1st character to the end e.g. 'ello World! H'
Else 'Else if text is to rotate right then..
sTemp = Right(sString, 1) 'Get the last charater of the Label Text e.g '!'
sString = sTemp & Left(sString, -1) 'Recreate sString with all the text less the last character e.g. ' Hello World' and add the last character to the begining e.g. '! Hello World'
End If
hLabel.text = sString 'Display the result
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.
| #Common_Lisp | Common Lisp | (defvar *frame-rate* 30)
(defvar *damping* 0.99 "Deceleration factor.")
(defun make-pendulum (length theta0 x)
"Returns an anonymous function with enclosed state representing a pendulum."
(let* ((theta (* (/ theta0 180) pi))
(acceleration 0))
(if (< length 40) (setf length 40)) ;;avoid a divide-by-zero
(lambda ()
;;Draws the pendulum, updating its location and speed.
(sdl:draw-line (sdl:point :x x :y 1)
(sdl:point :x (+ (* (sin theta) length) x)
:y (* (cos theta) length)))
(sdl:draw-filled-circle (sdl:point :x (+ (* (sin theta) length) x)
:y (* (cos theta) length))
20
:color sdl:*yellow*
:stroke-color sdl:*white*)
;;The magic constant approximates the speed we want for a given frame-rate.
(incf acceleration (* (sin theta) (* *frame-rate* -0.001)))
(incf theta acceleration)
(setf acceleration (* acceleration *damping*)))))
(defun main (&optional (w 640) (h 480))
(sdl:with-init ()
(sdl:window w h :title-caption "Pendulums"
:fps (make-instance 'sdl:fps-fixed))
(setf (sdl:frame-rate) *frame-rate*)
(let ((pendulums nil))
(sdl:with-events ()
(:quit-event () t)
(:idle ()
(sdl:clear-display sdl:*black*)
(mapcar #'funcall pendulums) ;;Draw all the pendulums
(sdl:update-display))
(:key-down-event (:key key)
(cond ((sdl:key= key :sdl-key-escape)
(sdl:push-quit-event))
((sdl:key= key :sdl-key-space)
(push (make-pendulum (random (- h 100))
(random 90)
(round w 2))
pendulums)))))))) |
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
| #Common_Lisp | Common Lisp |
(defun angle-difference (b1 b2)
(let ((diff (mod (- b2 b1) 360)))
(if (< diff -180)
(incf diff 360)
(if (> diff 180)
(decf diff 360)
diff))))
|
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
| #Factor | Factor | USING: assocs fry io.encodings.utf8 io.files kernel math
math.combinatorics sequences sorting strings ;
IN: rosettacode.deranged-anagrams
: derangement? ( str1 str2 -- ? ) [ = not ] 2all? ;
: derangements ( seq -- seq )
2 [ first2 derangement? ] filter-combinations ;
: parse-dict-file ( path -- hash )
utf8 file-lines
H{ } clone [
'[
[ natural-sort >string ] keep
_ [ swap suffix ] with change-at
] each
] keep ;
: anagrams ( hash -- seq ) [ nip length 1 > ] assoc-filter values ;
: deranged-anagrams ( path -- seq )
parse-dict-file anagrams [ derangements ] map concat ;
: longest-deranged-anagrams ( path -- anagrams )
deranged-anagrams [ first length ] sort-with last ; |
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.23 | F# | let fib = function
| n when n < 0 -> None
| n -> let rec fib2 = function
| 0 | 1 -> 1
| n -> fib2 (n-1) + fib2 (n-2)
in Some (fib2 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
| #Kotlin | Kotlin | import java.text.DecimalFormat as DF
const val DEGREE = 360.0
const val GRADIAN = 400.0
const val MIL = 6400.0
const val RADIAN = 2 * Math.PI
fun d2d(a: Double) = a % DEGREE
fun d2g(a: Double) = a * (GRADIAN / DEGREE)
fun d2m(a: Double) = a * (MIL / DEGREE)
fun d2r(a: Double) = a * (RADIAN / 360)
fun g2d(a: Double) = a * (DEGREE / GRADIAN)
fun g2g(a: Double) = a % GRADIAN
fun g2m(a: Double) = a * (MIL / GRADIAN)
fun g2r(a: Double) = a * (RADIAN / GRADIAN)
fun m2d(a: Double) = a * (DEGREE / MIL)
fun m2g(a: Double) = a * (GRADIAN / MIL)
fun m2m(a: Double) = a % MIL
fun m2r(a: Double) = a * (RADIAN / MIL)
fun r2d(a: Double) = a * (DEGREE / RADIAN)
fun r2g(a: Double) = a * (GRADIAN / RADIAN)
fun r2m(a: Double) = a * (MIL / RADIAN)
fun r2r(a: Double) = a % RADIAN
fun main() {
val fa = DF("######0.000000")
val fc = DF("###0.0000")
println(" degrees gradiens mils radians")
for (a in listOf(-2.0, -1.0, 0.0, 1.0, 2.0, 6.2831853, 16.0, 57.2957795, 359.0, 399.0, 6399.0, 1000000.0))
for (units in listOf("degrees", "gradiens", "mils", "radians")) {
val (d,g,m,r) = when (units) {
"degrees" -> {
val d = d2d(a)
listOf(d, d2g(d), d2m(d), d2r(d))
}
"gradiens" -> {
val g = g2g(a)
listOf(g2d(g), g, g2m(g), g2r(g))
}
"mils" -> {
val m = m2m(a)
listOf(m2d(m), m2g(m), m, m2r(m))
}
"radians" -> {
val r = r2r(a)
listOf(r2d(r), r2g(r), r2m(r), r)
}
else -> emptyList()
}
println("%15s %8s = %10s %10s %10s %10s".format(fa.format(a), units, fc.format(d), fc.format(g), fc.format(m), fc.format(r)))
}
} |
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.
| #Clojure | Clojure |
(ns example
(:gen-class))
(defn factors [n]
" Find the proper factors of a number "
(into (sorted-set)
(mapcat (fn [x] (if (= x 1) [x] [x (/ n x)]))
(filter #(zero? (rem n %)) (range 1 (inc (Math/sqrt n)))) )))
(def find-pairs (into #{}
(for [n (range 2 20000)
:let [f (factors n) ; Factors of n
M (apply + f) ; Sum of factors
g (factors M) ; Factors of sum
N (apply + g)] ; Sum of Factors of sum
:when (= n N) ; (sum(proDivs(N)) = M and sum(propDivs(M)) = N
:when (not= M N)] ; N not-equal M
(sorted-set n M)))) ; Found pair
;; Output Results
(doseq [q find-pairs]
(println 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
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.
| #Go | Go | package main
import (
"log"
"time"
"github.com/gdamore/tcell"
)
const (
msg = "Hello World! "
x0, y0 = 8, 3
shiftsPerSecond = 4
clicksToExit = 5
)
func main() {
s, err := tcell.NewScreen()
if err != nil {
log.Fatal(err)
}
if err = s.Init(); err != nil {
log.Fatal(err)
}
s.Clear()
s.EnableMouse()
tick := time.Tick(time.Second / shiftsPerSecond)
click := make(chan bool)
go func() {
for {
em, ok := s.PollEvent().(*tcell.EventMouse)
if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
continue
}
mx, my := em.Position()
if my == y0 && mx >= x0 && mx < x0+len(msg) {
click <- true
}
}
}()
for inc, shift, clicks := 1, 0, 0; ; {
select {
case <-tick:
shift = (shift + inc) % len(msg)
for i, r := range msg {
s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
}
s.Show()
case <-click:
clicks++
if clicks == clicksToExit {
s.Fini()
return
}
inc = len(msg) - inc
}
}
} |
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.
| #Delphi | Delphi |
unit main;
interface
uses
Vcl.Forms, Vcl.Graphics, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
Timer: TTimer;
angle, angleAccel, angleVelocity, dt: double;
len: Integer;
procedure Tick(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Width := 200;
Height := 200;
DoubleBuffered := True;
Timer := TTimer.Create(nil);
Timer.Interval := 30;
Timer.OnTimer := Tick;
Caption := 'Pendulum';
// initialize
angle := PI / 2;
angleAccel := 0;
angleVelocity := 0;
dt := 0.1;
len := 50;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Timer.Free;
end;
procedure TForm1.Tick(Sender: TObject);
const
HalfPivot = 4;
HalfBall = 7;
var
anchorX, anchorY, ballX, ballY: Integer;
begin
anchorX := Width div 2 - 12;
anchorY := Height div 4;
ballX := anchorX + Trunc(Sin(angle) * len);
ballY := anchorY + Trunc(Cos(angle) * len);
angleAccel := -9.81 / len * Sin(angle);
angleVelocity := angleVelocity + angleAccel * dt;
angle := angle + angleVelocity * dt;
with canvas do
begin
Pen.Color := clBlack;
with Brush do
begin
Style := bsSolid;
Color := clWhite;
end;
FillRect(ClientRect);
MoveTo(anchorX, anchorY);
LineTo(ballX, ballY);
Brush.Color := clGray;
Ellipse(anchorX - HalfPivot, anchorY - HalfPivot, anchorX + HalfPivot,
anchorY + HalfPivot);
Brush.Color := clYellow;
Ellipse(ballX - HalfBall, ballY - HalfBall, ballX + HalfBall, ballY + HalfBall);
end;
end;
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.
| #11l | 11l | F isqrt(BigInt =x)
BigInt q = 1
BigInt r = 0
BigInt t
L q <= x
q *= 4
L q > 1
q I/= 4
t = x - r - q
r I/= 2
I t >= 0
x = t
r += q
R r
F dump(=digs, show)
V gb = 1
digs++
V dg = digs + gb
BigInt t1 = 1
BigInt t2 = 9
BigInt t3 = 1
BigInt te
BigInt su = 0
V t = BigInt(10) ^ (I dg <= 60 {0} E dg - 60)
BigInt d = -1
BigInt _fn_ = 1
V n = 0
L n < dg
I n > 0
t3 *= BigInt(n) ^ 6
te = t1 * t2 I/ t3
V z = dg - 1 - n * 6
I z > 0
te *= BigInt(10) ^ z
E
te I/= BigInt(10) ^ -z
I show & n < 10
print(‘#2 #62’.format(n, te * 32 I/ 3 I/ t))
su += te
I te < 10
I show
digs--
print("\n#. iterations required for #. digits after the decimal point.\n".format(n, digs))
L.break
L(j) n * 6 + 1 .. n * 6 + 6
t1 *= j
d += 2
t2 += 126 + 532 * d
n++
V s = String(isqrt(BigInt(10) ^ (dg * 2 + 3) I/ su I/ 32 * 3 * BigInt(10) ^ (dg + 5)))
R s[0]‘.’s[1 .+ digs]
print(dump(70, 1B)) |
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
| #D | D | import std.stdio;
double getDifference(double b1, double b2) {
double r = (b2 - b1) % 360.0;
if (r < -180.0) {
r += 360.0;
}
if (r >= 180.0) {
r -= 360.0;
}
return r;
}
void main() {
writeln("Input in -180 to +180 range");
writeln(getDifference(20.0, 45.0));
writeln(getDifference(-45.0, 45.0));
writeln(getDifference(-85.0, 90.0));
writeln(getDifference(-95.0, 90.0));
writeln(getDifference(-45.0, 125.0));
writeln(getDifference(-45.0, 145.0));
writeln(getDifference(-45.0, 125.0));
writeln(getDifference(-45.0, 145.0));
writeln(getDifference(29.4803, -88.6381));
writeln(getDifference(-78.3251, -159.036));
writeln("Input in wider range");
writeln(getDifference(-70099.74233810938, 29840.67437876723));
writeln(getDifference(-165313.6666297357, 33693.9894517456));
writeln(getDifference(1174.8380510598456, -154146.66490124757));
writeln(getDifference(60175.77306795546, 42213.07192354373));
} |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type IndexedWord
As String word
As Integer index
End Type
' selection sort, quick enough for sorting small number of letters
Sub sortWord(s As String)
Dim As Integer i, j, m, n = Len(s)
For i = 0 To n - 2
m = i
For j = i + 1 To n - 1
If s[j] < s[m] Then m = j
Next j
If m <> i Then Swap s[i], s[m]
Next i
End Sub
' quicksort for sorting whole dictionary of IndexedWord instances by sorted word
Sub quicksort(a() As IndexedWord, first As Integer, last As Integer)
Dim As Integer length = last - first + 1
If length < 2 Then Return
Dim pivot As String = a(first + length\ 2).word
Dim lft As Integer = first
Dim rgt As Integer = last
While lft <= rgt
While a(lft).word < pivot
lft +=1
Wend
While a(rgt).word > pivot
rgt -= 1
Wend
If lft <= rgt Then
Swap a(lft), a(rgt)
lft += 1
rgt -= 1
End If
Wend
quicksort(a(), first, rgt)
quicksort(a(), lft, last)
End Sub
Function isDeranged(s1 As String, s2 As String) As Boolean
For i As Integer = 0 To Len(s1) - 1
If s1[i] = s2[i] Then Return False
Next
Return True
End Function
Dim t As Double = timer
Dim As String w() '' array to hold actual words
Open "undict.txt" For Input As #1
Dim count As Integer = 0
While Not Eof(1)
count +=1
Redim Preserve w(1 To count)
Line Input #1, w(count)
Wend
Close #1
Dim As IndexedWord iw(1 To count) '' array to hold sorted words and their index into w()
Dim word As String
For i As Integer = 1 To count
word = w(i)
sortWord(word)
iw(i).word = word
iw(i).index = i
Next
quickSort iw(), 1, count '' sort the IndexedWord array by sorted word
Dim As Integer startIndex = 1, maxLength, ub
Dim As Integer maxIndex()
Dim As IndexedWord iWord = iw(1)
maxLength = 0
For i As Integer = 2 To count
If iWord.word = iw(i).word Then
If isDeranged(w(iword.index), w(iw(i).index)) Then
If startIndex + 1 < i Then Swap iw(i), iw(startIndex + 1)
If Len(iWord.word) > maxLength Then
maxLength = Len(iWord.word)
Erase maxIndex
ub = 1
Redim maxIndex(1 To ub)
maxIndex(ub) = startIndex
startIndex += 2
i = startIndex
iWord = iw(i)
ElseIf Len(iWord.word) = maxLength Then
ub += 1
Redim Preserve maxIndex(1 To ub)
maxIndex(ub) = startIndex
startIndex += 2
i = startIndex
iWord = iw(i)
End If
End If
ElseIf i = count Then
Exit For
Else
For j As Integer = i To count - 1
iWord = iw(j)
If Len(iWord.word) >= maxLength Then
startIndex = j
i = startIndex
Exit For
End If
Next
End If
Next
Print Str(count); " words in the dictionary"
Print "The deranged anagram pair(s) with the greatest length (namely"; maxLength; ") is:"
Print
Dim iws(1 To maxLength) As IndexedWord '' array to hold each deranged anagram pair
For i As Integer = 1 To UBound(maxIndex)
For j As Integer = maxIndex(i) To maxIndex(i) + 1
iws(j - maxIndex(i) + 1) = iw(j)
Next j
If iws(1).index > iws(2).index Then swap iws(1), iws(2) '' ensure pair is in correct order
For j As Integer = 1 To 2
Print w(iws(j).index); " ";
Next j
Print
Next i
Print
Print "Took ";
Print Using "#.###"; timer - t;
Print " seconds on i3 @ 2.13 GHz"
Print
Print "Press any key to quit"
Sleep |
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.
| #Factor | Factor | USING: kernel math ;
IN: rosettacode.fibonacci.ar
: fib ( n -- m )
dup 0 < [ "fib of negative" throw ] when
[
! If n < 2, then drop q, else find q(n - 1) + q(n - 2).
[ dup 2 < ] dip swap [ drop ] [
[ [ 1 - ] dip dup call ]
[ [ 2 - ] dip dup call ] 2bi +
] if
] dup call( n q -- 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º
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
| #Lua | Lua | range = { degrees=360, gradians=400, mils=6400, radians=2.0*math.pi }
function convert(value, fromunit, tounit)
return math.fmod(value * range[tounit] / range[fromunit], range[tounit])
end
testvalues = { -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000 }
testunits = { "degrees", "gradians", "mils", "radians" }
print(string.format("%15s %8s = %15s %15s %15s %15s", "VALUE", "UNIT", "DEGREES", "GRADIANS", "MILS", "RADIANS"))
for _, value in ipairs(testvalues) do
for _, fromunit in ipairs(testunits) do
local d = convert(value, fromunit, "degrees")
local g = convert(value, fromunit, "gradians")
local m = convert(value, fromunit, "mils")
local r = convert(value, fromunit, "radians")
print(string.format("%15.7f %8s = %15.7f %15.7f %15.7f %15.7f", value, fromunit, d, g, m, r))
end
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.
| #CLU | CLU | % Generate proper divisors from 1 to max
proper_divisors = proc (max: int) returns (array[int])
divs: array[int] := array[int]$fill(1, max, 0)
for i: int in int$from_to(1, max/2) do
for j: int in int$from_to_by(i*2, max, i) do
divs[j] := divs[j] + i
end
end
return(divs)
end proper_divisors
% Are A and B and amicable pair, given the proper divisors?
amicable = proc (divs: array[int], a, b: int) returns (bool)
return(divs[a] = b & divs[b] = a)
end amicable
% Find all amicable pairs up to 20 000
start_up = proc ()
max = 20000
po: stream := stream$primary_output()
divs: array[int] := proper_divisors(max)
for a: int in int$from_to(1, max) do
for b: int in int$from_to(a+1, max) do
if amicable(divs, a, b) then
stream$putl(po, int$unparse(a) || ", " || int$unparse(b))
end
end
end
end start_up |
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.
| #Haskell | Haskell | import Graphics.HGL.Units (Time, Point, Size, )
import Graphics.HGL.Draw.Monad (Graphic, )
import Graphics.HGL.Draw.Text
import Graphics.HGL.Draw.Font
import Graphics.HGL.Window
import Graphics.HGL.Run
import Graphics.HGL.Utils
import Control.Exception (bracket, )
runAnim = runGraphics $
bracket
(openWindowEx "Basic animation task" Nothing (250,50) DoubleBuffered (Just 110))
closeWindow
(\w -> do
f <- createFont (64,28) 0 False False "courier"
let loop t dir = do
e <- maybeGetWindowEvent w
let d = case e of
Just (Button _ True False) -> -dir
_ -> dir
t' = if d == 1 then last t : init t else tail t ++ [head t]
setGraphic w (withFont f $ text (5,10) t') >> getWindowTick w
loop t' d
loop "Hello world ! " 1 ) |
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.
| #E | E | #!/usr/bin/env rune
pragma.syntax("0.9")
def pi := (-1.0).acos()
def makeEPainter := <unsafe:com.zooko.tray.makeEPainter>
def makeLamportSlot := <import:org.erights.e.elib.slot.makeLamportSlot>
def whenever := <import:org.erights.e.elib.slot.whenever>
def colors := <import:java.awt.makeColor>
# --------------------------------------------------------------
# --- Definitions
def makePendulumSim(length_m :float64,
gravity_mps2 :float64,
initialAngle_rad :float64,
timestep_ms :int) {
var velocity := 0
def &angle := makeLamportSlot(initialAngle_rad)
def k := -gravity_mps2/length_m
def timestep_s := timestep_ms / 1000
def clock := timer.every(timestep_ms, fn _ {
def acceleration := k * angle.sin()
velocity += acceleration * timestep_s
angle += velocity * timestep_s
})
return [clock, &angle]
}
def makeDisplayComponent(&angle) {
def c
def updater := whenever([&angle], fn { c.repaint() })
bind c := makeEPainter(def paintCallback {
to paintComponent(g) {
try {
def originX := c.getWidth() // 2
def originY := c.getHeight() // 2
def pendRadius := (originX.min(originY) * 0.95).round()
def ballRadius := (originX.min(originY) * 0.04).round()
def ballX := (originX + angle.sin() * pendRadius).round()
def ballY := (originY + angle.cos() * pendRadius).round()
g.setColor(colors.getWhite())
g.fillRect(0, 0, c.getWidth(), c.getHeight())
g.setColor(colors.getBlack())
g.fillOval(originX - 2, originY - 2, 4, 4)
g.drawLine(originX, originY, ballX, ballY)
g.fillOval(ballX - ballRadius, ballY - ballRadius, ballRadius * 2, ballRadius * 2)
updater[] # provoke interest provided that we did get drawn (window not closed)
} catch p {
stderr.println(`In paint callback: $p${p.eStack()}`)
}
}
})
c.setPreferredSize(<awt:makeDimension>(300, 300))
return c
}
# --------------------------------------------------------------
# --- Application setup
def [clock, &angle] := makePendulumSim(1, 9.80665, pi*99/100, 10)
# Initialize AWT, move to AWT event thread
when (currentVat.morphInto("awt")) -> {
# Create the window
def frame := <unsafe:javax.swing.makeJFrame>("Pendulum")
frame.setContentPane(def display := makeDisplayComponent(&angle))
frame.addWindowListener(def mainWindowListener {
to windowClosing(_) {
clock.stop()
interp.continueAtTop()
}
match _ {}
})
frame.setLocation(50, 50)
frame.pack()
# Start and become visible
frame.show()
clock.start()
}
interp.blockAtTop() |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program calculPi64.s */
/* this program use gmp library */
/* link with gcc option -lgmp */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI, 10
.equ SIZEBIG, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessDebutPgm: .asciz "Program 64 bits start. \n"
szMessPi: .asciz "\nPI = \n"
szCarriageReturn: .asciz "\n"
szFormat: .asciz " %Zd\n"
szFormatFloat: .asciz " %.*Ff\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
Result1: .skip SIZEBIG
Result2: .skip SIZEBIG
Result3: .skip SIZEBIG
Result4: .skip SIZEBIG
fIntex5: .skip SIZEBIG
fIntex6: .skip SIZEBIG
fIntex7: .skip SIZEBIG
fSum: .skip SIZEBIG
fSum1: .skip SIZEBIG
sBuffer: .skip SIZEBIG
fEpsilon: .skip SIZEBIG
fPrec: .skip SIZEBIG
fPI: .skip SIZEBIG
fTEN: .skip SIZEBIG
fONE: .skip SIZEBIG
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessDebutPgm
bl affichageMess
mov x20,#0 // loop indice
1:
mov x0,x20
bl computeAlmkvist // compute
mov x1,x0
ldr x0,qAdrszFormat // print big integer
bl __gmp_printf
add x20,x20,#1
cmp x20,#MAXI
blt 1b // and loop
mov x0,#560 // float précision in bits
bl __gmpf_set_default_prec
mov x19,#0 // compute indice
ldr x0,qAdrfSum // init to zéro
bl __gmpf_init
ldr x0,qAdrfSum1 // init to zéro
bl __gmpf_init
ldr x0,qAdrfONE // result address
mov x1,#1 // init à 1
bl __gmpf_init_set_ui
ldr x0,qAdrfIntex5 // init to zéro
bl __gmpf_init
ldr x0,qAdrfIntex6 // init to zéro
bl __gmpf_init
ldr x0,qAdrfIntex7 // init to zéro
bl __gmpf_init
ldr x0,qAdrfEpsilon // init to zéro
bl __gmpf_init
ldr x0,qAdrfPrec // init to zéro
bl __gmpf_init
ldr x0,qAdrfPI // init to zéro
bl __gmpf_init
ldr x0,qAdrfTEN
mov x1,#10 // init to 10
bl __gmpf_init_set_ui
ldr x0,qAdrfIntex6 // compute 10 pow 70
ldr x1,qAdrfTEN
mov x2,#70
bl __gmpf_pow_ui
ldr x0,qAdrfEpsilon // divide 1 by 10 pow 70
ldr x1,qAdrfONE // dividende
ldr x2,qAdrfIntex6 // divisor
bl __gmpf_div
2: // PI compute loop
mov x0,x19
bl computeAlmkvist
mov x20,x0
mov x1,#6
mul x2,x1,x19
add x6,x2,#3 // compute 6n + 3
ldr x0,qAdrfIntex6 // compute 10 pow (6n+3)
ldr x1,qAdrfTEN
mov x2,x6
bl __gmpf_pow_ui
ldr x0,qAdrfIntex7 // compute 1 / 10 pow (6n+3)
ldr x1,qAdrfONE // dividende
ldr x2,qAdrfIntex6 // divisor
bl __gmpf_div
ldr x0,qAdrfIntex6 // result big float
mov x1,x20 // big integer Almkvist
bl __gmpf_set_z // conversion in big float
ldr x0,qAdrfIntex5 // result Almkvist * 1 / 10 pow (6n+3)
ldr x1,qAdrfIntex7 // operator 1
ldr x2,qAdrfIntex6 // operator 2
bl __gmpf_mul
ldr x0,qAdrfSum1 // terms addition
ldr x1,qAdrfSum
ldr x2,qAdrfIntex5
bl __gmpf_add
ldr x0,qAdrfSum // copy terms
ldr x1,qAdrfSum1
bl __gmpf_set
ldr x0,qAdrfIntex7 // compute 1 / sum
ldr x1,qAdrfONE // dividende
ldr x2,qAdrfSum // divisor
bl __gmpf_div
ldr x0,qAdrfPI // compute square root (1 / sum )
ldr x1,qAdrfIntex7
bl __gmpf_sqrt
ldr x0,qAdrfIntex6 // compute variation PI
ldr x1,qAdrfPrec
ldr x2,qAdrfPI
bl __gmpf_sub
ldr x0,qAdrfIntex6 // absolue value
ldr x1,qAdrfIntex5
bl __gmpf_abs
add x19,x19,#1 // increment indice
ldr x0,qAdrfPrec // copy PI -> prévious
ldr x1,qAdrfPI
bl __gmpf_set
ldr x0,qAdrfIntex6 // compare gap and epsilon
ldr x1,qAdrfEpsilon
bl __gmpf_cmp
cmp w0,#0 // !!! cmp return result on 32 bits
bgt 2b // if gap is highter -> loop
ldr x0,qAdrszMessPi // title display
bl affichageMess
ldr x2,qAdrfPI // PI display
ldr x0,qAdrszFormatFloat
mov x1,#70
bl __gmp_printf
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszMessDebutPgm: .quad szMessDebutPgm
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrfIntex5: .quad fIntex5
qAdrfIntex6: .quad fIntex6
qAdrfIntex7: .quad fIntex7
qAdrfSum: .quad fSum
qAdrfSum1: .quad fSum1
qAdrszFormatFloat: .quad szFormatFloat
qAdrszMessPi: .quad szMessPi
qAdrfEpsilon: .quad fEpsilon
qAdrfPrec: .quad fPrec
qAdrfPI: .quad fPI
qAdrfTEN: .quad fTEN
qAdrfONE: .quad fONE
/***************************************************/
/* compute almkvist_giullera formula */
/***************************************************/
/* x0 contains the number */
computeAlmkvist:
stp x19,lr,[sp,-16]! // save registers
mov x19,x0
mov x1,#6
mul x0,x1,x0
ldr x1,qAdrResult1 // result address
bl computeFactorielle // compute (n*6)!
mov x1,#532
mul x2,x19,x19
mul x2,x1,x2
mov x1,#126
mul x3,x19,x1
add x2,x2,x3
add x2,x2,#9
lsl x2,x2,#5 // * 32
ldr x0,qAdrResult2 // result
ldr x1,qAdrResult1 // operator
bl __gmpz_mul_ui
mov x0,x19
ldr x1,qAdrResult1
bl computeFactorielle
ldr x0,qAdrResult3
bl __gmpz_init // init to 0
ldr x0,qAdrResult3 // result
ldr x1,qAdrResult1 // operator
mov x2,#6
bl __gmpz_pow_ui
ldr x0,qAdrResult1 // result
ldr x1,qAdrResult3 // operator
mov x2,#3
bl __gmpz_mul_ui
ldr x0,qAdrResult3 // result
ldr x1,qAdrResult2 // operator
ldr x2,qAdrResult1 // operator
bl __gmpz_cdiv_q
ldr x0,qAdrResult3 // return result address
100:
ldp x19,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszFormat: .quad szFormat
qAdrResult1: .quad Result1
qAdrResult2: .quad Result2
qAdrResult3: .quad Result3
/***************************************************/
/* compute factorielle N */
/***************************************************/
/* x0 contains the number */
/* x1 contains big number result address */
computeFactorielle:
stp x19,lr,[sp,-16]! // save registers
stp x20,x21,[sp,-16]! // save registers
mov x19,x0 // save N
mov x20,x1 // save result address
mov x0,x1 // result address
mov x1,#1 // init to 1
bl __gmpz_init_set_ui
ldr x0,qAdrResult4
bl __gmpz_init // init to 0
mov x21,#1
1: // loop
ldr x0,qAdrResult4 // result
mov x1,x20 // operator 1
mov x2,x21 // operator 2
bl __gmpz_mul_ui
mov x0,x20 // copy result4 -> result
ldr x1,qAdrResult4
bl __gmpz_set
add x21,x21,#1 // increment indice
cmp x21,x19 // N ?
ble 1b // no -> loop
ldr x0,qAdrResult4
ldp x20,x21,[sp],16 // restaur 2 registers
ldp x19,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrResult4: .quad Result4
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program calculPi.s */
/* this program use gmp library package : libgmp3-dev */
/* link with gcc option -lgmp */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 10
.equ SIZEBIG, 100
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessPi: .asciz "\nPI = \n"
szCarriageReturn: .asciz "\n"
szFormat: .asciz " %Zd\n"
szFormatFloat: .asciz " %.*Ff\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
Result1: .skip SIZEBIG
Result2: .skip SIZEBIG
Result3: .skip SIZEBIG
Result4: .skip SIZEBIG
fInter5: .skip SIZEBIG
fInter6: .skip SIZEBIG
fInter7: .skip SIZEBIG
fSum: .skip SIZEBIG
fSum1: .skip SIZEBIG
sBuffer: .skip SIZEBIG
fEpsilon: .skip SIZEBIG
fPrec: .skip SIZEBIG
fPI: .skip SIZEBIG
fTEN: .skip SIZEBIG
fONE: .skip SIZEBIG
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
mov r4,#0 @ loop indice
1:
mov r0,r4
bl computeAlmkvist @ compute
mov r1,r0
ldr r0,iAdrszFormat @ print big integer
bl __gmp_printf
add r4,r4,#1
cmp r4,#MAXI
blt 1b @ and loop
mov r0,#560 @ float précision in bits
bl __gmpf_set_default_prec
mov r4,#0 @ compute indice
ldr r0,iAdrfSum @ init to zéro
bl __gmpf_init
ldr r0,iAdrfSum1 @ init to zéro
bl __gmpf_init
ldr r0,iAdrfONE @ result address
mov r1,#1 @ init à 1
bl __gmpf_init_set_ui
ldr r0,iAdrfInter5 @ init to zéro
bl __gmpf_init
ldr r0,iAdrfInter6 @ init to zéro
bl __gmpf_init
ldr r0,iAdrfInter7 @ init to zéro
bl __gmpf_init
ldr r0,iAdrfEpsilon @ init to zéro
bl __gmpf_init
ldr r0,iAdrfPrec @ init to zéro
bl __gmpf_init
ldr r0,iAdrfPI @ init to zéro
bl __gmpf_init
ldr r0,iAdrfTEN
mov r1,#10 @ init to 10
bl __gmpf_init_set_ui
ldr r0,iAdrfInter6 @ compute 10 pow 70
ldr r1,iAdrfTEN
mov r2,#70
bl __gmpf_pow_ui
ldr r0,iAdrfEpsilon @ divide 1 by 10 pow 70
ldr r1,iAdrfONE @ dividende
ldr r2,iAdrfInter6 @ divisor
bl __gmpf_div
2: @ PI compute loop
mov r0,r4
bl computeAlmkvist
mov r5,r0
mov r1,#6
mul r2,r1,r4
add r6,r2,#3 @ compute 6n + 3
ldr r0,iAdrfInter6 @ compute 10 pow (6n+3)
ldr r1,iAdrfTEN
mov r2,r6
bl __gmpf_pow_ui
ldr r0,iAdrfInter7 @ compute 1 / 10 pow (6n+3)
ldr r1,iAdrfONE @ dividende
ldr r2,iAdrfInter6 @ divisor
bl __gmpf_div
ldr r0,iAdrfInter6 @ result big float
mov r1,r5 @ big integer Almkvist
bl __gmpf_set_z @ conversion in big float
ldr r0,iAdrfInter5 @ result Almkvist * 1 / 10 pow (6n+3)
ldr r1,iAdrfInter7 @ operator 1
ldr r2,iAdrfInter6 @ operator 2
bl __gmpf_mul
ldr r0,iAdrfSum1 @ terms addition
ldr r1,iAdrfSum
ldr r2,iAdrfInter5
bl __gmpf_add
ldr r0,iAdrfSum @ copy terms
ldr r1,iAdrfSum1
bl __gmpf_set
ldr r0,iAdrfInter7 @ compute 1 / sum
ldr r1,iAdrfONE @ dividende
ldr r2,iAdrfSum @ divisor
bl __gmpf_div
ldr r0,iAdrfPI @ compute square root (1 / sum )
ldr r1,iAdrfInter7
bl __gmpf_sqrt
ldr r0,iAdrfInter6 @ compute variation PI
ldr r1,iAdrfPrec
ldr r2,iAdrfPI
bl __gmpf_sub
ldr r0,iAdrfInter6 @ absolue value
ldr r1,iAdrfInter5
bl __gmpf_abs
add r4,r4,#1 @ increment indice
ldr r0,iAdrfPrec @ copy PI -> prévious
ldr r1,iAdrfPI
bl __gmpf_set
ldr r0,iAdrfInter6 @ compare gap and epsilon
ldr r1,iAdrfEpsilon
bl __gmpf_cmp
cmp r0,#0
bgt 2b @ if gap is highter -> loop
ldr r0,iAdrszMessPi @ title display
bl affichageMess
ldr r2,iAdrfPI @ PI display
ldr r0,iAdrszFormatFloat
mov r1,#70
bl __gmp_printf
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrfInter5: .int fInter5
iAdrfInter6: .int fInter6
iAdrfInter7: .int fInter7
iAdrfSum: .int fSum
iAdrfSum1: .int fSum1
iAdrszFormatFloat: .int szFormatFloat
iAdrszMessPi: .int szMessPi
iAdrfEpsilon: .int fEpsilon
iAdrfPrec: .int fPrec
iAdrfPI: .int fPI
iAdrfTEN: .int fTEN
iAdrfONE: .int fONE
/***************************************************/
/* compute almkvist_giullera formula */
/***************************************************/
/* r0 contains the number */
computeAlmkvist:
push {r1-r4,lr} @ save registers
mov r4,r0
mov r1,#6
mul r0,r1,r0
ldr r1,iAdrResult1 @ result address
bl computeFactorielle @ compute (n*6)!
mov r1,#532
mul r2,r4,r4
mul r2,r1,r2
mov r1,#126
mul r3,r4,r1
add r2,r2,r3
add r2,#9
lsl r2,r2,#5 @ * 32
ldr r0,iAdrResult2 @ result
ldr r1,iAdrResult1 @ operator
bl __gmpz_mul_ui
mov r0,r4
ldr r1,iAdrResult1
bl computeFactorielle
ldr r0,iAdrResult3
bl __gmpz_init @ init to 0
ldr r0,iAdrResult3 @ result
ldr r1,iAdrResult1 @ operator
mov r2,#6
bl __gmpz_pow_ui
ldr r0,iAdrResult1 @ result
ldr r1,iAdrResult3 @ operator
mov r2,#3
bl __gmpz_mul_ui
ldr r0,iAdrResult3 @ result
ldr r1,iAdrResult2 @ operator
ldr r2,iAdrResult1 @ operator
bl __gmpz_cdiv_q
ldr r0,iAdrResult3 @ return result address
pop {r1-r4,pc} @ restaur des registres
iAdrszFormat: .int szFormat
iAdrResult1: .int Result1
iAdrResult2: .int Result2
iAdrResult3: .int Result3
/***************************************************/
/* compute factorielle N */
/***************************************************/
/* r0 contains the number */
/* r1 contains big number result address */
computeFactorielle:
push {r1-r6,lr} @ save registers
mov r5,r0 @ save N
mov r6,r1 @ save result address
mov r0,r1 @ result address
mov r1,#1 @ init to 1
bl __gmpz_init_set_ui
ldr r0,iAdrResult4
bl __gmpz_init @ init to 0
mov r4,#1
1: @ loop
ldr r0,iAdrResult4 @ result
mov r1,r6 @ operator 1
mov r2,r4 @ operator 2
bl __gmpz_mul_ui
mov r0,r6 @ copy result4 -> result
ldr r1,iAdrResult4
bl __gmpz_set
add r4,r4,#1 @ increment indice
cmp r4,r5 @ N ?
ble 1b @ no -> loop
mov r0,r1
pop {r1-r6,pc} @ restaur des registres
iAdrResult4: .int Result4
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.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
| #Delphi | Delphi |
-module(bearings).
%% API
-export([angle_sub_degrees/2,test/0]).
-define(RealAngleMultiplier,16#10000000000).
-define(DegreesPerTurn,360).
-define(Precision,9).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% @spec
%% @end
%%--------------------------------------------------------------------
%%
angle_sub_degrees(B1,B2) when is_integer(B1), is_integer(B2) ->
angle_sub(B2-B1,?DegreesPerTurn);
angle_sub_degrees(B1,B2) ->
NewB1 = trunc(B1*?RealAngleMultiplier),
NewB2 = trunc(B2*?RealAngleMultiplier),
round(angle_sub(NewB2 - NewB1,
?DegreesPerTurn*?RealAngleMultiplier)
/?RealAngleMultiplier,?Precision).
%%%===================================================================
%%% Internal functions
%%%===================================================================
%% delta normalises the angle difference. Consider a turn from 350 degrees
%% to 20 degrees. Subtraction results in 330 degress. This is equivalent of
%% a turn in the other direction of 30 degrees, thus 330 degrees is equal
%% to -30 degrees.
angle_sub(Value,TurnSize) ->
NormalisedValue = Value rem TurnSize,
minimise_angle(NormalisedValue,TurnSize).
% X rem Turn result in 0..Turn for X > 0 and -Turn..0 for X < 0
% specification requires -Turn/2 < X < Turn/2. This is achieved
% by adding or removing a turn as required.
% bsr 1 divides an integer by 2
minimise_angle(Angle,Turn) when Angle + (Turn bsr 1) < 0 ->
Angle+Turn;
minimise_angle(Angle,Turn) when Angle - (Turn bsr 1) > 0 ->
Angle-Turn;
minimise_angle(Angle,_) ->
Angle.
round(Number,Precision) ->
P = math:pow(10,Precision),
round(Number*P)/P.
test() ->
25 = angle_sub_degrees(20,45),
90 = angle_sub_degrees(-45,45),
175 = angle_sub_degrees(-85,90),
-175 = angle_sub_degrees(-95,90),
170 = angle_sub_degrees(-45,125),
-170 = angle_sub_degrees(-45,145),
-118.1184 = angle_sub_degrees( 29.4803,-88.6381),
-139.583283124=angle_sub_degrees(-70099.742338109,29840.674378767),
-72.343918514=angle_sub_degrees( -165313.66662974,33693.989451746),
-161.50295231=angle_sub_degrees( 1174.8380510598,-154146.66490125),
37.298855589=angle_sub_degrees( 60175.773067955,42213.071923544),
passed.
|
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
| #GAP | GAP | IsDeranged := function(a, b)
local i, n;
for i in [1 .. Size(a)] do
if a[i] = b[i] then
return false;
fi;
od;
return true;
end;
# This solution will find all deranged pairs of any length.
Deranged := function(name)
local sol, ana, u, v;
sol := [ ];
ana := Anagrams(name);
for u in ana do
for v in Combinations(u, 2) do
if IsDeranged(v[1], v[2]) then
Add(sol, v);
fi;
od;
od;
return sol;
end;
# Now we find all deranged pairs of maximum length
a := Deranged("unixdict.txt");;
n := Maximum(List(a, x -> Size(x[1])));
Filtered(a, x -> Size(x[1]) = n);
# [ [ "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.
| #Falcon | Falcon | function fib(x)
if x < 0
raise ParamError(description|"Negative argument invalid", extra|"Fibbonacci sequence is undefined for negative numbers")
else
return (function(y)
if y == 0
return 0
elif y == 1
return 1
else
return fself(y-1) + fself(y-2)
end
end)(x)
end
end
try
>fib(2)
>fib(3)
>fib(4)
>fib(-1)
catch in e
> e
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[NormalizeAngle, NormalizeDegree, NormalizeGradian, NormalizeMil, NormalizeRadian]
NormalizeAngle[d_, full_] := Module[{a = d},
If[Abs[a/full] > 4,
a = a - Sign[a] full (Quotient[Abs[a], full] - 4)
];
While[a < -full, a += full];
While[a > full, a -= full];
a
]
ClearAll[Degree2Gradian, Degree2Mil, Degree2Radian, Gradian2Degree, Gradian2Mil, Gradian2Radian, Mil2Degree, Mil2Gradian, Mil2Radian, Radian2Degree, Radian2Gradian, Radian2Mil]
NormalizeDegree[d_] := NormalizeAngle[d, 360]
NormalizeGradian[d_] := NormalizeAngle[d, 400]
NormalizeMil[d_] := NormalizeAngle[d, 6400]
NormalizeRadian[d_] := NormalizeAngle[d, 2 Pi]
Degree2Gradian[d_] := d 400/360
Degree2Mil[d_] := d 6400/360
Degree2Radian[d_] := d Pi/180
Gradian2Degree[d_] := d 360/400
Gradian2Mil[d_] := d 6400/400
Gradian2Radian[d_] := d 2 Pi/400
Mil2Degree[d_] := d 360/6400
Mil2Gradian[d_] := d 400/6400
Mil2Radian[d_] := d 2 Pi/6400
Radian2Degree[d_] := d 180/Pi
Radian2Gradian[d_] := d 400/(2 Pi)
Radian2Mil[d_] := d 6400/(2 Pi)
MapThread[Construct, {{Degree2Gradian, Degree2Mil, Degree2Radian,
Gradian2Degree, Gradian2Mil, Gradian2Radian, Mil2Degree,
Mil2Gradian, Mil2Radian, Radian2Degree, Radian2Gradian,
Radian2Mil}, {-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399,
6399, 1000000}}] |
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.
| #Common_Lisp | Common Lisp | (let ((cache (make-hash-table)))
(defun sum-proper-divisors (n)
(or (gethash n cache)
(setf (gethash n cache)
(loop for x from 1 to (/ n 2)
when (zerop (rem n x))
sum x)))))
(defun amicable-pairs-up-to (n)
(loop for x from 1 to n
for sum-divs = (sum-proper-divisors x)
when (and (< x sum-divs) (= x (sum-proper-divisors sum-divs)))
collect (list x sum-divs)))
(amicable-pairs-up-to 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
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.
| #HicEst | HicEst | CHARACTER string="Hello World! "
WINDOW(WINdowhandle=wh, Height=1, X=1, TItle="left/right click to rotate left/right, Y-click-position sets milliseconds period")
AXIS(WINdowhandle=wh, PoinT=20, X=2048, Y, Title='ms', MiN=0, MaX=400, MouSeY=msec, MouSeCall=Mouse_callback, MouSeButton=button_type)
direction = 4
msec = 100 ! initial milliseconds
DO tic = 1, 1E20
WRITE(WIN=wh, Align='Center Vertical') string
IF(direction == 4) string = string(LEN(string)) // string ! rotate left
IF(direction == 8) string = string(2:) // string(1) ! rotate right
WRITE(StatusBar, Name) tic, direction, msec
SYSTEM(WAIT=msec)
ENDDO
END
SUBROUTINE Mouse_callback()
direction = button_type ! 4 == left button up, 8 == right button up
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.
| #EasyLang | EasyLang | on animate
clear
move 50 50
circle 1
x = 50 + 40 * sin ang
y = 50 - 40 * cos ang
line x y
circle 5
vel += sin ang / 5
ang += vel
.
ang = 45 |
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.
| #C.23 | C# | using System;
using BI = System.Numerics.BigInteger;
using static System.Console;
class Program {
static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }
static string dump(int digs, bool show = false) {
int gb = 1, dg = ++digs + gb, z;
BI t1 = 1, t2 = 9, t3 = 1, te, su = 0,
t = BI.Pow(10, dg <= 60 ? 0 : dg - 60), d = -1, fn = 1;
for (BI n = 0; n < dg; n++) {
if (n > 0) t3 *= BI.Pow(n, 6);
te = t1 * t2 / t3;
if ((z = dg - 1 - (int)n * 6) > 0) te *= BI.Pow (10, z);
else te /= BI.Pow (10, -z);
if (show && n < 10)
WriteLine("{0,2} {1,62}", n, te * 32 / 3 / t);
su += te; if (te < 10) {
if (show) WriteLine("\n{0} iterations required for {1} digits " +
"after the decimal point.\n", n, --digs); break; }
for (BI j = n * 6 + 1; j <= n * 6 + 6; j++) t1 *= j;
t2 += 126 + 532 * (d += 2);
}
string s = string.Format("{0}", isqrt(BI.Pow(10, dg * 2 + 3) /
su / 32 * 3 * BI.Pow((BI)10, dg + 5)));
return s[0] + "." + s.Substring(1, digs); }
static void Main(string[] args) {
WriteLine(dump(70, true)); }
} |
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
| #Erlang | Erlang |
-module(bearings).
%% API
-export([angle_sub_degrees/2,test/0]).
-define(RealAngleMultiplier,16#10000000000).
-define(DegreesPerTurn,360).
-define(Precision,9).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% @spec
%% @end
%%--------------------------------------------------------------------
%%
angle_sub_degrees(B1,B2) when is_integer(B1), is_integer(B2) ->
angle_sub(B2-B1,?DegreesPerTurn);
angle_sub_degrees(B1,B2) ->
NewB1 = trunc(B1*?RealAngleMultiplier),
NewB2 = trunc(B2*?RealAngleMultiplier),
round(angle_sub(NewB2 - NewB1,
?DegreesPerTurn*?RealAngleMultiplier)
/?RealAngleMultiplier,?Precision).
%%%===================================================================
%%% Internal functions
%%%===================================================================
%% delta normalises the angle difference. Consider a turn from 350 degrees
%% to 20 degrees. Subtraction results in 330 degress. This is equivalent of
%% a turn in the other direction of 30 degrees, thus 330 degrees is equal
%% to -30 degrees.
angle_sub(Value,TurnSize) ->
NormalisedValue = Value rem TurnSize,
minimise_angle(NormalisedValue,TurnSize).
% X rem Turn result in 0..Turn for X > 0 and -Turn..0 for X < 0
% specification requires -Turn/2 < X < Turn/2. This is achieved
% by adding or removing a turn as required.
% bsr 1 divides an integer by 2
minimise_angle(Angle,Turn) when Angle + (Turn bsr 1) < 0 ->
Angle+Turn;
minimise_angle(Angle,Turn) when Angle - (Turn bsr 1) > 0 ->
Angle-Turn;
minimise_angle(Angle,_) ->
Angle.
round(Number,Precision) ->
P = math:pow(10,Precision),
round(Number*P)/P.
test() ->
25 = angle_sub_degrees(20,45),
90 = angle_sub_degrees(-45,45),
175 = angle_sub_degrees(-85,90),
-175 = angle_sub_degrees(-95,90),
170 = angle_sub_degrees(-45,125),
-170 = angle_sub_degrees(-45,145),
-118.1184 = angle_sub_degrees( 29.4803,-88.6381),
-139.583283124=angle_sub_degrees(-70099.742338109,29840.674378767),
-72.343918514=angle_sub_degrees( -165313.66662974,33693.989451746),
-161.50295231=angle_sub_degrees( 1174.8380510598,-154146.66490125),
37.298855589=angle_sub_degrees( 60175.773067955,42213.071923544),
passed.
|
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
| #Go | Go | package main
import (
"fmt"
"io/ioutil"
"strings"
"sort"
)
func deranged(a, b string) bool {
if len(a) != len(b) {
return false
}
for i := range(a) {
if a[i] == b[i] { return false }
}
return true
}
func main() {
/* read the whole thing in. how big can it be? */
buf, _ := ioutil.ReadFile("unixdict.txt")
words := strings.Split(string(buf), "\n")
m := make(map[string] []string)
best_len, w1, w2 := 0, "", ""
for _, w := range(words) {
// don't bother: too short to beat current record
if len(w) <= best_len { continue }
// save strings in map, with sorted string as key
letters := strings.Split(w, "")
sort.Strings(letters)
k := strings.Join(letters, "")
if _, ok := m[k]; !ok {
m[k] = []string { w }
continue
}
for _, c := range(m[k]) {
if deranged(w, c) {
best_len, w1, w2 = len(w), c, w
break
}
}
m[k] = append(m[k], w)
}
fmt.Println(w1, w2, ": Length", best_len)
} |
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.
| #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION Fibonacci(n)
IF n < 0 THEN
RETURN "Nuts!"
ELSE
RETURN Fib(n)
END IF
FUNCTION Fib(m)
IF m < 2 THEN
Fib = m
ELSE
Fib = Fib(m - 1) + Fib(m - 2)
END IF
END FUNCTION
END FUNCTION
PRINT Fibonacci(-1.5)
PRINT Fibonacci(1.5)
PRINT Fibonacci(13.666)
PAUSE |
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
| #Nim | Nim | import math
import strformat
const Values = [float -2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000]
func d2d(x: float): float {.inline.} = x mod 360
func g2g(x: float): float {.inline.} = x mod 400
func m2m(x: float): float {.inline.} = x mod 6400
func r2r(x: float): float {.inline.} = x mod (2 * Pi)
func d2g(x: float): float {.inline.} = d2d(x) * 10 / 9
func d2m(x: float): float {.inline.} = d2d(x) * 160 / 9
func d2r(x: float): float {.inline.} = d2d(x) * Pi / 180
func g2d(x: float): float {.inline.} = g2g(x) * 9 / 10
func g2m(x: float): float {.inline.} = g2g(x) * 16
func g2r(x: float): float {.inline.} = g2g(x) * Pi / 200
func m2d(x: float): float {.inline.} = m2m(x) * 9 / 160
func m2g(x: float): float {.inline.} = m2m(x) / 16
func m2r(x: float): float {.inline.} = m2m(x) * Pi / 3200
func r2d(x: float): float {.inline.} = r2r(x) * 180 / Pi
func r2g(x: float): float {.inline.} = r2r(x) * 200 / Pi
func r2m(x: float): float {.inline.} = r2r(x) * 3200 / Pi
# Normalizing and converting degrees.
echo " Degrees Normalized Gradians Mils Radians"
echo "———————————————————————————————————————————————————————————————————————————————————"
for val in Values:
echo fmt"{val:15.7f} {d2d(val):15.7f} {d2g(val):15.7f} {d2m(val):15.7f} {d2r(val):15.7f}"
# Normalizing and converting gradians.
echo ""
echo " Gradians Normalized Degrees Mils Radians"
echo "———————————————————————————————————————————————————————————————————————————————————"
for val in Values:
echo fmt"{val:15.7f} {g2g(val):15.7f} {g2d(val):15.7f} {g2m(val):15.7f} {g2r(val):15.7f}"
# Normalizing and converting mils.
echo ""
echo " Mils Normalized Degrees Gradians Radians"
echo "———————————————————————————————————————————————————————————————————————————————————"
for val in Values:
echo fmt"{val:15.7f} {m2m(val):15.7f} {m2d(val):15.7f} {m2g(val):15.7f} {m2r(val):15.7f}"
# Normalizing and converting radians.
echo ""
echo " Radians Normalized Degrees Gradians Mils"
echo "———————————————————————————————————————————————————————————————————————————————————"
for val in Values:
echo fmt"{val:15.7f} {r2r(val):15.7f} {r2d(val):15.7f} {r2g(val):15.7f} {r2m(val):15.7f}" |
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use POSIX 'fmod';
my $tau = 2 * 4*atan2(1, 1);
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 %cvt;
for my $a (@units) {
for my $b (@units) {
$cvt{ "${$a}{code}2${$b}{code}" } = sub {
my($angle) = shift;
my $norm = fmod($angle,${$a}{number}); # built-in '%' returns only integers
$norm -= ${$a}{number} if $angle < 0;
$norm * ${$b}{number} / ${$a}{number}
}
}
}
printf '%s'. '%12s'x4 . "\n", ' Angle Unit ', <Degrees Gradians Mills Radians>;
for my $angle (-2, -1, 0, 1, 2, $tau, 16, 360/$tau, 360-1, 400-1, 6400-1, 1_000_000) {
print "\n";
for my $from (@units) {
my @sub_keys = map { "${$from}{code}2${$_}{code}" } @units;
my @results = map { &{$cvt{$_}}($angle) } @sub_keys;
printf '%10g %-8s' . '%12g'x4 . "\n", $angle, ${$from}{name}, @results;
}
} |
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.
| #Cowgol | Cowgol | include "cowgol.coh";
const LIMIT := 20000;
# Calculate sums of proper divisors
var divSum: uint16[LIMIT + 1];
var i: @indexof divSum;
var j: @indexof divSum;
i := 2;
while i <= LIMIT loop
divSum[i] := 1;
i := i + 1;
end loop;
i := 2;
while i <= LIMIT/2 loop
j := i * 2;
while j <= LIMIT loop
divSum[j] := divSum[j] + i;
j := j + i;
end loop;
i := i + 1;
end loop;
# Test each pair
i := 2;
while i <= LIMIT loop
j := i + 1;
while j <= LIMIT loop
if divSum[i] == j and divSum[j] == i then
print_i32(i as uint32);
print(", ");
print_i32(j as uint32);
print_nl();
end if;
j := j + 1;
end loop;
i := i + 1;
end loop; |
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.
| #Icon_and_Unicon | Icon and Unicon | import gui
$include "guih.icn"
class WindowApp : Dialog (label, direction)
method rotate_left (msg)
return msg[2:0] || msg[1]
end
method rotate_right (msg)
return msg[-1:0] || msg[1:-1]
end
method reverse_direction ()
direction := 1-direction
end
# this method gets called by the ticker, and updates the label
method tick ()
static msg := "Hello World! "
if direction = 0
then msg := rotate_left (msg)
else msg := rotate_right (msg)
label.set_label(msg)
end
method component_setup ()
direction := 1 # start off rotating to the right
label := Label("label=Hello World! ", "pos=0,0")
# respond to a mouse click on the label
label.connect (self, "reverse_direction", MOUSE_RELEASE_EVENT)
add (label)
connect (self, "dispose", CLOSE_BUTTON_EVENT)
# tick every 100ms
self.set_ticker (100)
end
end
# create and show the window
procedure main ()
w := WindowApp ()
w.show_modal ()
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.
| #Elm | Elm | import Color exposing (..)
import Collage exposing (..)
import Element exposing (..)
import Html exposing (..)
import Time exposing (..)
import Html.App exposing (program)
dt = 0.01
scale = 100
type alias Model =
{ angle : Float
, angVel : Float
, length : Float
, gravity : Float
}
type Msg
= Tick Time
init : (Model,Cmd Msg)
init =
( { angle = 3 * pi / 4
, angVel = 0.0
, length = 2
, gravity = -9.81
}
, Cmd.none)
update : Msg -> Model -> (Model, Cmd Msg)
update _ model =
let
angAcc = -1.0 * (model.gravity / model.length) * sin (model.angle)
angVel' = model.angVel + angAcc * dt
angle' = model.angle + angVel' * dt
in
( { model
| angle = angle'
, angVel = angVel'
}
, Cmd.none )
view : Model -> Html Msg
view model =
let
endPoint = ( 0, scale * model.length )
pendulum =
group
[ segment ( 0, 0 ) endPoint
|> traced { defaultLine | width = 2, color = red }
, circle 8
|> filled blue
, ngon 3 10
|> filled green
|> rotate (pi/2)
|> move endPoint
]
in
toHtml <|
collage 700 500
[ pendulum |> rotate model.angle ]
subscriptions : Model -> Sub Msg
subscriptions _ =
Time.every (dt * second) Tick
main =
program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
} |
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.
| #C.2B.2B | C++ | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/gmp.hpp>
#include <iomanip>
#include <iostream>
namespace mp = boost::multiprecision;
using big_int = mp::mpz_int;
using big_float = mp::cpp_dec_float_100;
using rational = mp::mpq_rational;
big_int factorial(int n) {
big_int result = 1;
for (int i = 2; i <= n; ++i)
result *= i;
return result;
}
// Return the integer portion of the nth term of Almkvist-Giullera sequence.
big_int almkvist_giullera(int n) {
return factorial(6 * n) * 32 * (532 * n * n + 126 * n + 9) /
(pow(factorial(n), 6) * 3);
}
int main() {
std::cout << "n | Integer portion of nth term\n"
<< "------------------------------------------------\n";
for (int n = 0; n < 10; ++n)
std::cout << n << " | " << std::setw(44) << almkvist_giullera(n)
<< '\n';
big_float epsilon(pow(big_float(10), -70));
big_float prev = 0, pi = 0;
rational sum = 0;
for (int n = 0;; ++n) {
rational term(almkvist_giullera(n), pow(big_int(10), 6 * n + 3));
sum += term;
pi = sqrt(big_float(1 / sum));
if (abs(pi - prev) < epsilon)
break;
prev = pi;
}
std::cout << "\nPi to 70 decimal places is:\n"
<< std::fixed << std::setprecision(70) << pi << '\n';
} |
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
| #Excel | Excel | ANGLEBETWEENBEARINGS
=LAMBDA(ab,
DEGREES(
BEARINGDELTA(
RADIANS(ab)
)
)
)
BEARINGDELTA
=LAMBDA(ab,
LET(
sinab, SIN(ab),
cosab, COS(ab),
ax, INDEX(sinab, 1),
bx, INDEX(sinab, 2),
ay, INDEX(cosab, 1),
by, INDEX(cosab, 2),
rem, "Sign * dot product",
IF(0 < ((ay * bx) - (by * ax)),
1,
-1
) * ACOS((ax * bx) + (ay * by))
)
) |
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
| #Groovy | Groovy | def map = new TreeMap<Integer,Map<String,List<String>>>()
new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt').eachLine { word ->
def size = - word.size()
map[size] = map[size] ?: new TreeMap<String,List<String>>()
def norm = word.toList().sort().sum()
map[size][norm] = map[size][norm] ?: []
map[size][norm] << word
}
def result = map.findResult { negasize, normMap ->
def size = - negasize
normMap.findResults { x, anagrams ->
def n = anagrams.size()
(0..<(n-1)).findResults { i ->
((i+1)..<n).findResult { j ->
(0..<size).every { k -> anagrams[i][k] != anagrams[j][k] } \
? anagrams[i,j]
: null
}
}?.flatten() ?: null
}?.flatten() ?: null
}
if (result) {
println "Longest deranged anagram pair: ${result}"
} else {
println 'Deranged anagrams are a MYTH!'
} |
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.
| #Forth | Forth | :noname ( n -- n' )
dup 2 < ?exit
1- dup recurse swap 1- recurse + ; ( xt )
: fib ( +n -- n' )
dup 0< abort" Negative numbers don't exist."
[ ( xt from the :NONAME above ) compile, ] ; |
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
| #Phix | Phix | constant units = {"degrees","gradians","mils","radians"},
turns = {1/360,1/400,1/6400,0.5/PI}
function convert(atom a, integer fdx, tdx)
return remainder(a*turns[fdx],1)/turns[tdx]
end function
constant tests = {-2,-1,0,1,2,2*PI,16,57.2957795,359,399,6399,1000000}
printf(1," angle unit %9s %9s %9s %9s\n",units)
for i=1 to length(tests) do
for fdx=1 to length(units) do
printf(1,"%9g %-8s",{tests[i],units[fdx]})
for tdx=1 to length(units) do
printf(1," %9g",convert(tests[i],fdx,tdx))
end for
puts(1,"\n")
end for
puts(1,"\n")
end for
|
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.
| #Crystal | Crystal |
MX = 524_000_000
N = Math.sqrt(MX).to_u32
x = Array(Int32).new(MX+1, 1)
(2..N).each { |i|
p = i*i
x[p] += i
k = i+i+1
(p+i..MX).step(i) { |j|
x[j] += k
k += 1
}
}
(4..MX).each { |m|
n = x[m]
if n < m && n != 0 && m == x[n]
puts "#{n} #{m}"
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.
| #J | J | coinsert'jgl2' [ require'gl2'
MESSAGE =: 'Hello World! '
TIMER_INTERVAL =: 0.5 * 1000 NB. Milliseconds
DIRECTION =: -1 NB. Initial direction is right -->
ANIM =: noun define
pc anim closeok;pn "Basic Animation in J";
minwh 350 5;
cc isi isigraph flush;
pcenter;pshow;
)
anim_run =: verb def 'wd ANIM,''; ptimer '',":TIMER_INTERVAL' NB. Set form timer
anim_timer =: verb def 'glpaint MESSAGE=: DIRECTION |. MESSAGE' NB. Rotate MESSAGE according to DIRECTION
anim_isi_mbldown=: verb def 'DIRECTION=: - DIRECTION' NB. Reverse direction when user clicks
anim_close =: verb def 'wd ''timer 0; pclose; reset'' ' NB. Shut down timer
anim_isi_paint =: verb define
glclear '' NB. Clear out old drawing
glrgb 255 0 0
gltextcolor''
glfont '"courier new" 36'
gltext MESSAGE
)
anim_run '' |
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.
| #Java | Java | import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
public class Rotate {
private static class State {
private final String text = "Hello World! ";
private int startIndex = 0;
private boolean rotateRight = true;
}
public static void main(String[] args) {
State state = new State();
JLabel label = new JLabel(state.text);
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
state.rotateRight = !state.rotateRight;
}
});
TimerTask task = new TimerTask() {
public void run() {
int delta = state.rotateRight ? 1 : -1;
state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();
label.setText(rotate(state.text, state.startIndex));
}
};
Timer timer = new Timer(false);
timer.schedule(task, 0, 500);
JFrame rot = new JFrame();
rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
rot.add(label);
rot.pack();
rot.setLocationRelativeTo(null);
rot.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
timer.cancel();
}
});
rot.setVisible(true);
}
private static String rotate(String text, int startIdx) {
char[] rotated = new char[text.length()];
for (int i = 0; i < text.length(); i++) {
rotated[i] = text.charAt((i + startIdx) % text.length());
}
return String.valueOf(rotated);
}
} |
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.
| #ERRE | ERRE |
PROGRAM PENDULUM
!
! for rosettacode.org
!
!$KEY
!$INCLUDE="PC.LIB"
PROCEDURE PENDULUM(A,L)
PIVOTX=320
PIVOTY=0
BOBX=PIVOTX+L*500*SIN(a)
BOBY=PIVOTY+L*500*COS(a)
LINE(PIVOTX,PIVOTY,BOBX,BOBY,6,FALSE)
CIRCLE(BOBX+24*SIN(A),BOBY+24*COS(A),27,11)
PAUSE(0.01)
LINE(PIVOTX,PIVOTY,BOBX,BOBY,0,FALSE)
CIRCLE(BOBX+24*SIN(A),BOBY+24*COS(A),27,0)
END PROCEDURE
BEGIN
SCREEN(9)
THETA=40*p/180 ! initial displacement
G=9.81 ! acceleration due to gravity
L=0.5 ! length of pendulum in metres
LINE(0,0,639,0,5,FALSE)
LOOP
PENDULUM(THETA,L)
ACCEL=-G*SIN(THETA)/L/100
SPEED=SPEED+ACCEL/100
THETA=THETA+SPEED
END LOOP
END PROGRAM
|
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.
| #Common_Lisp | Common Lisp | (ql:quickload :computable-reals :silent t)
(use-package :computable-reals)
(setq *print-prec* 70)
(defparameter *iterations* 52)
; factorial using computable-reals multiplication op to keep precision
(defun !r (n)
(let ((p 1))
(loop for i from 2 to n doing (setq p (*r p i)))
p))
; the nth integer term
(defun integral (n)
(let* ((polynomial (+r (*r 532 n n) (*r 126 n) 9))
(numer (*r 32 (!r (*r 6 n)) polynomial))
(denom (*r 3 (expt-r (!r n) 6))))
(/r numer denom)))
; the exponent for 10 in the nth term of the series
(defun power (n) (- 3 (* 6 (1+ n))))
; the nth term of the series
(defun almkvist-giullera (n)
(/r (integral n) (expt-r 10 (abs (power n)))))
; the sum of the first n terms
(defun almkvist-giullera-sigma (n)
(let ((s 0))
(loop for i from 0 to n doing (setq s (+r s (almkvist-giullera i))))
s))
; the approximation to pi after n terms
(defun almkvist-giullera-pi (n)
(sqrt-r (/r 1 (almkvist-giullera-sigma n))))
(format t "~A. ~44A~4A ~A~%" "N" "Integral part of Nth term" "×10^" "=Actual value of Nth term")
(loop for i from 0 to 9 doing
(format t "~&~a. ~44d ~3d " i (integral i) (power i))
(finish-output *standard-output*)
(print-r (almkvist-giullera i) 50 nil))
(format t "~%~%Pi after ~a iterations: " *iterations*)
(print-r (almkvist-giullera-pi *iterations*) *print-prec*)
|
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
| #F.23 | F# | let deltaBearing (b1:double) (b2:double) =
let r = (b2 - b1) % 360.0;
if r > 180.0 then
r - 360.0
elif r < -180.0 then
r + 360.0
else
r
[<EntryPoint>]
let main _ =
printfn "%A" (deltaBearing 20.0 45.0)
printfn "%A" (deltaBearing -45.0 45.0)
printfn "%A" (deltaBearing -85.0 90.0)
printfn "%A" (deltaBearing -95.0 90.0)
printfn "%A" (deltaBearing -45.0 125.0)
printfn "%A" (deltaBearing -45.0 145.0)
printfn "%A" (deltaBearing 29.4803 -88.6381)
printfn "%A" (deltaBearing -78.3251 -159.036)
printfn "%A" (deltaBearing -70099.74233810938 29840.67437876723)
printfn "%A" (deltaBearing -165313.6666297357 33693.9894517456)
printfn "%A" (deltaBearing 1174.8380510598456 -154146.66490124757)
printfn "%A" (deltaBearing 60175.77306795546 42213.07192354373)
0 // return an integer exit code |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.