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/Population_count
|
Population count
|
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
|
#11l
|
11l
|
F popcount(n)
R bin(n).count(‘1’)
print((0.<30).map(i -> popcount(Int64(3) ^ i)))
[Int] evil, odious
V i = 0
L evil.len < 30 | odious.len < 30
V p = popcount(i)
I (p % 2) != 0
odious.append(i)
E
evil.append(i)
i++
print(evil[0.<30])
print(odious[0.<30])
|
http://rosettacode.org/wiki/Polynomial_long_division
|
Polynomial long division
|
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
|
#11l
|
11l
|
F degree(&poly)
L !poly.empty & poly.last == 0
poly.pop()
R poly.len - 1
F poly_div(&n, &D)
V dD = degree(&D)
V dN = degree(&n)
I dD < 0
exit(1)
[Float] q
I dN >= dD
q = [0.0] * dN
L dN >= dD
V d = [0.0] * (dN - dD) [+] D
V mult = n.last / Float(d.last)
q[dN - dD] = mult
d = d.map(coeff -> coeff * @mult)
n = zip(n, d).map((coeffN, coeffd) -> coeffN - coeffd)
dN = degree(&n)
E
q = [0.0]
R (q, n)
print(‘POLYNOMIAL LONG DIVISION’)
V n = [-42.0, 0.0, -12.0, 1.0]
V D = [-3.0, 1.0, 0.0, 0.0]
print(‘ #. / #. =’.format(n, D), end' ‘ ’)
V (q, r) = poly_div(&n, &D)
print(‘ #. remainder #.’.format(q, r))
|
http://rosettacode.org/wiki/Polymorphic_copy
|
Polymorphic copy
|
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Polymorphic_Copy is
package Base is
type T is tagged null record;
type T_ptr is access all T'Class;
function Name (X : T) return String;
end Base;
use Base;
package body Base is
function Name (X : T) return String is
begin
return "T";
end Name;
end Base;
-- The procedure knows nothing about S
procedure Copier (X : T'Class) is
Duplicate : T'Class := X; -- A copy of X
begin
Put_Line ("Copied " & Duplicate.Name); -- Check the copy
end Copier;
-- The function knows nothing about S and creates a copy on the heap
function Clone (X : T'Class) return T_ptr is
begin
return new T'Class(X);
end Copier;
package Derived is
type S is new T with null record;
overriding function Name (X : S) return String;
end Derived;
use Derived;
package body Derived is
function Name (X : S) return String is
begin
return "S";
end Name;
end Derived;
Object_1 : T;
Object_2 : S;
Object_3 : T_ptr := Clone(T);
Object_4 : T_ptr := Clone(S);
begin
Copier (Object_1);
Copier (Object_2);
Put_Line ("Cloned " & Object_3.all.Name);
Put_Line ("Cloned " & Object_4.all.Name);
end Test_Polymorphic_Copy;
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#F.C5.8Drmul.C3.A6
|
Fōrmulæ
|
## plotpoly.gp 1/10/17 aev
## Plotting a polyspiral and writing to the png-file.
## Note: assign variables: rng, d, clr, filename and ttl (before using load command).
## Direction d (-1 clockwise / 1 counter-clockwise)
reset
set terminal png font arial 12 size 640,640
ofn=filename.".png"
set output ofn
unset border; unset xtics; unset ytics; unset key;
set title ttl font "Arial:Bold,12"
set parametric
c=rng*pi; set xrange[-c:c]; set yrange[-c:c];
set dummy t
plot [0:c] t*cos(d*t), t*sin(d*t) lt rgb @clr
set output
|
http://rosettacode.org/wiki/Polynomial_regression
|
Polynomial regression
|
Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#ALGOL_68
|
ALGOL 68
|
MODE FIELD = REAL;
MODE
VEC = [0]FIELD,
MAT = [0,0]FIELD;
PROC VOID raise index error := VOID: (
print(("stop", new line));
stop
);
COMMENT from http://rosettacode.org/wiki/Matrix_Transpose#ALGOL_68 END COMMENT
OP ZIP = ([,]FIELD in)[,]FIELD:(
[2 LWB in:2 UPB in,1 LWB in:1UPB in]FIELD out;
FOR i FROM LWB in TO UPB in DO
out[,i]:=in[i,]
OD;
out
);
COMMENT from http://rosettacode.org/wiki/Matrix_multiplication#ALGOL_68 END COMMENT
OP * = (VEC a,b)FIELD: ( # basically the dot product #
FIELD result:=0;
IF LWB a/=LWB b OR UPB a/=UPB b THEN raise index error FI;
FOR i FROM LWB a TO UPB a DO result+:= a[i]*b[i] OD;
result
);
OP * = (VEC a, MAT b)VEC: ( # overload vector times matrix #
[2 LWB b:2 UPB b]FIELD result;
IF LWB a/=LWB b OR UPB a/=UPB b THEN raise index error FI;
FOR j FROM 2 LWB b TO 2 UPB b DO result[j]:=a*b[,j] OD;
result
);
OP * = (MAT a, b)MAT: ( # overload matrix times matrix #
[LWB a:UPB a, 2 LWB b:2 UPB b]FIELD result;
IF 2 LWB a/=LWB b OR 2 UPB a/=UPB b THEN raise index error FI;
FOR k FROM LWB result TO UPB result DO result[k,]:=a[k,]*b OD;
result
);
COMMENT from http://rosettacode.org/wiki/Pyramid_of_numbers#ALGOL_68 END COMMENT
OP / = (VEC a, MAT b)VEC: ( # vector division #
[LWB a:UPB a,1]FIELD transpose a;
transpose a[,1]:=a;
(transpose a/b)[,1]
);
OP / = (MAT a, MAT b)MAT:( # matrix division #
[LWB b:UPB b]INT p ;
INT sign;
[,]FIELD lu = lu decomp(b, p, sign);
[LWB a:UPB a, 2 LWB a:2 UPB a]FIELD out;
FOR col FROM 2 LWB a TO 2 UPB a DO
out[,col] := lu solve(b, lu, p, a[,col]) [@LWB out[,col]]
OD;
out
);
FORMAT int repr = $g(0)$,
real repr = $g(-7,4)$;
PROC fit = (VEC x, y, INT order)VEC:
BEGIN
[0:order, LWB x:UPB x]FIELD a; # the plane #
FOR i FROM 2 LWB a TO 2 UPB a DO
FOR j FROM LWB a TO UPB a DO
a [j, i] := x [i]**j
OD
OD;
( y * ZIP a ) / ( a * ZIP a )
END # fit #;
PROC print polynomial = (VEC x)VOID: (
BOOL empty := TRUE;
FOR i FROM UPB x BY -1 TO LWB x DO
IF x[i] NE 0 THEN
IF x[i] > 0 AND NOT empty THEN print ("+") FI;
empty := FALSE;
IF x[i] NE 1 OR i=0 THEN
IF ENTIER x[i] = x[i] THEN
printf((int repr, x[i]))
ELSE
printf((real repr, x[i]))
FI
FI;
CASE i+1 IN
SKIP,print(("x"))
OUT
printf(($"x**"g(0)$,i))
ESAC
FI
OD;
IF empty THEN print("0") FI;
print(new line)
);
fitting: BEGIN
VEC c =
fit
( (0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0),
(1.0, 6.0, 17.0, 34.0, 57.0, 86.0, 121.0, 162.0, 209.0, 262.0, 321.0),
2
);
print polynomial(c);
VEC d =
fit
( (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0),
2
);
print polynomial(d)
END # fitting #
|
http://rosettacode.org/wiki/Power_set
|
Power set
|
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
|
#APL
|
APL
|
ps←(↓∘⍉(2/⍨≢)⊤(⍳2*≢))(/¨)⊂
|
http://rosettacode.org/wiki/Primality_by_trial_division
|
Primality by trial division
|
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Ada
|
Ada
|
function Is_Prime(Item : Positive) return Boolean is
Test : Natural;
begin
if Item = 1 then
return False;
elsif Item = 2 then
return True;
elsif Item mod 2 = 0 then
return False;
else
Test := 3;
while Test <= Integer(Sqrt(Float(Item))) loop
if Item mod Test = 0 then
return False;
end if;
Test := Test + 2;
end loop;
end if;
return True;
end Is_Prime;
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#BASIC256
|
BASIC256
|
arraybase 1
dim byValue = {10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100}
dim byLimit = {6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96}
for byCount = 1 to 100
for byCheck = 0 to byLimit[?]
if byCount < byLimit[byCheck] then exit for
next byCheck
print ljust((byCount/100),4," "); " -> "; ljust((byValue[byCheck]/100),4," "); chr(9);
if byCount mod 5 = 0 then print
next byCount
end
|
http://rosettacode.org/wiki/Proper_divisors
|
Proper divisors
|
The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#Eiffel
|
Eiffel
|
class
APPLICATION
create
make
feature
make
-- Test the feature proper_divisors.
local
list: LINKED_LIST [INTEGER]
count, number: INTEGER
do
across
1 |..| 10 as c
loop
list := proper_divisors (c.item)
io.put_string (c.item.out + ": ")
across
list as l
loop
io.put_string (l.item.out + " ")
end
io.new_line
end
across
1 |..| 20000 as c
loop
list := proper_divisors (c.item)
if list.count > count then
count := list.count
number := c.item
end
end
io.put_string (number.out + " has with " + count.out + " divisors the highest number of proper divisors.")
end
proper_divisors (n: INTEGER): LINKED_LIST [INTEGER]
-- Proper divisors of 'n'.
do
create Result.make
across
1 |..| (n - 1) as c
loop
if n \\ c.item = 0 then
Result.extend (c.item)
end
end
end
end
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#Go
|
Go
|
package main
import (
"fmt"
"math/rand"
"time"
)
type mapping struct {
item string
pr float64
}
func main() {
// input mapping
m := []mapping{
{"aleph", 1 / 5.},
{"beth", 1 / 6.},
{"gimel", 1 / 7.},
{"daleth", 1 / 8.},
{"he", 1 / 9.},
{"waw", 1 / 10.},
{"zayin", 1 / 11.},
{"heth", 1759 / 27720.}} // adjusted so that probabilities add to 1
// cumulative probability
cpr := make([]float64, len(m)-1)
var c float64
for i := 0; i < len(m)-1; i++ {
c += m[i].pr
cpr[i] = c
}
// generate
const samples = 1e6
occ := make([]int, len(m))
rand.Seed(time.Now().UnixNano())
for i := 0; i < samples; i++ {
r := rand.Float64()
for j := 0; ; j++ {
if r < cpr[j] {
occ[j]++
break
}
if j == len(cpr)-1 {
occ[len(cpr)]++
break
}
}
}
// report
fmt.Println(" Item Target Generated")
var totalTarget, totalGenerated float64
for i := 0; i < len(m); i++ {
target := m[i].pr
generated := float64(occ[i]) / samples
fmt.Printf("%6s %8.6f %8.6f\n", m[i].item, target, generated)
totalTarget += target
totalGenerated += generated
}
fmt.Printf("Totals %8.6f %8.6f\n", totalTarget, totalGenerated)
}
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#Factor
|
Factor
|
<min-heap> [ {
{ 3 "Clear drains" }
{ 4 "Feed cat" }
{ 5 "Make tea" }
{ 1 "Solve RC tasks" }
{ 2 "Tax return" }
} swap heap-push-all
] [
[ print ] slurp-heap
] bi
|
http://rosettacode.org/wiki/Problem_of_Apollonius
|
Problem of Apollonius
|
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#Perl
|
Perl
|
use utf8;
use Math::Cartesian::Product;
package Circle;
sub new {
my ($class, $args) = @_;
my $self = {
x => $args->{x},
y => $args->{y},
r => $args->{r},
};
bless $self, $class;
}
sub show {
my ($self, $args) = @_;
sprintf "x =%7.3f y =%7.3f r =%7.3f\n", $args->{x}, $args->{y}, $args->{r};
}
package main;
sub circle {
my($x,$y,$r) = @_;
Circle->new({ x => $x, y=> $y, r => $r });
}
sub solve_Apollonius {
my($c1, $c2, $c3, $s1, $s2, $s3) = @_;
my $𝑣11 = 2 * $c2->{x} - 2 * $c1->{x};
my $𝑣12 = 2 * $c2->{y} - 2 * $c1->{y};
my $𝑣13 = $c1->{x}**2 - $c2->{x}**2 + $c1->{y}**2 - $c2->{y}**2 - $c1->{r}**2 + $c2->{r}**2;
my $𝑣14 = 2 * $s2 * $c2->{r} - 2 * $s1 * $c1->{r};
my $𝑣21 = 2 * $c3->{x} - 2 * $c2->{x};
my $𝑣22 = 2 * $c3->{y} - 2 * $c2->{y};
my $𝑣23 = $c2->{x}**2 - $c3->{x}**2 + $c2->{y}**2 - $c3->{y}**2 - $c2->{r}**2 + $c3->{r}**2;
my $𝑣24 = 2 * $s3 * $c3->{r} - 2 * $s2 * $c2->{r};
my $𝑤12 = $𝑣12 / $𝑣11;
my $𝑤13 = $𝑣13 / $𝑣11;
my $𝑤14 = $𝑣14 / $𝑣11;
my $𝑤22 = $𝑣22 / $𝑣21 - $𝑤12;
my $𝑤23 = $𝑣23 / $𝑣21 - $𝑤13;
my $𝑤24 = $𝑣24 / $𝑣21 - $𝑤14;
my $𝑃 = -$𝑤23 / $𝑤22;
my $𝑄 = $𝑤24 / $𝑤22;
my $𝑀 = -$𝑤12 * $𝑃 - $𝑤13;
my $𝑁 = $𝑤14 - $𝑤12 * $𝑄;
my $𝑎 = $𝑁**2 + $𝑄**2 - 1;
my $𝑏 = 2 * $𝑀 * $𝑁 - 2 * $𝑁 * $c1->{x} + 2 * $𝑃 * $𝑄 - 2 * $𝑄 * $c1->{y} + 2 * $s1 * $c1->{r};
my $𝑐 = $c1->{x}**2 + $𝑀**2 - 2 * $𝑀 * $c1->{x} + $𝑃**2 + $c1->{y}**2 - 2 * $𝑃 * $c1->{y} - $c1->{r}**2;
my $𝐷 = $𝑏**2 - 4 * $𝑎 * $𝑐;
my $rs = (-$𝑏 - sqrt $𝐷) / (2 * $𝑎);
my $xs = $𝑀 + $𝑁 * $rs;
my $ys = $𝑃 + $𝑄 * $rs;
circle($xs, $ys, $rs);
}
$c1 = circle(0, 0, 1);
$c2 = circle(4, 0, 1);
$c3 = circle(2, 4, 2);
for (cartesian {@_} ([-1,1])x3) {
print Circle->show( solve_Apollonius $c1, $c2, $c3, @$_);
}
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Racket
|
Racket
|
#!/usr/bin/env racket
#lang racket
(define (program) (find-system-path 'run-file))
(module+ main (printf "Program: ~a\n" (program)))
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Raku
|
Raku
|
say $*PROGRAM-NAME;
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#PowerShell
|
PowerShell
|
function triples($p) {
if($p -gt 4) {
# ai + bi + ci = pi <= p
# ai < bi < ci --> 3ai < pi <= p and ai + 2bi < pi <= p
$pa = [Math]::Floor($p/3)
1..$pa | foreach {
$ai = $_
$pb = [Math]::Floor(($p-$ai)/2)
($ai+1)..$pb | foreach {
$bi = $_
$pc = $p-$ai-$bi
($bi+1)..$pc | where {
$ci = $_
$pi = $ai + $bi + $ci
$ci*$ci -eq $ai*$ai + $bi*$bi
} |
foreach {
[pscustomobject]@{
a = "$ai"
b = "$bi"
c = "$ci"
p = "$pi"
}
}
}
}
}
else {
Write-Error "$p is not greater than 4"
}
}
function gcd ($a, $b) {
function pgcd ($n, $m) {
if($n -le $m) {
if($n -eq 0) {$m}
else{pgcd $n ($m%$n)}
}
else {pgcd $m $n}
}
$n = [Math]::Abs($a)
$m = [Math]::Abs($b)
(pgcd $n $m)
}
$triples = (triples 100)
$coprime = $triples |
where {((gcd $_.a $_.b) -eq 1) -and ((gcd $_.a $_.c) -eq 1) -and ((gcd $_.b $_.c) -eq 1)}
"There are $(($triples).Count) Pythagorean triples with perimeter no larger than 100
and $(($coprime).Count) of them are coprime."
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Phix
|
Phix
|
if error_code!=NO_ERROR then
abort(0)
end if
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Phixmonti
|
Phixmonti
|
if 1 quit endif
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#Haskell
|
Haskell
|
import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Pascal
|
Pascal
|
program primCons;
{$IFNDEF FPC}
{$APPTYPE CONSOLE}
{$ENDIF}
const
PrimeLimit = 2038074748 DIV 2;
type
tLimit = 0..PrimeLimit;
tCntTransition = array[0..9,0..9] of NativeInt;
tCntTransRec = record
CTR_CntTrans:tCntTransition;
CTR_primCnt,
CTR_Limit : NativeInt;
end;
tCntTransRecField = array[0..19] of tCntTransRec;
var
primes: array [tLimit] of boolean;
CntTransitions : tCntTransRecField;
procedure SieveSmall;
//sieve of eratosthenes with only odd numbers
var
i,j,p: NativeInt;
Begin
FillChar(primes[1],SizeOF(primes),chr(ord(true)));
i := 1;
p := 3;
j := i*(i+1)*2;
repeat
IF (primes[i]) then
begin
p := i+i+1;
repeat
primes[j] := false;
inc(j,p);
until j > PrimeLimit;
end;
inc(i);
j := i*(i+1)*2;//position of i*i
IF PrimeLimit < j then
BREAK;
until false;
end;
procedure OutputTransitions(const Trs:tCntTransRecField);
var
i,j,k,res,cnt: NativeInt;
ThereWasOutput: boolean;
Begin
cnt := 0;
while Trs[cnt].CTR_primCnt > 0 do
inc(cnt);
dec(cnt);
IF cnt < 0 then
EXIT;
write('PrimCnt ');
For i := 0 to cnt do
write(Trs[i].CTR_primCnt:i+7);
writeln;
For i := 0 to 9 do
Begin
ThereWasOutput := false;
For j := 0 to 9 do
Begin
res := Trs[0].CTR_CntTrans[i,j];
IF res > 0 then
Begin
ThereWasOutput := true;
write('''',i,'''->''',j,'''');
For k := 0 to cnt do
Begin
res := Trs[k].CTR_CntTrans[i,j];
write(res/Trs[k].CTR_primCnt*100:k+6:k+2,'%');
end;
writeln;
end;
end;
IF ThereWasOutput then
writeln;
end;
end;
var
pCntTransOld,
pCntTransNew : ^tCntTransRec;
i,primCnt,lmt : NativeInt;
prvChr,
nxtChr : NativeInt;
Begin
SieveSmall;
pCntTransOld := @CntTransitions[0].CTR_CntTrans;
pCntTransOld^.CTR_CntTrans[2,3]:= 1;
lmt := 10*1000;
//starting at 2 *2+1 => 5
primCnt := 2; // the prime 2,3
prvChr := 3;
nxtChr := prvChr;
for i:= 2 to PrimeLimit do
Begin
inc(nxtChr,2);
if nxtChr >= 10 then nxtChr := 1;
IF primes[i] then
Begin
inc(pCntTransOld^.CTR_CntTrans[prvChr][nxtChr]);
inc(primCnt);
prvchr := nxtChr;
IF primCnt >= lmt then
Begin
with pCntTransOld^ do Begin
CTR_Limit := i;
CTR_primCnt := primCnt;
end;
pCntTransNew := pCntTransOld;
inc(pCntTransNew);
pCntTransNew^:= pCntTransOld^;
pCntTransOld := pCntTransNew;
lmt := lmt*10;
end;
end;
end;
pCntTransOld^.CTR_primCnt := 0;
OutputTransitions(CntTransitions);
end.
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Batch_file
|
Batch file
|
@echo off
::usage: cmd /k primefactor.cmd number
setlocal enabledelayedexpansion
set /a compo=%1
if "%compo%"=="" goto:eof
set list=%compo%= (
set /a div=2 & call :loopdiv
set /a div=3 & call :loopdiv
set /a div=5,inc=2
:looptest
call :loopdiv
set /a div+=inc,inc=6-inc,div2=div*div
if %div2% lss %compo% goto looptest
if %compo% neq 1 set list= %list% %compo%
echo %list%) & goto:eof
:loopdiv
set /a "res=compo%%div
if %res% neq 0 goto:eof
set list=%list% %div%,
set/a compo/=div
goto:loopdiv
|
http://rosettacode.org/wiki/Population_count
|
Population count
|
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
|
#360_Assembly
|
360 Assembly
|
* Population count 09/05/2019
POPCNT CSECT
USING POPCNT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LD F0,UN 1
STD F0,BB bb=1
MVC PG(7),=C'pow 3:' init buffer
L R10,NN nn
BCTR R10,0 nn-1
LA R9,PG+7 @pg
LA R6,0 i=0
DO WHILE=(CR,R6,LE,R10) do i=0 to nn-1
LM R0,R1,BB r0r1=bb
BAL R14,POPCOUNT call popcount(bb)
LR R1,R0 popcount(bb)
XDECO R1,XDEC edit popcount(bb)
MVC 0(3,R9),XDEC+9 output popcount(bb)
LD F0,BB bb
AW F0,BB bb*2
AW F0,BB bb*3
STD F0,BB bb=bb*3
LA R9,3(R9) @pg
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print buffer
SR R7,R7 j=0
DO WHILE=(C,R7,LE,=F'1') do j=0 to 1
MVC PG,=CL132' ' clear buffer
IF LTR,R7,Z,R7 THEN if j=0 then
MVC PG(7),=C'evil: ' init buffer
ELSE , else
MVC PG(7),=C'odious:' init buffer
ENDIF , endif
LA R9,PG+7 @pg
SR R8,R8 n=0
SR R6,R6 i=0
DO WHILE=(C,R8,LT,NN) do i=0 by 1 while(n<nn)
XR R0,R0 r0=0
LR R1,R6 r1=i
BAL R14,POPCOUNT r0=popcount(i)
SRDA R0,32 ~
D R0,=F'2' popcount(i)/2
IF CR,R0,EQ,R7 THEN if popcount(i)//2=j then
LA R8,1(R8) n=n+1
XDECO R6,XDEC edit i
MVC 0(3,R9),XDEC+9 output i
LA R9,3(R9) @pg
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
XPRNT PG,L'PG print buffer
LA R7,1(R7) j++
ENDDO , enddo j
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
*------- ---- ------------------
POPCOUNT EQU * popcount(x)
ICM R0,B'1000',=X'00' zap exponant part
XR R3,R3 y=0
LA R4,56 mantissa size = 56
LOOP STC R1,CC do i=1 to 56
TM CC,X'01' if bit(x,i)=1
BNO NOTONE then{
LA R3,1(R3) y++}
NOTONE SRDA R0,1 shift right double arithmetic
BCT R4,LOOP enddo i
LR R0,R3 return(y)
BR R14 return
*------- ---- ------------------
NN DC F'30' nn=30
BB DS D bb
UN DC X'4E00000000000001' un=1 (unnormalized)
PG DC CL132' ' buffer
XDEC DS CL12 temp for xdeco
CC DS C
REGEQU
END POPCNT
|
http://rosettacode.org/wiki/Polynomial_long_division
|
Polynomial long division
|
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Long_Division is
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
use Int_IO;
type Degrees is range -1 .. Integer'Last;
subtype Valid_Degrees is Degrees range 0 .. Degrees'Last;
type Polynom is array (Valid_Degrees range <>) of Integer;
function Degree (P : Polynom) return Degrees is
begin
for I in reverse P'Range loop
if P (I) /= 0 then
return I;
end if;
end loop;
return -1;
end Degree;
function Shift_Right (P : Polynom; D : Valid_Degrees) return Polynom is
Result : Polynom (0 .. P'Last + D) := (others => 0);
begin
Result (Result'Last - P'Length + 1 .. Result'Last) := P;
return Result;
end Shift_Right;
function "*" (Left : Polynom; Right : Integer) return Polynom is
Result : Polynom (Left'Range);
begin
for I in Result'Range loop
Result (I) := Left (I) * Right;
end loop;
return Result;
end "*";
function "-" (Left, Right : Polynom) return Polynom is
Result : Polynom (Left'Range);
begin
for I in Result'Range loop
if I in Right'Range then
Result (I) := Left (I) - Right (I);
else
Result (I) := Left (I);
end if;
end loop;
return Result;
end "-";
procedure Poly_Long_Division (Num, Denom : Polynom; Q, R : out Polynom) is
N : Polynom := Num;
D : Polynom := Denom;
begin
if Degree (D) < 0 then
raise Constraint_Error;
end if;
Q := (others => 0);
while Degree (N) >= Degree (D) loop
declare
T : Polynom := Shift_Right (D, Degree (N) - Degree (D));
begin
Q (Degree (N) - Degree (D)) := N (Degree (N)) / T (Degree (T));
T := T * Q (Degree (N) - Degree (D));
N := N - T;
end;
end loop;
R := N;
end Poly_Long_Division;
procedure Output (P : Polynom) is
First : Boolean := True;
begin
for I in reverse P'Range loop
if P (I) /= 0 then
if First then
First := False;
else
Put (" + ");
end if;
if I > 0 then
if P (I) /= 1 then
Put (P (I), 0);
Put ("*");
end if;
Put ("x");
if I > 1 then
Put ("^");
Put (Integer (I), 0);
end if;
elsif P (I) /= 0 then
Put (P (I), 0);
end if;
end if;
end loop;
New_Line;
end Output;
Test_N : constant Polynom := (0 => -42, 1 => 0, 2 => -12, 3 => 1);
Test_D : constant Polynom := (0 => -3, 1 => 1);
Test_Q : Polynom (Test_N'Range);
Test_R : Polynom (Test_N'Range);
begin
Poly_Long_Division (Test_N, Test_D, Test_Q, Test_R);
Put_Line ("Dividing Polynoms:");
Put ("N: "); Output (Test_N);
Put ("D: "); Output (Test_D);
Put_Line ("-------------------------");
Put ("Q: "); Output (Test_Q);
Put ("R: "); Output (Test_R);
end Long_Division;
|
http://rosettacode.org/wiki/Polymorphic_copy
|
Polymorphic copy
|
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
|
#Aikido
|
Aikido
|
class T {
public function print {
println ("class T")
}
}
class S extends T {
public function print {
println ("class S")
}
}
var t = new T()
var s = new S()
println ("before copy")
t.print()
s.print()
var tcopy = clone (t, false)
var scopy = clone (s, false)
println ("after copy")
tcopy.print()
scopy.print()
|
http://rosettacode.org/wiki/Polymorphic_copy
|
Polymorphic copy
|
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
|
#ALGOL_68
|
ALGOL 68
|
BEGIN
# Algol 68 doesn't have classes and inheritence as such, however structures #
# can contain procedures and different instances of a structure can have #
# different versons of the procedure #
# this allows us to simulate inheritence by creating structure instances #
# with different procedures #
# the following declares a type (MODE) HORSE with two constructors, one for #
# a standard horse and one for a zebra (the "derived class"). #
# The standard horse has its print procedure set to thw print horse #
# procedure (the "base class" method). zebras get the print zebra procedure #
# (the "derived class" method). A convenience operator (PRINT) is defined #
# to simplify calling the horse/zebra print method of its horse parameter #
# = this PRINT operator is independent of which actual print method the #
# horse has - it just saved typeing "( print OF h )( h )" everywhere we #
# need to call the print method (euivalent to h.print(h) in e.g. C, Java, #
# etc.) #
# "class" #
MODE HORSE = STRUCT( STRING name, PROC(HORSE)VOID print );
# constructors #
PROC new horse = ( STRING name )HORSE: ( name, print horse );
PROC new zebra = ( STRING name )HORSE: ( name, print zebra );
# print methods: one for a standard horse and one for a zebra #
PROC print horse = ( HORSE h )VOID: print( ( "horse: ", name OF h ) );
PROC print zebra = ( HORSE h )VOID: print( ( "zebra: ", name OF h ) );
# print operator #
OP PRINT = ( HORSE h )VOID: ( print OF h )( h );
# declare and construct some horses and zebras #
HORSE h1 := new horse( "silver blaze" );
HORSE z1 := new zebra( "stripy" );
HORSE z2 := new zebra( "second zebra" );
# show their values #
PRINT h1; print( ( newline ) );
PRINT z1; print( ( newline ) );
PRINT z2; print( ( newline ) );
print( ( "----", newline ) );
# change the second zebra to be a copy of the first zebra #
z2 := z1;
PRINT z1; print( ( newline ) );
PRINT z2; print( ( newline ) );
print( ( "----", newline ) );
# change the name of the first zebra leaving z2 unchanged #
name OF z1 := "ed";
PRINT z1; print( ( newline ) );
PRINT z2; print( ( newline ) )
END
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#Gnuplot
|
Gnuplot
|
## plotpoly.gp 1/10/17 aev
## Plotting a polyspiral and writing to the png-file.
## Note: assign variables: rng, d, clr, filename and ttl (before using load command).
## Direction d (-1 clockwise / 1 counter-clockwise)
reset
set terminal png font arial 12 size 640,640
ofn=filename.".png"
set output ofn
unset border; unset xtics; unset ytics; unset key;
set title ttl font "Arial:Bold,12"
set parametric
c=rng*pi; set xrange[-c:c]; set yrange[-c:c];
set dummy t
plot [0:c] t*cos(d*t), t*sin(d*t) lt rgb @clr
set output
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#Go
|
Go
|
$ convert polyspiral.gif -coalesce polyspiral2.gif
$ eog polyspiral2.gif
|
http://rosettacode.org/wiki/Polynomial_regression
|
Polynomial regression
|
Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#AutoHotkey
|
AutoHotkey
|
regression(xa,ya){
n := xa.Count()
xm := ym := x2m := x3m := x4m := xym := x2ym := 0
loop % n {
i := A_Index
xm := xm + xa[i]
ym := ym + ya[i]
x2m := x2m + xa[i] * xa[i]
x3m := x3m + xa[i] * xa[i] * xa[i]
x4m := x4m + xa[i] * xa[i] * xa[i] * xa[i]
xym := xym + xa[i] * ya[i]
x2ym := x2ym + xa[i] * xa[i] * ya[i]
}
xm := xm / n
ym := ym / n
x2m := x2m / n
x3m := x3m / n
x4m := x4m / n
xym := xym / n
x2ym := x2ym / n
sxx := x2m - xm * xm
sxy := xym - xm * ym
sxx2 := x3m - xm * x2m
sx2x2 := x4m - x2m * x2m
sx2y := x2ym - x2m * ym
b := (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
c := (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
a := ym - b * xm - c * x2m
result := "Input`tApproximation`nx y`ty1`n"
loop % n
i := A_Index, result .= xa[i] ", " ya[i] "`t" eval(a, b, c, xa[i]) "`n"
return "y = " c "x^2" " + " b "x + " a "`n`n" result
}
eval(a,b,c,x){
return a + (b + c*x) * x
}
|
http://rosettacode.org/wiki/Power_set
|
Power set
|
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
|
#AppleScript
|
AppleScript
|
-- POWER SET -----------------------------------------------------------------
-- powerset :: [a] -> [[a]]
on powerset(xs)
script subSet
on |λ|(acc, x)
script cons
on |λ|(y)
{x} & y
end |λ|
end script
acc & map(cons, acc)
end |λ|
end script
foldr(subSet, {{}}, xs)
end powerset
-- TEST ----------------------------------------------------------------------
on run
script test
on |λ|(x)
set {setName, setMembers} to x
{setName, powerset(setMembers)}
end |λ|
end script
map(test, [¬
["Set [1,2,3]", {1, 2, 3}], ¬
["Empty set", {}], ¬
["Set containing only empty set", {{}}]])
--> {{"Set [1,2,3]", {{}, {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}}},
--> {"Empty set", {{}}},
--> {"Set containing only empty set", {{}, {{}}}}}
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
|
http://rosettacode.org/wiki/Primality_by_trial_division
|
Primality by trial division
|
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#ALGOL_68
|
ALGOL 68
|
COMMENT
This routine is used in more than one place, and is essentially a
template that can by used for many different types, eg INT, LONG INT...
USAGE
MODE ISPRIMEINT = INT, LONG INT, etc
PR READ "prelude/is_prime.a68" PR
END COMMENT
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#BBC_BASIC
|
BBC BASIC
|
PRINT FNpricefraction(0.5)
END
DEF FNpricefraction(p)
IF p < 0.06 THEN = 0.10
IF p < 0.11 THEN = 0.18
IF p < 0.16 THEN = 0.26
IF p < 0.21 THEN = 0.32
IF p < 0.26 THEN = 0.38
IF p < 0.31 THEN = 0.44
IF p < 0.36 THEN = 0.50
IF p < 0.41 THEN = 0.54
IF p < 0.46 THEN = 0.58
IF p < 0.51 THEN = 0.62
IF p < 0.56 THEN = 0.66
IF p < 0.61 THEN = 0.70
IF p < 0.66 THEN = 0.74
IF p < 0.71 THEN = 0.78
IF p < 0.76 THEN = 0.82
IF p < 0.81 THEN = 0.86
IF p < 0.86 THEN = 0.90
IF p < 0.91 THEN = 0.94
IF p < 0.96 THEN = 0.98
= 1.00
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#Beads
|
Beads
|
beads 1 program 'Price fraction'
record a_table
value
rescaled
const table : array of a_table = [<
value, rescaled
0.06, 0.10
0.11, 0.18
0.16, 0.26
0.21, 0.32
0.26, 0.38
0.31, 0.44
0.36, 0.50
0.41, 0.54
0.46, 0.58
0.51, 0.62
0.56, 0.66
0.61, 0.70
0.66, 0.74
0.71, 0.78
0.76, 0.82
0.81, 0.86
0.86, 0.90
0.91, 0.94
0.96, 0.98
1.01, 1.00 >]
const a_test = [0.05 0.62 0.34 0.93 0.45]
calc main_init
loop across:a_test val:v
loop across:table index:ix
if v < table[ix].value
log "{v} => {table[ix].rescaled}"
exit
|
http://rosettacode.org/wiki/Proper_divisors
|
Proper divisors
|
The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#Elixir
|
Elixir
|
defmodule Proper do
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
defp divisors(k,_n,q) when k>q, do: []
defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q)
defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)]
defp divisors(k,n,q) , do: [k,div(n,k) | divisors(k+1,n,q)]
def most_divisors(limit) do
{length,nums} = Enum.group_by(1..limit, fn n -> length(divisors(n)) end)
|> Enum.max_by(fn {length,_nums} -> length end)
IO.puts "With #{length}, Number #{inspect nums} has the most divisors"
end
end
Enum.each(1..10, fn n ->
IO.puts "#{n}: #{inspect Proper.divisors(n)}"
end)
Proper.most_divisors(20000)
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#Haskell
|
Haskell
|
import System.Random (newStdGen, randomRs)
dataBinCounts :: [Float] -> [Float] -> [Int]
dataBinCounts thresholds range =
let sampleSize = length range
xs = ((-) sampleSize . length . flip filter range . (<)) <$> thresholds
in zipWith (-) (xs ++ [sampleSize]) (0 : xs)
main :: IO ()
main = do
g <- newStdGen
let fractions = recip <$> [5 .. 11] :: [Float]
expected = fractions ++ [1 - sum fractions]
actual =
((/ 1000000.0) . fromIntegral) <$>
dataBinCounts (scanl1 (+) expected) (take 1000000 (randomRs (0, 1) g))
piv n = take n . (++ repeat ' ')
putStrLn " expected actual"
mapM_ putStrLn $
zipWith3
(\l s c -> piv 7 l ++ piv 13 (show s) ++ piv 12 (show c))
["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"]
expected
actual
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#Fortran
|
Fortran
|
module priority_queue_mod
implicit none
type node
character (len=100) :: task
integer :: priority
end type
type queue
type(node), allocatable :: buf(:)
integer :: n = 0
contains
procedure :: top
procedure :: enqueue
procedure :: siftdown
end type
contains
subroutine siftdown(this, a)
class (queue) :: this
integer :: a, parent, child
associate (x => this%buf)
parent = a
do while(parent*2 <= this%n)
child = parent*2
if (child + 1 <= this%n) then
if (x(child+1)%priority > x(child)%priority ) then
child = child +1
end if
end if
if (x(parent)%priority < x(child)%priority) then
x([child, parent]) = x([parent, child])
parent = child
else
exit
end if
end do
end associate
end subroutine
function top(this) result (res)
class(queue) :: this
type(node) :: res
res = this%buf(1)
this%buf(1) = this%buf(this%n)
this%n = this%n - 1
call this%siftdown(1)
end function
subroutine enqueue(this, priority, task)
class(queue), intent(inout) :: this
integer :: priority
character(len=*) :: task
type(node) :: x
type(node), allocatable :: tmp(:)
integer :: i
x%priority = priority
x%task = task
this%n = this%n +1
if (.not.allocated(this%buf)) allocate(this%buf(1))
if (size(this%buf)<this%n) then
allocate(tmp(2*size(this%buf)))
tmp(1:this%n-1) = this%buf
call move_alloc(tmp, this%buf)
end if
this%buf(this%n) = x
i = this%n
do
i = i / 2
if (i==0) exit
call this%siftdown(i)
end do
end subroutine
end module
program main
use priority_queue_mod
type (queue) :: q
type (node) :: x
call q%enqueue(3, "Clear drains")
call q%enqueue(4, "Feed cat")
call q%enqueue(5, "Make Tea")
call q%enqueue(1, "Solve RC tasks")
call q%enqueue(2, "Tax return")
do while (q%n >0)
x = q%top()
print "(g0,a,a)", x%priority, " -> ", trim(x%task)
end do
end program
! Output:
! 5 -> Make Tea
! 4 -> Feed cat
! 3 -> Clear drains
! 2 -> Tax return
! 1 -> Solve RC tasks
|
http://rosettacode.org/wiki/Problem_of_Apollonius
|
Problem of Apollonius
|
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#Phix
|
Phix
|
function Apollonius(sequence calc, circles)
integer {s1,s2,s3} = calc
atom {x1,y1,r1} = circles[1],
{x2,y2,r2} = circles[2],
{x3,y3,r3} = circles[3],
v11 = 2*x2 - 2*x1,
v12 = 2*y2 - 2*y1,
v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2,
v14 = 2*s2*r2 - 2*s1*r1,
v21 = 2*x3 - 2*x2,
v22 = 2*y3 - 2*y2,
v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3,
v24 = 2*s3*r3 - 2*s2*r2,
w12 = v12 / v11,
w13 = v13 / v11,
w14 = v14 / v11,
w22 = v22 / v21 - w12,
w23 = v23 / v21 - w13,
w24 = v24 / v21 - w14,
P = -w23 / w22,
Q = w24 / w22,
M = -w12*P - w13,
N = w14 - w12*Q,
a = N*N + Q*Q - 1,
b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1,
c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1,
d = b*b - 4*a*c,
rs = (-b-sqrt(d)) / (2*a),
xs = M + N*rs,
ys = P + Q*rs
return {xs,ys,rs}
end function
constant circles = {{0,0,1},
{4,0,1},
{2,4,2}}
-- +1: externally tangental, -1: internally tangental
constant calcs = {{+1,+1,+1},
{-1,-1,-1},
{+1,-1,-1},
{-1,+1,-1},
{-1,-1,+1},
{+1,+1,-1},
{-1,+1,+1},
{+1,-1,+1}}
for i=1 to 8 do
atom {xs,ys,rs} = Apollonius(calcs[i],circles)
string th = {"st (external)","nd (internal)","rd","th"}[min(i,4)]
printf(1,"%d%s solution: x=%+f, y=%+f, r=%f\n",{i,th,xs,ys,rs})
end for
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Raven
|
Raven
|
ARGS list " " join "%s\n" print
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#REXX
|
REXX
|
/* Rexx */
Parse source . . pgmPath
Say pgmPath
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#Prolog
|
Prolog
|
show :-
Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000],
forall(
member(Max, Data),
(count_triples(Max, Total, Prim),
format("upto ~D, there are ~D Pythagorean triples (~D primitive.)~n", [Max, Total, Prim]))).
div(A, B, C) :- C is A div B.
count_triples(Max, Total, Prims) :-
findall(S, (triple(Max, A, B, C), S is A + B + C), Ps),
length(Ps, Prims),
maplist(div(Max), Ps, Counts), sumlist(Counts, Total).
% - between_by/4
between_by(A, B, N, K) :-
C is (B - A) div N,
between(0, C, J),
K is N*J + A.
% - Pythagorean triple generator
triple(P, A, B, C) :-
Max is floor(sqrt(P/2)) - 1,
between(0, Max, M),
Start is (M /\ 1) + 1, succ(Pm, M),
between_by(Start, Pm, 2, N),
gcd(M, N) =:= 1,
X is M*M - N*N,
Y is 2*M*N,
C is M*M + N*N,
order2(X, Y, A, B),
(A + B + C) =< P.
order2(A, B, A, B) :- A < B, !.
order2(A, B, B, A).
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#PHP
|
PHP
|
if (problem)
exit(1);
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Picat
|
Picat
|
% ...
if problem then
halt
end,
% ...
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#J
|
J
|
wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#Java
|
Java
|
import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Perl
|
Perl
|
use ntheory qw/forprimes nth_prime/;
my $upto = 1_000_000;
my %freq;
my($this_digit,$last_digit)=(2,0);
forprimes {
($last_digit,$this_digit) = ($this_digit, $_ % 10);
$freq{$last_digit . $this_digit}++;
} 3,nth_prime($upto);
print "$upto first primes. Transitions prime % 10 → next-prime % 10.\n";
printf "%s → %s count:\t%7d\tfrequency: %4.2f %%\n",
substr($_,0,1), substr($_,1,1), $freq{$_}, 100*$freq{$_}/$upto
for sort keys %freq;
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Befunge
|
Befunge
|
& 211p > : 1 - #v_ 25*, @ > 11g:. / v
> : 11g %!|
> 11g 1+ 11p v
^ <
|
http://rosettacode.org/wiki/Pointers_and_references
|
Pointers and references
|
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
|
#6502_Assembly
|
6502 Assembly
|
LDA $19 ;load the value at memory address $19 into the accumulator
LDA #$19 ;load the value hexadecimal 19 (decimal 25) into the accumulator
|
http://rosettacode.org/wiki/Population_count
|
Population count
|
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
|
#8080_Assembly
|
8080 Assembly
|
org 100h
mvi e,30 ; 3^0 to 3^29 inclusive
powers: push d ; Keep counter
;;; Calculate Hamming weight of pow3
lxi b,6 ; C = 6 bytes, B = counter
lxi h,pow3
ham48: mov a,m ; Get byte
ana a ; Clear carry
hambt: ral ; Rotate into carry
jnc $+4 ; Increment counter if carry set
inr b
ana a ; Done yet?
jnz hambt ; If not, keep going
dcr c ; More bytes?
inx h
jnz ham48 ; If not, keep going
mov a,b ; Print result
call outa
;;; Multiply pow3 by 3
mvi b,6 ; Make copy
lxi h,pow3
lxi d,pow3c
copy: mov a,m
stax d
inx h
inx d
dcr b
jnz copy
;;; Multiply by 3 (add copy to it twice)
lxi h,pow3c
lxi d,pow3
call add48
call add48
pop d ; Restore counter
dcr e ; Count down from 30
jnz powers
call outnl
;;; Print first 30 evil numbers
;;; An evil number has even parity
lxi b,-226 ; B=current number (start -1), C=counter
evil: inr b ; Increment number
jpo evil ; If odious, try next number
push b ; Otherwise, output it,
mov a,b
call outa
pop b
dcr c ; Decrement counter
jnz evil ; If not zero, get more numbers
call outnl
;;; Print first 30 odious numbers
;;; An odious number has odd parity
lxi b,-226
odious: inr b
jpe odious ; If number is evil, try next number
push b
mov a,b
call outa
pop b
dcr c
jnz odious
;;; Print newline
outnl: lxi d,nl
mvi c,9
jmp 5
;;; Print 2-digit number in A
outa: lxi d,0A2Fh ; D=10, E=high digit
mkdgt: inr e
sub d
jnc mkdgt
adi '0'+10 ; Low digit
push psw ; Save low digit
mvi c,2 ; Print high digit
call 5
pop psw ; Restore low digit
mov e,a ; Print low digit
mvi c,2
call 5
mvi e,' ' ; Print space
mvi c,2
jmp 5
;;; Add 48-byte number at [HL] to [DE]
add48: push h ; Keep pointers
push d
mvi b,6 ; 6 bytes
ana a ; Clear carry
a48l: ldax d ; Get byte at [DE]
adc m ; Add byte at [HL]
stax d ; Store result at [DE]
inx h ; Increment pointers
inx d
dcr b ; Any more bytes left?
jnz a48l ; If so, do next byte
pop d ; Restore pointers
pop h
ret
nl: db 13,10,'$'
pow3: db 1,0,0,0,0,0 ; pow3, starts at 1
pow3c: equ $ ; room for copy
|
http://rosettacode.org/wiki/Polynomial_long_division
|
Polynomial long division
|
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
|
#APL
|
APL
|
div←{
{
q r d←⍵
(≢d) > n←≢r : q r
c ← (⊃⌽r) ÷ ⊃⌽d
∇ (c,q) ((¯1↓r) - c × ¯1↓(-n)↑d) d
} ⍬ ⍺ ⍵
}
|
http://rosettacode.org/wiki/Polymorphic_copy
|
Polymorphic copy
|
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
|
#BBC_BASIC
|
BBC BASIC
|
INSTALL @lib$ + "CLASSLIB"
REM Create parent class T:
DIM classT{array#(0), setval, retval}
DEF classT.setval (n%,v) classT.array#(n%) = v : ENDPROC
DEF classT.retval (n%) = classT.array#(n%)
PROC_class(classT{})
REM Create class S derived from T, known only at run-time:
RunTimeSize% = RND(100)
DIM classS{array#(RunTimeSize%)}
PROC_inherit(classS{}, classT{})
DEF classS.retval (n%) = classS.array#(n%) ^ 2 : REM Overridden method
PROC_class(classS{})
REM Create an instance of class S:
PROC_new(myobject{}, classS{})
REM Now make a copy of the instance:
DIM mycopy{} = myobject{}
mycopy{} = myobject{}
PROC_discard(myobject{})
REM Test the copy (should print 123^2):
PROC(mycopy.setval)(RunTimeSize%, 123)
result% = FN(mycopy.retval)(RunTimeSize%)
PRINT result%
END
|
http://rosettacode.org/wiki/Polymorphic_copy
|
Polymorphic copy
|
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct object *BaseObj;
typedef struct sclass *Class;
typedef void (*CloneFctn)(BaseObj s, BaseObj clo);
typedef const char * (*SpeakFctn)(BaseObj s);
typedef void (*DestroyFctn)(BaseObj s);
typedef struct sclass {
size_t csize; /* size of the class instance */
const char *cname; /* name of the class */
Class parent; /* parent class */
CloneFctn clone; /* clone function */
SpeakFctn speak; /* speak function */
DestroyFctn del; /* delete the object */
} sClass;
typedef struct object {
Class class;
} SObject;
static
BaseObj obj_copy( BaseObj s, Class c )
{
BaseObj clo;
if (c->parent)
clo = obj_copy( s, c->parent);
else
clo = malloc( s->class->csize );
if (clo)
c->clone( s, clo );
return clo;
}
static
void obj_del( BaseObj s, Class c )
{
if (c->del)
c->del(s);
if (c->parent)
obj_del( s, c->parent);
else
free(s);
}
BaseObj ObjClone( BaseObj s )
{ return obj_copy( s, s->class ); }
const char * ObjSpeak( BaseObj s )
{
return s->class->speak(s);
}
void ObjDestroy( BaseObj s )
{ if (s) obj_del( s, s->class ); }
/* * * * * * */
static
void baseClone( BaseObj s, BaseObj clone)
{
clone->class = s->class;
}
static
const char *baseSpeak(BaseObj s)
{
return "Hello, I'm base object";
}
sClass boc = { sizeof(SObject), "BaseObj", NULL,
&baseClone, &baseSpeak, NULL };
Class BaseObjClass = &boc;
/* * * * * * */
/* Dog - a derived class */
typedef struct sDogPart {
double weight;
char color[32];
char name[24];
} DogPart;
typedef struct sDog *Dog;
struct sDog {
Class class; // parent structure
DogPart dog;
};
static
void dogClone( BaseObj s, BaseObj c)
{
Dog src = (Dog)s;
Dog clone = (Dog)c;
clone->dog = src->dog; /* no pointers so strncpys not needed */
}
static
const char *dogSpeak( BaseObj s)
{
Dog d = (Dog)s;
static char response[90];
sprintf(response, "woof! woof! My name is %s. I'm a %s %s",
d->dog.name, d->dog.color, d->class->cname);
return response;
}
sClass dogc = { sizeof(struct sDog), "Dog", &boc,
&dogClone, &dogSpeak, NULL };
Class DogClass = &dogc;
BaseObj NewDog( const char *name, const char *color, double weight )
{
Dog dog = malloc(DogClass->csize);
if (dog) {
DogPart *dogp = &dog->dog;
dog->class = DogClass;
dogp->weight = weight;
strncpy(dogp->name, name, 23);
strncpy(dogp->color, color, 31);
}
return (BaseObj)dog;
}
/* * * * * * * * * */
/* Ferret - a derived class */
typedef struct sFerretPart {
char color[32];
char name[24];
int age;
} FerretPart;
typedef struct sFerret *Ferret;
struct sFerret {
Class class; // parent structure
FerretPart ferret;
};
static
void ferretClone( BaseObj s, BaseObj c)
{
Ferret src = (Ferret)s;
Ferret clone = (Ferret)c;
clone->ferret = src->ferret; /* no pointers so strncpys not needed */
}
static
const char *ferretSpeak(BaseObj s)
{
Ferret f = (Ferret)s;
static char response[90];
sprintf(response, "My name is %s. I'm a %d mo. old %s wiley %s",
f->ferret.name, f->ferret.age, f->ferret.color,
f->class->cname);
return response;
}
sClass ferretc = { sizeof(struct sFerret), "Ferret", &boc,
&ferretClone, &ferretSpeak, NULL };
Class FerretClass = &ferretc;
BaseObj NewFerret( const char *name, const char *color, int age )
{
Ferret ferret = malloc(FerretClass->csize);
if (ferret) {
FerretPart *ferretp = &(ferret->ferret);
ferret->class = FerretClass;
strncpy(ferretp->name, name, 23);
strncpy(ferretp->color, color, 31);
ferretp->age = age;
}
return (BaseObj)ferret;
}
/* * Now you really understand why Bjarne created C++ * */
int main()
{
BaseObj o1;
BaseObj kara = NewFerret( "Kara", "grey", 15 );
BaseObj bruce = NewDog("Bruce", "yellow", 85.0 );
printf("Ok created things\n");
o1 = ObjClone(kara );
printf("Karol says %s\n", ObjSpeak(o1));
printf("Kara says %s\n", ObjSpeak(kara));
ObjDestroy(o1);
o1 = ObjClone(bruce );
strncpy(((Dog)o1)->dog.name, "Donald", 23);
printf("Don says %s\n", ObjSpeak(o1));
printf("Bruce says %s\n", ObjSpeak(bruce));
ObjDestroy(o1);
return 0;
}
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#Haskell
|
Haskell
|
{-# LANGUAGE OverloadedStrings #-}
import Reflex
import Reflex.Dom
import Reflex.Dom.Time
import Data.Text (Text, pack)
import Data.Map (Map, fromList)
import Data.Time.Clock (getCurrentTime)
import Control.Monad.Trans (liftIO)
type Point = (Float,Float)
type Segment = (Point,Point)
main = mainWidget $ do
-- An event that fires every 0.05 seconds.
dTick <- tickLossy 0.05 =<< liftIO getCurrentTime
-- A dynamically updating counter.
dCounter <- foldDyn (\_ c -> c+1) (0::Int) dTick
let
-- A dynamically updating angle.
dAngle = fmap (\c -> fromIntegral c / 800.0) dCounter
-- A dynamically updating spiral
dSpiralMap = fmap toSpiralMap dAngle
-- svg parameters
width = 600
height = 600
boardAttrs =
fromList [ ("width" , pack $ show width)
, ("height", pack $ show height)
, ("viewBox", pack $ show (-width/2) ++ " " ++ show (-height/2) ++ " " ++ show width ++ " " ++ show height)
]
elAttr "h1" ("style" =: "color:black") $ text "Polyspiral"
elAttr "a" ("href" =: "http://rosettacode.org/wiki/Polyspiral#Haskell") $ text "Rosetta Code / Polyspiral / Haskell"
el "br" $ return ()
elSvgns "svg" (constDyn boardAttrs) (listWithKey dSpiralMap showLine)
return ()
-- The svg attributes needed to display a line segment.
lineAttrs :: Segment -> Map Text Text
lineAttrs ((x1,y1), (x2,y2)) =
fromList [ ( "x1", pack $ show x1)
, ( "y1", pack $ show y1)
, ( "x2", pack $ show x2)
, ( "y2", pack $ show y2)
, ( "style", "stroke:blue")
]
-- Use svg to display a line segment.
showLine :: MonadWidget t m => Int -> Dynamic t Segment -> m ()
showLine _ dSegment = elSvgns "line" (lineAttrs <$> dSegment) $ return ()
-- Given a point and distance/bearing , get the next point
advance :: Float -> (Point, Float, Float) -> (Point, Float, Float)
advance angle ((x,y), len, rot) =
let new_x = x + len * cos rot
new_y = y + len * sin rot
new_len = len + 3.0
new_rot = rot + angle
in ((new_x, new_y), new_len, new_rot)
-- Given an angle, generate a map of segments that form a spiral.
toSpiralMap :: Float -> Map Int ((Float,Float),(Float,Float))
toSpiralMap angle =
fromList -- changes list to map (for listWithKey)
$ zip [0..] -- annotates segments with index
$ (\pts -> zip pts $ tail pts) -- from points to line segments
$ take 80 -- limit the number of points
$ (\(pt,_,_) -> pt) -- cull out the (x,y) values
<$> iterate (advance angle) ((0, 0), 0, 0) -- compute the spiral
-- Display an element in svg namespace
elSvgns :: MonadWidget t m => Text -> Dynamic t (Map Text Text) -> m a -> m a
elSvgns t m ma = do
(el, val) <- elDynAttrNS' (Just "http://www.w3.org/2000/svg") t m ma
return val
|
http://rosettacode.org/wiki/Polynomial_regression
|
Polynomial regression
|
Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#AWK
|
AWK
|
BEGIN{
i = 0;
xa[i] = 0; i++;
xa[i] = 1; i++;
xa[i] = 2; i++;
xa[i] = 3; i++;
xa[i] = 4; i++;
xa[i] = 5; i++;
xa[i] = 6; i++;
xa[i] = 7; i++;
xa[i] = 8; i++;
xa[i] = 9; i++;
xa[i] = 10; i++;
i = 0;
ya[i] = 1; i++;
ya[i] = 6; i++;
ya[i] = 17; i++;
ya[i] = 34; i++;
ya[i] = 57; i++;
ya[i] = 86; i++;
ya[i] =121; i++;
ya[i] =162; i++;
ya[i] =209; i++;
ya[i] =262; i++;
ya[i] =321; i++;
exit;
}
{
# (nothing to do)
}
END{
a = 0; b = 0; c = 0; # globals - will change by regression()
regression(xa,ya);
printf("y = %6.2f x^2 + %6.2f x + %6.2f\n",c,b,a);
printf("%-13s %-8s\n","Input","Approximation");
printf("%-6s %-6s %-8s\n","x","y","y^")
for (i=0;i<length(xa);i++) {
printf("%6.1f %6.1f %8.3f\n",xa[i],ya[i],eval(a,b,c,xa[i]));
}
}
function eval(a,b,c,x) {
return a+b*x+c*x*x;
}
# locals
function regression(x,y, n,xm,ym,x2m,x3m,x4m,xym,x2ym,sxx,sxy,sxx2,sx2x2,sx2y) {
n = 0
xm = 0.0;
ym = 0.0;
x2m = 0.0;
x3m = 0.0;
x4m = 0.0;
xym = 0.0;
x2ym = 0.0;
for (i in x) {
xm += x[i];
ym += y[i];
x2m += x[i] * x[i];
x3m += x[i] * x[i] * x[i];
x4m += x[i] * x[i] * x[i] * x[i];
xym += x[i] * y[i];
x2ym += x[i] * x[i] * y[i];
n++;
}
xm = xm / n;
ym = ym / n;
x2m = x2m / n;
x3m = x3m / n;
x4m = x4m / n;
xym = xym / n;
x2ym = x2ym / n;
sxx = x2m - xm * xm;
sxy = xym - xm * ym;
sxx2 = x3m - xm * x2m;
sx2x2 = x4m - x2m * x2m;
sx2y = x2ym - x2m * ym;
b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
a = ym - b * xm - c * x2m;
}
|
http://rosettacode.org/wiki/Power_set
|
Power set
|
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
|
#Arturo
|
Arturo
|
print powerset [1 2 3 4]
|
http://rosettacode.org/wiki/Primality_by_trial_division
|
Primality by trial division
|
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#ALGOL-M
|
ALGOL-M
|
BEGIN
% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% RETURN INTEGER SQUARE ROOT OF N %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
INTEGER R1, R2;
R1 := N;
R2 := 1;
WHILE R1 > R2 DO
BEGIN
R1 := (R1+R2) / 2;
R2 := N / R1;
END;
ISQRT := R1;
END;
% RETURN 1 IF N IS PRIME, OTHERWISE 0 %
INTEGER FUNCTION ISPRIME(N);
INTEGER N;
BEGIN
IF N = 2 THEN
ISPRIME := 1
ELSE IF (N < 2) OR (MOD(N,2) = 0) THEN
ISPRIME := 0
ELSE % TEST ODD NUMBERS UP TO SQRT OF N %
BEGIN
INTEGER I, LIMIT;
LIMIT := ISQRT(N);
I := 3;
WHILE I <= LIMIT AND MOD(N,I) <> 0 DO
I := I + 2;
ISPRIME := (IF I <= LIMIT THEN 0 ELSE 1);
END;
END;
% TEST FOR PRIMES IN RANGE 1 TO 50 %
INTEGER I;
WRITE("");
FOR I := 1 STEP 1 UNTIL 50 DO
BEGIN
IF ISPRIME(I)=1 THEN WRITEON(I," "); % WORKS FOR 80 COL SCREEN %
END;
END
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#Bracmat
|
Bracmat
|
( ( convert
=
. ("0.06"."0.10")
("0.11"."0.18")
("0.16"."0.26")
("0.21"."0.32")
("0.26"."0.38")
("0.31"."0.44")
("0.36"."0.50")
("0.41"."0.54")
("0.46"."0.58")
("0.51"."0.62")
("0.56"."0.66")
("0.61"."0.70")
("0.66"."0.74")
("0.71"."0.78")
("0.76"."0.82")
("0.81"."0.86")
("0.86"."0.90")
("0.91"."0.94")
("0.96"."0.98")
("1.01"."1.00")
: ? (>!arg.?arg) ?
& !arg
| "invalid input"
)
& -1:?n
& whl
' ( !n+1:?n:<103
& ( @(!n:? [<2)&str$("0.0" !n):?a
| @(!n:? [<3)&str$("0." !n):?a
| @(!n:?ones [-3 ?decimals)
& str$(!ones "." !decimals):?a
)
& out$(!a "-->" convert$!a)
)
)
|
http://rosettacode.org/wiki/Proper_divisors
|
Proper divisors
|
The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#Erlang
|
Erlang
|
-module(properdivs).
-export([divs/1,sumdivs/1,longest/1]).
divs(0) -> [];
divs(1) -> [];
divs(N) -> lists:sort([1] ++ divisors(2,N,math:sqrt(N))).
divisors(K,_N,Q) when K > Q -> [];
divisors(K,N,Q) when N rem K =/= 0 ->
divisors(K+1,N,Q);
divisors(K,N,Q) when K * K == N ->
[K] ++ divisors(K+1,N,Q);
divisors(K,N,Q) ->
[K, N div K] ++ divisors(K+1,N,Q).
sumdivs(N) -> lists:sum(divs(N)).
longest(Limit) -> longest(Limit,0,0,1).
longest(L,Current,CurLeng,Acc) when Acc >= L ->
io:format("With ~w, Number ~w has the most divisors~n", [CurLeng,Current]);
longest(L,Current,CurLeng,Acc) ->
A = length(divs(Acc)),
if A > CurLeng ->
longest(L,Acc,A,Acc+1);
true -> longest(L,Current,CurLeng,Acc+1)
end.
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#HicEst
|
HicEst
|
REAL :: trials=1E6, n=8, map(n), limit(n), expected(n), outcome(n)
expected = 1 / ($ + 4)
expected(n) = 1 - SUM(expected) + expected(n)
map = expected
map = map($) + map($-1)
DO i = 1, trials
random = RAN(1)
limit = random > map
item = INDEX(limit, 0)
outcome(item) = outcome(item) + 1
ENDDO
outcome = outcome / trials
DLG(Text=expected, Text=outcome, Y=0)
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#FreeBASIC
|
FreeBASIC
|
Type Tupla
Prioridad As Integer
Tarea As String
End Type
Dim Shared As Tupla a()
Dim Shared As Integer n 'número de eltos. en la matriz, el último elto. es n-1
Function Izda(i As Integer) As Integer
Izda = 2 * i + 1
End Function
Function Dcha(i As Integer) As Integer
Dcha = 2 * i + 2
End Function
Function Parent(i As Integer) As Integer
Parent = (i - 1) \ 2
End Function
Sub Intercambio(i As Integer, j As Integer)
Dim t As Tupla
t = a(i)
a(i) = a(j)
a(j) = t
End Sub
Sub bubbleUp(i As Integer)
Dim As Integer p = Parent(i)
Do While i > 0 And a(i).Prioridad < a(p).Prioridad
Intercambio i, p
i = p
p = Parent(i)
Loop
End Sub
Sub Annadir(fPrioridad As Integer, fTarea As String)
n += 1
If n > Ubound(a) Then Redim Preserve a(2 * n)
a(n - 1).Prioridad = fPrioridad
a(n - 1).Tarea = fTarea
bubbleUp (n - 1)
End Sub
Sub trickleDown(i As Integer)
Dim As Integer j, l, r
Do
j = -1
r = Dcha(i)
If r < n And a(r).Prioridad < a(i).Prioridad Then
l = Izda(i)
If a(l).Prioridad < a(r).Prioridad Then
j = l
Else
j = r
End If
Else
l = Izda(i)
If l < n And a(l).Prioridad < a(i).Prioridad Then j = l
End If
If j >= 0 Then Intercambio i, j
i = j
Loop While i >= 0
End Sub
Function Remove() As Tupla
Dim As Tupla x = a(0)
a(0) = a(n - 1)
n = n - 1
trickleDown 0
If 3 * n < Ubound(a) Then Redim Preserve a(Ubound(a) \ 2)
Remove = x
End Function
Redim a(4)
Annadir (3, "Clear drains")
Annadir (4, "Feed cat")
Annadir (5, "Make tea")
Annadir (1, "Solve RC tasks")
Annadir (2, "Tax return")
Dim t As Tupla
Do While n > 0
t = Remove
Print t.Prioridad; " "; t.Tarea
Loop
Sleep
|
http://rosettacode.org/wiki/Problem_of_Apollonius
|
Problem of Apollonius
|
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#PL.2FI
|
PL/I
|
Apollonius: procedure options (main); /* 29 October 2013 */
define structure
1 circle,
2 x float (15),
2 y float (15),
2 radius float (15);
declare (c1 , c2, c3, result) type (circle);
c1.x = 0; c1.y = 0; c1.radius = 1;
c2.x = 4; c2.y = 0; c2.radius = 1;
c3.x = 2; c3.y = 4; c3.radius = 2;
result = Solve_Apollonius(c1, c2, c3, 1, 1, 1);
put skip edit ('External tangent:', result.x, result.y, result.radius) (a, 3 f(12,8));
result = Solve_Apollonius(c1, c2, c3, -1, -1, -1);
put skip edit ('Internal tangent:', result.x, result.y, result.radius) (a, 3 f(12,8));
Solve_Apollonius: procedure (c1, c2, c3, s1, s2, s3) returns(type(circle));
declare (c1, c2, c3) type(circle);
declare res type (circle);
declare (s1, s2, s3) fixed binary;
declare (
v11, v12, v13, v14,
v21, v22, v23, v24,
w12, w13, w14,
w22, w23, w24,
p, q, m, n, a, b, c, det) float (15);
v11 = 2*c2.x - 2*c1.x;
v12 = 2*c2.y - 2*c1.y;
v13 = c1.x**2 - c2.x**2 + c1.y**2 - c2.y**2 - c1.radius**2 + c2.radius**2;
v14 = 2*s2*c2.radius - 2*s1*c1.radius;
v21 = 2*c3.x - 2*c2.x;
v22 = 2*c3.y - 2*c2.y;
v23 = c2.x**2 - c3.x**2 + c2.y**2 - c3.y**2 - c2.radius**2 + c3.radius**2;
v24 = 2*s3*c3.radius - 2*s2*c2.radius;
w12 = v12/v11;
w13 = v13/v11;
w14 = v14/v11;
w22 = v22/v21-w12;
w23 = v23/v21-w13;
w24 = v24/v21-w14;
p = -w23/w22;
q = w24/w22;
m = -w12*P - w13;
n = w14 - w12*q;
a = n*n + q*q - 1;
b = 2*m*n - 2*n*c1.x + 2*p*q - 2*q*c1.y + 2*s1*c1.radius;
c = c1.x**2 + m*m - 2*m*c1.x + p*p + c1.y**2 - 2*p*c1.y - c1.radius**2;
det = b*b - 4*a*c;
res.radius = (-b-sqrt(det)) / (2*a);
res.x = m + n*res.radius;
res.y = p + q*res.radius;
return (res);
end Solve_Apollonius;
end Apollonius;
|
http://rosettacode.org/wiki/Problem_of_Apollonius
|
Problem of Apollonius
|
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#PowerShell
|
PowerShell
|
function Measure-Apollonius
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[int]$Counter,
[double]$x1,
[double]$y1,
[double]$r1,
[double]$x2,
[double]$y2,
[double]$r2,
[double]$x3,
[double]$y3,
[double]$r3
)
switch ($Counter)
{
{$_ -eq 2} {$s1 = -1; $s2 = -1; $s3 = -1; break}
{$_ -eq 3} {$s1 = 1; $s2 = -1; $s3 = -1; break}
{$_ -eq 4} {$s1 = -1; $s2 = 1; $s3 = -1; break}
{$_ -eq 5} {$s1 = -1; $s2 = -1; $s3 = 1; break}
{$_ -eq 6} {$s1 = 1; $s2 = 1; $s3 = -1; break}
{$_ -eq 7} {$s1 = -1; $s2 = 1; $s3 = 1; break}
{$_ -eq 8} {$s1 = 1; $s2 = -1; $s3 = 1; break}
Default {$s1 = 1; $s2 = 1; $s3 = 1; break}
}
[double]$v11 = 2 * $x2 - 2 * $x1
[double]$v12 = 2 * $y2 - 2 * $y1
[double]$v13 = $x1 * $x1 - $x2 * $x2 + $y1 * $y1 - $y2 * $y2 - $r1 * $r1 + $r2 * $r2
[double]$v14 = 2 * $s2 * $r2 - 2 * $s1 * $r1
[double]$v21 = 2 * $x3 - 2 * $x2
[double]$v22 = 2 * $y3 - 2 * $y2
[double]$v23 = $x2 * $x2 - $x3 * $x3 + $y2 * $y2 - $y3 * $y3 - $r2 * $r2 + $r3 * $r3
[double]$v24 = 2 * $s3 * $r3 - 2 * $s2 * $r2
[double]$w12 = $v12 / $v11
[double]$w13 = $v13 / $v11
[double]$w14 = $v14 / $v11
[double]$w22 = $v22 / $v21 - $w12
[double]$w23 = $v23 / $v21 - $w13
[double]$w24 = $v24 / $v21 - $w14
[double]$P = -$w23 / $w22
[double]$Q = $w24 / $w22
[double]$M = -$w12 * $P - $w13
[double]$N = $w14 - $w12 * $Q
[double]$a = $N * $N + $Q * $Q - 1
[double]$b = 2 * $M * $N - 2 * $N * $x1 + 2 * $P * $Q - 2 * $Q * $y1 + 2 * $s1 * $r1
[double]$c = $x1 * $x1 + $M * $M - 2 * $M * $x1 + $P * $P + $y1 * $y1 - 2 * $P * $y1 - $r1 * $r1
[double]$D = $b * $b - 4 * $a * $c
[double]$rs = (-$b - [Double]::Parse([Math]::Sqrt($D).ToString())) / (2 * [Double]::Parse($a.ToString()))
[double]$xs = $M + $N * $rs
[double]$ys = $P + $Q * $rs
[PSCustomObject]@{
X = $xs
Y = $ys
Radius = $rs
}
}
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Ring
|
Ring
|
see "Active Source File Name : " + filename() + nl
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Ruby
|
Ruby
|
#!/usr/bin/env ruby
puts "Path: #{$PROGRAM_NAME}" # or puts "Path: #{$0}"
puts "Name: #{File.basename $0}"
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#PureBasic
|
PureBasic
|
Procedure.i ConsoleWrite(t.s) ; compile using /CONSOLE option
OpenConsole()
PrintN (t.s)
CloseConsole()
ProcedureReturn 1
EndProcedure
Procedure.i StdOut(t.s) ; compile using /CONSOLE option
OpenConsole()
Print(t.s)
CloseConsole()
ProcedureReturn 1
EndProcedure
Procedure.i gcDiv(n,m) ; greatest common divisor
if n=0:ProcedureReturn m:endif
while m <> 0
if n > m
n - m
else
m - n
endif
wend
ProcedureReturn n
EndProcedure
st=ElapsedMilliseconds()
nmax =10000
power =8
dim primitiveA(power)
dim alltripleA(power)
dim pmaxA(power)
x=1
for i=1 to power
x*10:pmaxA(i)=x/2
next
for n=1 to nmax
for m=(n+1) to (nmax+1) step 2 ; assure m-n is odd
d=gcDiv(n,m)
p=m*m+m*n
for i=1 to power
if p<=pmaxA(i)
if d =1
primitiveA(i)+1 ; right here we have the primitive perimeter "seed" 'p'
k=1:q=p*k ; set k to one to include p : use q as the 'p*k'
while q<=pmaxA(i)
alltripleA(i)+1 ; accumulate multiples of this perimeter while q <= pmaxA(i)
k+1:q=p*k
wend
endif
endif
next
next
next
for i=1 to power
t.s="Up to "+str(pmaxA(i)*2)+": "
t.s+str(alltripleA(i))+" triples, "
t.s+str(primitiveA(i))+" primitives."
ConsoleWrite(t.s)
next
ConsoleWrite("")
et=ElapsedMilliseconds()-st:ConsoleWrite("Elapsed time = "+str(et)+" milliseconds")
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#PicoLisp
|
PicoLisp
|
(push '*Bye '(prinl "Goodbye world!"))
(bye)
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#PL.2FI
|
PL/I
|
STOP; /* terminates the entire program */
/* PL/I does any required cleanup, such as closing files. */
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#jq
|
jq
|
## Compute (n - 1)! mod m.
def facmod($n; $m):
reduce range(2; $n+1) as $k (1; (. * $k) % $m);
def isPrime: .>1 and (facmod(. - 1; .) + 1) % . == 0;
"Prime numbers between 2 and 100:",
[range(2;101) | select (isPrime)],
# Notice that `infinite` can be used as the second argument of `range`:
"First 10 primes after 7900:",
[limit(10; range(7900; infinite) | select(isPrime))]
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#Julia
|
Julia
|
iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Phix
|
Phix
|
with javascript_semantics
sequence p10k = get_primes(-10_000),
transitions = repeat(repeat(0,9),9)
integer l = length(p10k), last = p10k[1], curr
for i=2 to l do
curr = remainder(p10k[i],10)
transitions[last][curr] += 1
last = curr
end for
for i=1 to 9 do
for j=1 to 9 do
atom tij = transitions[i][j]
if tij!=0 then
atom pc = tij*100/l
printf(1,"%d->%d:%3.2f%%\n",{i,j,pc})
end if
end for
end for
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#BQN
|
BQN
|
Factor ← { 𝕊n:
# Prime sieve
primes ← ↕0
Sieve ← { p 𝕊 a‿b:
p(⍋↑⊣)↩√b ⋄ l←b-a
E ← {↕∘⌈⌾(((𝕩|-a)+𝕩×⊢)⁼)l} # Indices of multiples of 𝕩
a + / (1⥊˜l) E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p # Primes in segment [a,b)
}
# Factor by trial division
r ← ↕0 # Result list
Try ← {
m ← (1+⌊√n) ⌊ 2×𝕩 # Upper bound for factors this round
𝕩<m ? # Stop if no factors
primes ∾↩ np ← primes Sieve 𝕩‿m # New primes
{0=𝕩|n? r∾↩𝕩 ⋄ n÷↩𝕩 ⋄ 𝕊𝕩 ;@}¨ np # Try each one
𝕊 m # Next segment
;@}
Try 2
r ∾ 1⊸<⊸⥊n
}
|
http://rosettacode.org/wiki/Pointers_and_references
|
Pointers and references
|
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
|
#8086_Assembly
|
8086 Assembly
|
.model small
.stack 1024
.data ; data segment begins here
UserRam byte 256 dup (0) ; the next 256 bytes have a value of zero. The address of the 0th of these bytes can be referenced as "UserRam"
tempByte equ UserRam ;this variable's address is the same as that of the 0th byte of UserRam
tempWord equ UserRam+2 ;this variable's address is the address of UserRam + 2
.code
start:
mov ax, @data
mov ds, ax
mov ax, @code
mov es, ax
|
http://rosettacode.org/wiki/Population_count
|
Population count
|
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
|
#8086_Assembly
|
8086 Assembly
|
cpu 8086
bits 16
org 100h
section .text
;;; Calculate hamming weights of 3^0 to 3^29.
;;; 3^29 needs a 48-bit representation, which
;;; we'll put in BP:SI:DI.
xor bp,bp ; BP:SI:DI = 1
xor si,si
xor di,di
inc di
mov cx,30
;;; Calculate pop count of BP:SI:DI
pow3s: push bp ; Keep state
push si
push di
xor ax,ax ; AL = counter
ham48: rcl bp,1
rcl si,1
rcl di,1
adc al,ah
mov dx,bp
or dx,si
or dx,di
jnz ham48
pop di ; Restore state
pop si
pop bp
call outal ; Output
;;; Multiply by 3
push bp ; Keep state
push si
push di
add di,di ; Mul by two (add to itself)
adc si,si
adc bp,bp
pop ax ; Add original (making x3)
add di,ax
pop ax
adc si,ax
pop ax
adc bp,ax
loop pow3s
call outnl
;;; Print first 30 evil numbers
;;; This is much easier, since they fit in a byte,
;;; and we only need to know whether the Hamming weight
;;; is odd or even, which is the same as the built-in
;;; parity check
mov cl,30
xor bx,bx
dec bx
evil: inc bx ; Increment number to test
jpo .next ; If parity is odd, number is not evil
mov al,bl ; Otherwise, output the number
call outal
dec cx ; One fewer left
.next: test cx,cx
jnz evil ; Next evil number
call outnl
;;; For the odious numbers it is the same
mov cl,30
xor bx,bx
dec bx
odious: inc bx
jpe .next ; Except this time we skip the evil numbers
mov al,bl
call outal
dec cx
.next: test cx,cx
jnz odious
;;; Print newline
outnl: mov ah,2
mov dl,13
int 21h
mov dl,10
int 21h
ret
;;; Print 2-digit number in AL
outal: aam
add ax,3030h
xchg dx,ax
xchg dl,dh
mov ah,2
int 21h
xchg dl,dh
int 21h
mov dl,' '
int 21h
ret
|
http://rosettacode.org/wiki/Polynomial_long_division
|
Polynomial long division
|
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
|
#BBC_BASIC
|
BBC BASIC
|
DIM N%(3) : N%() = -42, 0, -12, 1
DIM D%(3) : D%() = -3, 1, 0, 0
DIM q%(3), r%(3)
PROC_poly_long_div(N%(), D%(), q%(), r%())
PRINT "Quotient = "; FNcoeff(q%(2)) "x^2" FNcoeff(q%(1)) "x" FNcoeff(q%(0))
PRINT "Remainder = " ; r%(0)
END
DEF PROC_poly_long_div(N%(), D%(), q%(), r%())
LOCAL d%(), i%, s%
DIM d%(DIM(N%(),1))
s% = FNdegree(N%()) - FNdegree(D%())
IF s% >= 0 THEN
q%() = 0
WHILE s% >= 0
FOR i% = 0 TO DIM(d%(),1) - s%
d%(i%+s%) = D%(i%)
NEXT
q%(s%) = N%(FNdegree(N%())) DIV d%(FNdegree(d%()))
d%() = d%() * q%(s%)
N%() -= d%()
s% = FNdegree(N%()) - FNdegree(D%())
ENDWHILE
r%() = N%()
ELSE
q%() = 0
r%() = N%()
ENDIF
ENDPROC
DEF FNdegree(a%())
LOCAL i%
i% = DIM(a%(),1)
WHILE a%(i%)=0
i% -= 1
IF i%<0 EXIT WHILE
ENDWHILE
= i%
DEF FNcoeff(n%)
IF n%=0 THEN = ""
IF n%<0 THEN = " - " + STR$(-n%)
IF n%=1 THEN = " + "
= " + " + STR$(n%)
|
http://rosettacode.org/wiki/Polymorphic_copy
|
Polymorphic copy
|
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
|
#C.23
|
C#
|
using System;
class T
{
public virtual string Name()
{
return "T";
}
public virtual T Clone()
{
return new T();
}
}
class S : T
{
public override string Name()
{
return "S";
}
public override T Clone()
{
return new S();
}
}
class Program
{
static void Main()
{
T original = new S();
T clone = original.Clone();
Console.WriteLine(original.Name());
Console.WriteLine(clone.Name());
}
}
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#IS-BASIC
|
IS-BASIC
|
100 PROGRAM "PolySp.bas"
110 OPTION ANGLE DEGREES
120 LET CH=2
130 SET VIDEO X 40:SET VIDEO Y 27:SET VIDEO MODE 1:SET VIDEO COLOR 0
140 OPEN #1:"video:"
150 OPEN #2:"video:"
160 WHEN EXCEPTION USE POSERROR
170 FOR ANG=40 TO 150 STEP 2
180 IF CH=2 THEN
190 LET CH=1
200 ELSE
210 LET CH=2
220 END IF
230 CLEAR #CH
240 PLOT #CH:640,468,ANGLE 180;
250 FOR D=12 TO 740 STEP 4
260 PLOT #CH:FORWARD D,RIGHT ANG;
270 NEXT
280 DISPLAY #CH:AT 1 FROM 1 TO 27
290 NEXT
300 END WHEN
310 HANDLER POSERROR
320 LET D=740
330 CONTINUE
340 END HANDLER
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#J
|
J
|
require 'gl2 trig media/imagekit'
coinsert 'jgl2'
DT =: %30 NB. seconds
ANGLE =: 0.025p1 NB. radians
DIRECTION=: 0 NB. radians
POLY=: noun define
pc poly;pn "Poly Spiral";
minwh 320 320; cc isi isigraph;
)
poly_run=: verb define
wd POLY,'pshow'
wd 'timer ',":DT * 1000
)
poly_close=: verb define
wd 'timer 0; pclose'
)
sys_timer_z_=: verb define
recalcAngle_base_ ''
wd 'psel poly; set isi invalid'
)
poly_isi_paint=: verb define
drawPolyspiral DIRECTION
)
recalcAngle=: verb define
DIRECTION=: 2p1 | DIRECTION + ANGLE
)
drawPolyspiral=: verb define
glclear''
x1y1 =. (glqwh'')%2
a=. -DIRECTION
len=. 5
for_i. i.150 do.
glpen glrgb Hue a % 2p1
x2y2=. x1y1 + len*(cos,sin) a
gllines <.x1y1,x2y2
x1y1=. x2y2
len=. len+3
a=. 2p1 | a - DIRECTION
end.
)
poly_run''
|
http://rosettacode.org/wiki/Polynomial_regression
|
Polynomial regression
|
Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#BBC_BASIC
|
BBC BASIC
|
INSTALL @lib$+"ARRAYLIB"
Max% = 10000
DIM vector(5), matrix(5,5)
DIM x(Max%), x2(Max%), x3(Max%), x4(Max%), x5(Max%)
DIM x6(Max%), x7(Max%), x8(Max%), x9(Max%), x10(Max%)
DIM y(Max%), xy(Max%), x2y(Max%), x3y(Max%), x4y(Max%), x5y(Max%)
npts% = 11
x() = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
y() = 1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321
sum_x = SUM(x())
x2() = x() * x() : sum_x2 = SUM(x2())
x3() = x() * x2() : sum_x3 = SUM(x3())
x4() = x2() * x2() : sum_x4 = SUM(x4())
x5() = x2() * x3() : sum_x5 = SUM(x5())
x6() = x3() * x3() : sum_x6 = SUM(x6())
x7() = x3() * x4() : sum_x7 = SUM(x7())
x8() = x4() * x4() : sum_x8 = SUM(x8())
x9() = x4() * x5() : sum_x9 = SUM(x9())
x10() = x5() * x5() : sum_x10 = SUM(x10())
sum_y = SUM(y())
xy() = x() * y() : sum_xy = SUM(xy())
x2y() = x2() * y() : sum_x2y = SUM(x2y())
x3y() = x3() * y() : sum_x3y = SUM(x3y())
x4y() = x4() * y() : sum_x4y = SUM(x4y())
x5y() = x5() * y() : sum_x5y = SUM(x5y())
matrix() = \
\ npts%, sum_x, sum_x2, sum_x3, sum_x4, sum_x5, \
\ sum_x, sum_x2, sum_x3, sum_x4, sum_x5, sum_x6, \
\ sum_x2, sum_x3, sum_x4, sum_x5, sum_x6, sum_x7, \
\ sum_x3, sum_x4, sum_x5, sum_x6, sum_x7, sum_x8, \
\ sum_x4, sum_x5, sum_x6, sum_x7, sum_x8, sum_x9, \
\ sum_x5, sum_x6, sum_x7, sum_x8, sum_x9, sum_x10
vector() = \
\ sum_y, sum_xy, sum_x2y, sum_x3y, sum_x4y, sum_x5y
PROC_invert(matrix())
vector() = matrix().vector()
@% = &2040A
PRINT "Polynomial coefficients = "
FOR term% = 5 TO 0 STEP -1
PRINT ;vector(term%) " * x^" STR$(term%)
NEXT
|
http://rosettacode.org/wiki/Power_set
|
Power set
|
A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
|
#ATS
|
ATS
|
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
//
(* ****** ****** *)
//
extern
fun
Power_set(xs: list0(int)): void
//
(* ****** ****** *)
// Helper: fast power function.
fun power(n: int, p: int): int =
if p = 1 then n
else if p = 0 then 1
else if p % 2 = 0 then power(n*n, p/2)
else n * power(n, p-1)
fun print_list(list: list0(int)): void =
case+ list of
| nil0() => println!(" ")
| cons0(car, crd) =>
let
val () = begin print car; print ','; end
val () = print_list(crd)
in
end
fun get_list_length(list: list0(int), length: int): int =
case+ list of
| nil0() => length
| cons0(car, crd) => get_list_length(crd, length+1)
fun get_list_from_bit_mask(mask: int, list: list0(int), result: list0(int)): list0(int) =
if mask = 0 then result
else
case+ list of
| nil0() => result
| cons0(car, crd) =>
let
val current: int = mask % 2
in
if current = 0 then
get_list_from_bit_mask(mask >> 1, crd, result)
else
get_list_from_bit_mask(mask >> 1, crd, list0_cons(car, result))
end
implement
Power_set(xs) = let
val len: int = get_list_length(xs, 0)
val pow: int = power(2, len)
fun loop(mask: int, list: list0(int)): void =
if mask > 0 && mask >= pow then ()
else
let
val () = print_list(get_list_from_bit_mask(mask, list, list0_nil()))
in
loop(mask+1, list)
end
in
loop(0, xs)
end
(* ****** ****** *)
implement
main0() =
let
val xs: list0(int) = cons0(1, list0_pair(2, 3))
in
Power_set(xs)
end (* end of [main0] *)
(* ****** ****** *)
|
http://rosettacode.org/wiki/Primality_by_trial_division
|
Primality by trial division
|
Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#ALGOL_W
|
ALGOL W
|
% returns true if n is prime, false otherwise %
% uses trial division %
logical procedure isPrime ( integer value n ) ;
if n < 3 or not odd( n ) then n = 2
else begin
% odd number > 2 %
integer f, rootN;
logical havePrime;
f := 3;
rootN := entier( sqrt( n ) );
havePrime := true;
while f <= rootN and havePrime do begin
havePrime := ( n rem f ) not = 0;
f := f + 2
end;
havePrime
end isPrime ;
|
http://rosettacode.org/wiki/Price_fraction
|
Price fraction
|
A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
|
#C
|
C
|
#include<stdio.h>
double table[][2] = {
{0.06, 0.10}, {0.11, 0.18}, {0.16, 0.26}, {0.21, 0.32},
{0.26, 0.38}, {0.31, 0.44}, {0.36, 0.50}, {0.41, 0.54},
{0.46, 0.58}, {0.51, 0.62}, {0.56, 0.66}, {0.61, 0.70},
{0.66, 0.74}, {0.71, 0.78}, {0.76, 0.82}, {0.81, 0.86},
{0.86, 0.90}, {0.91, 0.94}, {0.96, 0.98}, {1.01, 1.00},
{-1, 0}, /* guarding element */
};
double price_fix(double x)
{
int i;
for (i = 0; table[i][0] > 0; i++)
if (x < table[i][0]) return table[i][1];
abort(); /* what else to do? */
}
int main()
{
int i;
for (i = 0; i <= 100; i++)
printf("%.2f %.2f\n", i / 100., price_fix(i / 100.));
return 0;
}
|
http://rosettacode.org/wiki/Proper_divisors
|
Proper divisors
|
The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
|
#F.23
|
F#
|
// the simple function with the answer
let propDivs n = [1..n/2] |> List.filter (fun x->n % x = 0)
// to cache the result length; helpful for a long search
let propDivDat n = propDivs n |> fun xs -> n, xs.Length, xs
// UI: always the longest and messiest
let show (n,count,divs) =
let showCount = count |> function | 0-> "no proper divisors" | 1->"1 proper divisor" | _-> sprintf "%d proper divisors" count
let showDiv = divs |> function | []->"" | x::[]->sprintf ": %d" x | _->divs |> Seq.map string |> String.concat "," |> sprintf ": %s"
printfn "%d has %s%s" n showCount showDiv
// generate output
[1..10] |> List.iter (propDivDat >> show)
// use a sequence: we don't really need to hold this data, just iterate over it
Seq.init 20000 ( ((+) 1) >> propDivDat)
|> Seq.fold (fun a b ->match a,b with | (_,c1,_),(_,c2,_) when c2 > c1 -> b | _-> a) (0,0,[])
|> fun (n,count,_) -> (n,count,[]) |> show
|
http://rosettacode.org/wiki/Probabilistic_choice
|
Probabilistic choice
|
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
|
#Icon_and_Unicon
|
Icon and Unicon
|
record Item(value, probability)
procedure find_item (items, v)
sum := 0.0
every item := !items do {
if v < sum+item.probability
then return item.value
else sum +:= item.probability
}
fail # v exceeded 1.0
end
# -- helper procedures
# count the number of occurrences of i in list l,
# assuming the items are strings
procedure count (l, i)
result := 0.0
every x := !l do
if x == i then result +:= 1
return result
end
procedure rand_float ()
return ?1000/1000.0
end
# -- test the procedure
procedure main ()
items := [
Item("aleph", 1/5.0),
Item("beth", 1/6.0),
Item("gimel", 1/7.0),
Item("daleth", 1/8.0),
Item("he", 1/9.0),
Item("waw", 1/10.0),
Item("zayin", 1/11.0),
Item("heth", 1759/27720.0)
]
# collect a sample of results
sample := []
every (1 to 1000000) do push (sample, find_item(items, rand_float ()))
# return comparison of expected vs actual probability
every item := !items do
write (right(item.value, 7) || " " ||
left(item.probability, 15) || " " ||
left(count(sample, item.value)/*sample, 6))
end
|
http://rosettacode.org/wiki/Priority_queue
|
Priority queue
|
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
#FunL
|
FunL
|
import util.ordering
native scala.collection.mutable.PriorityQueue
data Task( priority, description )
def comparator( Task(a, _), Task(b, _) )
| a > b = -1
| a < b = 1
| otherwise = 0
q = PriorityQueue( ordering(comparator) )
q.enqueue(
Task(3, 'Clear drains'),
Task(4, 'Feed cat'),
Task(5, 'Make tea'),
Task(1, 'Solve RC tasks'),
Task(2, 'Tax return')
)
while not q.isEmpty()
println( q.dequeue() )
|
http://rosettacode.org/wiki/Problem_of_Apollonius
|
Problem of Apollonius
|
Task
Implement a solution to the Problem of Apollonius (description on Wikipedia) which is the problem of finding the circle that is tangent to three specified circles (colored black in the diagram below to the right).
There is an algebraic solution which is pretty straightforward.
The solutions to the example in the code are shown in the diagram (below and to the right).
The red circle is "internally tangent" to all three black circles, and the green circle is "externally tangent" to all three black circles.
|
#PureBasic
|
PureBasic
|
Structure Circle
XPos.f
YPos.f
Radius.f
EndStructure
Procedure ApolloniusSolver(*c1.Circle,*c2.Circle,*c3.Circle, s1, s2, s3)
Define.f ; This tells the compiler that all non-specified new variables
; should be of float type (.f).
x1=*c1\XPos: y1=*c1\YPos: r1=*c1\Radius
x2=*c2\XPos: y2=*c2\YPos: r2=*c2\Radius
x3=*c3\XPos: y3=*c3\YPos: r3=*c3\Radius
v11 = 2*x2 - 2*x1
v12 = 2*y2 - 2*y1
v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2
v14 = 2*s2*r2 - 2*s1*r1
v21 = 2*x3 - 2*x2
v22 = 2*y3 - 2*y2
v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3
v24 = 2*s3*r3 - 2*s2*r2
w12 = v12/v11
w13 = v13/v11
w14 = v14/v11
w22 = v22/v21-w12
w23 = v23/v21-w13
w24 = v24/v21-w14
P = -w23/w22
Q = w24/w22
M = -w12*P-w13
N = w14-w12*Q
a = N*N + Q*Q - 1
b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1
c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1
D= b*b - 4*a*c
Define *result.Circle=AllocateMemory(SizeOf(Circle))
; Allocate memory for a returned Structure of type Circle.
; This memory should be freed later but if not, PureBasic’s
; internal framework will do so when the program shuts down.
If *result
*result\Radius=(-b-Sqr(D))/(2*a)
*result\XPos =M+N * *result\Radius
*result\YPos =P+Q * *result\Radius
EndIf
ProcedureReturn *result ; Sending back a pointer
EndProcedure
If OpenConsole()
Define.Circle c1, c2, c3
Define *c.Circle ; '*c' is defined as a pointer to a circle-structure.
c1\Radius=1
c2\XPos=4: c2\Radius=1
c3\XPos=2: c3\YPos=4: c3\Radius=2
*c=ApolloniusSolver(@c1, @c2, @c3, 1, 1, 1)
If *c ; Verify that *c got allocated
PrintN("Circle [x="+StrF(*c\XPos,2)+", y="+StrF(*c\YPos,2)+", r="+StrF(*c\Radius,2)+"]")
FreeMemory(*c) ; We are done with *c for the first calculation
EndIf
*c=ApolloniusSolver(@c1, @c2, @c3,-1,-1,-1)
If *c
PrintN("Circle [x="+StrF(*c\XPos,2)+", y="+StrF(*c\YPos,2)+", r="+StrF(*c\Radius,2)+"]")
FreeMemory(*c)
EndIf
Print("Press ENTER to exit"): Input()
EndIf
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#Rust
|
Rust
|
fn main() {
println!("Program: {}", std::env::args().next().unwrap());
}
|
http://rosettacode.org/wiki/Program_name
|
Program name
|
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".)
Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal ARGV.
See also Command-line arguments
Examples from GitHub.
|
#SAC
|
SAC
|
use StdIO: all;
use Array: all;
use String: { string };
use CommandLine: all;
int main() {
program = argv(0);
printf("Program: %s\n", program);
return(0);
}
|
http://rosettacode.org/wiki/Pythagorean_triples
|
Pythagorean triples
|
A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
|
#Python
|
Python
|
from fractions import gcd
def pt1(maxperimeter=100):
'''
# Naive method
'''
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
#
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
'''
# Parent/child relationship method:
# http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples#XI.
'''
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#Pop11
|
Pop11
|
if condition then
sysexit();
endif;
|
http://rosettacode.org/wiki/Program_termination
|
Program termination
|
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
|
#PostScript
|
PostScript
|
condition {stop} if
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#Lua
|
Lua
|
-- primality by Wilson's theorem
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
end
|
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
|
Primality by Wilson's theorem
|
Task
Write a boolean function that tells whether a given integer is prime using Wilson's theorem.
By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1.
Remember that 1 and all non-positive integers are not prime.
See also
Cut-the-knot: Wilson's theorem.
Wikipedia: Wilson's theorem
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#Picat
|
Picat
|
go =>
N = 15_485_863, % 1_000_000 primes
Primes = {P mod 10 : P in primes(N)},
Len = Primes.len,
A = new_array(10,10), bind_vars(A,0),
foreach(I in 2..Len)
P1 = 1 + Primes[I-1], % adjust for 1-based
P2 = 1 + Primes[I],
A[P1,P2] := A[P1,P2] + 1
end,
foreach(I in 0..9, J in 0..9, V = A[I+1,J+1], V > 0)
printf("%d -> %d count: %5d frequency: %0.4f%%\n", I,J,V,100*V/Len)
end,
nl.
|
http://rosettacode.org/wiki/Prime_conspiracy
|
Prime conspiracy
|
A recent discovery, quoted from Quantamagazine (March 13, 2016):
Two mathematicians have uncovered a simple, previously unnoticed property of
prime numbers — those numbers that are divisible only by 1 and themselves.
Prime numbers, it seems, have decided preferences about the final digits of
the primes that immediately follow them.
and
This conspiracy among prime numbers seems, at first glance, to violate a
longstanding assumption in number theory: that prime numbers behave much
like random numbers.
─── (original authors from Stanford University):
─── Kannan Soundararajan and Robert Lemke Oliver
The task is to check this assertion, modulo 10.
Lets call i -> j a transition if i is the last decimal digit of a prime, and j the last decimal digit of the following prime.
Task
Considering the first one million primes. Count, for any pair of successive primes, the number of transitions i -> j and print them along with their relative frequency, sorted by i .
You can see that, for a given i , frequencies are not evenly distributed.
Observation
(Modulo 10), primes whose last digit is 9 "prefer" the digit 1 to the digit 9, as its following prime.
Extra credit
Do the same for one hundred million primes.
Example for 10,000 primes
10000 first primes. Transitions prime % 10 → next-prime % 10.
1 → 1 count: 365 frequency: 3.65 %
1 → 3 count: 833 frequency: 8.33 %
1 → 7 count: 889 frequency: 8.89 %
1 → 9 count: 397 frequency: 3.97 %
2 → 3 count: 1 frequency: 0.01 %
3 → 1 count: 529 frequency: 5.29 %
3 → 3 count: 324 frequency: 3.24 %
3 → 5 count: 1 frequency: 0.01 %
3 → 7 count: 754 frequency: 7.54 %
3 → 9 count: 907 frequency: 9.07 %
5 → 7 count: 1 frequency: 0.01 %
7 → 1 count: 655 frequency: 6.55 %
7 → 3 count: 722 frequency: 7.22 %
7 → 7 count: 323 frequency: 3.23 %
7 → 9 count: 808 frequency: 8.08 %
9 → 1 count: 935 frequency: 9.35 %
9 → 3 count: 635 frequency: 6.35 %
9 → 7 count: 541 frequency: 5.41 %
9 → 9 count: 379 frequency: 3.79 %
|
#PicoLisp
|
PicoLisp
|
(load "pluser/sieve.l") # See the task "Sieve of Eratosthanes"
(setq NthPrime '(
( 10 . 29)
( 100 . 541)
( 1000 . 7919)
( 10000 . 104729)
( 100000 . 1299709)
(1000000 . 15485863)))
(de conspiracy (Power)
(let (Upto (cdr (assoc (** 10 Power) NthPrime)))
(if Upto
(report Upto)
(prog (prinl "Sorry, I don't know the value of the 1e" Power "th prime number.") NIL))))
(de report (Upto)
(for Count (tally Upto)
(let (((A . B) . C) Count)
(prinl A " -> " B ": " C)))
NIL)
(de tally (Upto)
(let
(Transitions
(maplist '((L)
(and
(cdr L)
(cons
(% (car L) 10)
(% (cadr L) 10))))
(sieve Upto)))
(let (Tally NIL)
(for Pair Transitions
(setq Tally (bump-trans Pair Tally)))
(cdr (sort Tally))))) # NOTE: After sorting, first element is NIL
# (since the last element from the maplist call is NIL)
(de bump-trans (Trans Tally)
(cond
((== Tally NIL)
(list (cons Trans 1)))
((= Trans (caar Tally))
(cons (cons Trans (inc (cdar Tally))) (cdr Tally)))
(T
(cons (car Tally) (bump-trans Trans (cdr Tally))))))
|
http://rosettacode.org/wiki/Prime_decomposition
|
Prime decomposition
|
The prime decomposition of a number is defined as a list of prime numbers
which when all multiplied together, are equal to that number.
Example
12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3}
Task
Write a function which returns an array or collection which contains the prime decomposition of a given number
n
{\displaystyle n}
greater than 1.
If your language does not have an isPrime-like function available,
you may assume that you have a function which determines
whether a number is prime (note its name before your code).
If you would like to test code from this task, you may use code from trial division or the Sieve of Eratosthenes.
Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc).
Related tasks
count in factors
factors of an integer
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
|
#Burlesque
|
Burlesque
|
blsq ) 12fC
{2 2 3}
|
http://rosettacode.org/wiki/Pointers_and_references
|
Pointers and references
|
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
|
#68000_Assembly
|
68000 Assembly
|
myVar equ $100000 ; a section of user ram given a label
myData: ; a data table given a label
dc.b $80,$81,$82,$83
|
http://rosettacode.org/wiki/Pointers_and_references
|
Pointers and references
|
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
|
#Ada
|
Ada
|
type Int_Access is access Integer;
Int_Acc : Int_Access := new Integer'(5);
|
http://rosettacode.org/wiki/Polymorphism
|
Polymorphism
|
Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
|
#ActionScript
|
ActionScript
|
package
{
public class Point
{
protected var _x:Number;
protected var _y:Number;
public function Point(x:Number = 0, y:Number = 0)
{
_x = x;
_y = y;
}
public function getX():Number
{
return _x;
}
public function setX(x:Number):void
{
_x = x;
}
public function getY():Number
{
return _y;
}
public function setY(y:Number):void
{
_x = y;
}
public function print():void
{
trace("Point");
}
}
}
|
http://rosettacode.org/wiki/Population_count
|
Population count
|
Population count
You are encouraged to solve this task according to the task description, using any language you may know.
The population count is the number of 1s (ones) in the binary representation of a non-negative integer.
Population count is also known as:
pop count
popcount
sideways sum
bit summation
Hamming weight
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count.
Odious numbers are positive integers that have an odd population count.
Task
write a function (or routine) to return the population count of a non-negative integer.
all computation of the lists below should start with 0 (zero indexed).
display the pop count of the 1st thirty powers of 3 (30, 31, 32, 33, 34, ∙∙∙ 329).
display the 1st thirty evil numbers.
display the 1st thirty odious numbers.
display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.
See also
The On-Line Encyclopedia of Integer Sequences: A000120 population count.
The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
|
#Ada
|
Ada
|
with Interfaces;
package Population_Count is
subtype Num is Interfaces.Unsigned_64;
function Pop_Count(N: Num) return Natural;
end Population_Count;
|
http://rosettacode.org/wiki/Polynomial_long_division
|
Polynomial long division
|
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
|
#C
|
C
|
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <gsl/gsl_vector.h>
#define MAX(A,B) (((A)>(B))?(A):(B))
void reoshift(gsl_vector *v, int h)
{
if ( h > 0 ) {
gsl_vector *temp = gsl_vector_alloc(v->size);
gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h);
gsl_vector_view p1 = gsl_vector_subvector(temp, h, v->size - h);
gsl_vector_memcpy(&p1.vector, &p.vector);
p = gsl_vector_subvector(temp, 0, h);
gsl_vector_set_zero(&p.vector);
gsl_vector_memcpy(v, temp);
gsl_vector_free(temp);
}
}
gsl_vector *poly_long_div(gsl_vector *n, gsl_vector *d, gsl_vector **r)
{
gsl_vector *nt = NULL, *dt = NULL, *rt = NULL, *d2 = NULL, *q = NULL;
int gn, gt, gd;
if ( (n->size >= d->size) && (d->size > 0) && (n->size > 0) ) {
nt = gsl_vector_alloc(n->size); assert(nt != NULL);
dt = gsl_vector_alloc(n->size); assert(dt != NULL);
rt = gsl_vector_alloc(n->size); assert(rt != NULL);
d2 = gsl_vector_alloc(n->size); assert(d2 != NULL);
gsl_vector_memcpy(nt, n);
gsl_vector_set_zero(dt); gsl_vector_set_zero(rt);
gsl_vector_view p = gsl_vector_subvector(dt, 0, d->size);
gsl_vector_memcpy(&p.vector, d);
gsl_vector_memcpy(d2, dt);
gn = n->size - 1;
gd = d->size - 1;
gt = 0;
while( gsl_vector_get(d, gd) == 0 ) gd--;
while ( gn >= gd ) {
reoshift(dt, gn-gd);
double v = gsl_vector_get(nt, gn)/gsl_vector_get(dt, gn);
gsl_vector_set(rt, gn-gd, v);
gsl_vector_scale(dt, v);
gsl_vector_sub(nt, dt);
gt = MAX(gt, gn-gd);
while( (gn>=0) && (gsl_vector_get(nt, gn) == 0.0) ) gn--;
gsl_vector_memcpy(dt, d2);
}
q = gsl_vector_alloc(gt+1); assert(q != NULL);
p = gsl_vector_subvector(rt, 0, gt+1);
gsl_vector_memcpy(q, &p.vector);
if ( r != NULL ) {
if ( (gn+1) > 0 ) {
*r = gsl_vector_alloc(gn+1); assert( *r != NULL );
p = gsl_vector_subvector(nt, 0, gn+1);
gsl_vector_memcpy(*r, &p.vector);
} else {
*r = gsl_vector_alloc(1); assert( *r != NULL );
gsl_vector_set_zero(*r);
}
}
gsl_vector_free(nt); gsl_vector_free(dt);
gsl_vector_free(rt); gsl_vector_free(d2);
return q;
} else {
q = gsl_vector_alloc(1); assert( q != NULL );
gsl_vector_set_zero(q);
if ( r != NULL ) {
*r = gsl_vector_alloc(n->size); assert( *r != NULL );
gsl_vector_memcpy(*r, n);
}
return q;
}
}
void poly_print(gsl_vector *p)
{
int i;
for(i=p->size-1; i >= 0; i--) {
if ( i > 0 )
printf("%lfx^%d + ",
gsl_vector_get(p, i), i);
else
printf("%lf\n", gsl_vector_get(p, i));
}
}
gsl_vector *create_poly(int d, ...)
{
va_list al;
int i;
gsl_vector *r = NULL;
va_start(al, d);
r = gsl_vector_alloc(d); assert( r != NULL );
for(i=0; i < d; i++)
gsl_vector_set(r, i, va_arg(al, double));
return r;
}
|
http://rosettacode.org/wiki/Polymorphic_copy
|
Polymorphic copy
|
An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
|
#C.2B.2B
|
C++
|
#include <iostream>
class T
{
public:
virtual void identify() { std::cout << "I am a genuine T" << std::endl; }
virtual T* clone() { return new T(*this); }
virtual ~T() {}
};
class S: public T
{
public:
virtual void identify() { std::cout << "I am an S" << std::endl; }
virtual S* clone() { return new S(*this); }
};
class X // the class of the object which contains a T or S
{
public:
// by getting the object through a pointer to T, X cannot know if it's an S or a T
X(T* t): member(t) {}
// copy constructor
X(X const& other): member(other.member->clone()) {}
// copy assignment operator
X& operator=(X const& other)
{
T* new_member = other.member->clone();
delete member;
member = new_member;
}
// destructor
~X() { delete member; }
// check what sort of object it contains
void identify_member() { member->identify(); }
private:
T* member;
};
int main()
{
X original(new S); // construct an X and give it an S,
X copy = original; // copy it,
copy.identify_member(); // and check what type of member it contains
}
|
http://rosettacode.org/wiki/Polyspiral
|
Polyspiral
|
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.
Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.
If animation is not practical in your programming environment, you may show a single frame instead.
Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
|
#Java
|
Java
|
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PolySpiral extends JPanel {
double inc = 0;
public PolySpiral() {
setPreferredSize(new Dimension(640, 640));
setBackground(Color.white);
new Timer(40, (ActionEvent e) -> {
inc = (inc + 0.05) % 360;
repaint();
}).start();
}
void drawSpiral(Graphics2D g, int len, double angleIncrement) {
double x1 = getWidth() / 2;
double y1 = getHeight() / 2;
double angle = angleIncrement;
for (int i = 0; i < 150; i++) {
g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f));
double x2 = x1 + Math.cos(angle) * len;
double y2 = y1 - Math.sin(angle) * len;
g.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
x1 = x2;
y1 = y2;
len += 3;
angle = (angle + angleIncrement) % (Math.PI * 2);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawSpiral(g, 5, Math.toRadians(inc));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("PolySpiral");
f.setResizable(true);
f.add(new PolySpiral(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
|
http://rosettacode.org/wiki/Polynomial_regression
|
Polynomial regression
|
Find an approximating polynomial of known degree for a given data.
Example:
For input data:
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
The approximating polynomial is:
3 x2 + 2 x + 1
Here, the polynomial's coefficients are (3, 2, 1).
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#C
|
C
|
#ifndef _POLIFITGSL_H
#define _POLIFITGSL_H
#include <gsl/gsl_multifit.h>
#include <stdbool.h>
#include <math.h>
bool polynomialfit(int obs, int degree,
double *dx, double *dy, double *store); /* n, p */
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.