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/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
|
#E
|
E
|
pragma.syntax("0.9")
pragma.enable("accumulator")
def superscript(x, out) {
if (x >= 10) { superscript(x // 10) }
out.print("⁰¹²³⁴⁵⁶⁷⁸⁹"[x %% 10])
}
def makePolynomial(initCoeffs :List) {
def degree := {
var i := initCoeffs.size() - 1
while (i >= 0 && initCoeffs[i] <=> 0) { i -= 1 }
if (i < 0) { -Infinity } else { i }
}
def coeffs := initCoeffs(0, if (degree == -Infinity) { [] } else { degree + 1 })
def polynomial {
/** Print the polynomial (not necessary for the task) */
to __printOn(out) {
out.print("(λx.")
var first := true
for i in (0..!(coeffs.size())).descending() {
def coeff := coeffs[i]
if (coeff <=> 0) { continue }
out.print(" ")
if (coeff <=> 1 && !(i <=> 0)) {
# no coefficient written if it's 1 and not the constant term
} else if (first) { out.print(coeff)
} else if (coeff > 0) { out.print("+ ", coeff)
} else { out.print("- ", -coeff)
}
if (i <=> 0) { # no x if it's the constant term
} else if (i <=> 1) { out.print("x")
} else { out.print("x"); superscript(i, out)
}
first := false
}
out.print(")")
}
/** Evaluate the polynomial (not necessary for the task) */
to run(x) {
return accum 0 for i => c in coeffs { _ + c * x**i }
}
to degree() { return degree }
to coeffs() { return coeffs }
to highestCoeff() { return coeffs[degree] }
/** Could support another polynomial, but not part of this task.
Computes this * x**power. */
to timesXToThe(power) {
return makePolynomial([0] * power + coeffs)
}
/** Multiply (by a scalar only). */
to multiply(scalar) {
return makePolynomial(accum [] for x in coeffs { _.with(x * scalar) })
}
/** Subtract (by another polynomial only). */
to subtract(other) {
def oc := other.coeffs() :List
return makePolynomial(accum [] for i in 0..(coeffs.size().max(oc.size())) { _.with(coeffs.fetch(i, fn{0}) - oc.fetch(i, fn{0})) })
}
/** Polynomial long division. */
to quotRem(denominator, trace) {
var numerator := polynomial
require(denominator.degree() >= 0)
if (numerator.degree() < denominator.degree()) {
return [makePolynomial([]), denominator]
} else {
var quotientCoeffs := [0] * (numerator.degree() - denominator.degree())
while (numerator.degree() >= denominator.degree()) {
trace.print(" ", numerator, "\n")
def qCoeff := numerator.highestCoeff() / denominator.highestCoeff()
def qPower := numerator.degree() - denominator.degree()
quotientCoeffs with= (qPower, qCoeff)
def d := denominator.timesXToThe(qPower) * qCoeff
trace.print("- ", d, " (= ", denominator, " * ", qCoeff, "x"); superscript(qPower, trace); trace.print(")\n")
numerator -= d
trace.print(" -------------------------- (Quotient so far: ", makePolynomial(quotientCoeffs), ")\n")
}
return [makePolynomial(quotientCoeffs), numerator]
}
}
}
return polynomial
}
|
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.
|
#Groovy
|
Groovy
|
class T implements Cloneable {
String property
String name() { 'T' }
T copy() {
try { super.clone() }
catch(CloneNotSupportedException e) { null }
}
@Override
boolean equals(that) { this.name() == that?.name() && this.property == that?.property }
}
class S extends T {
@Override String name() { 'S' }
}
|
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
|
#Python
|
Python
|
import math
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1024, 600))
pygame.display.set_caption("Polyspiral")
incr = 0
running = True
while running:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type==QUIT:
running = False
break
incr = (incr + 0.05) % 360
x1 = pygame.display.Info().current_w / 2
y1 = pygame.display.Info().current_h / 2
length = 5
angle = incr
screen.fill((255,255,255))
for i in range(1,151):
x2 = x1 + math.cos(angle) * length
y2 = y1 + math.sin(angle) * length
pygame.draw.line(screen, (255,0,0), (x1, y1), (x2, y2), 1)
# pygame.draw.aaline(screen, (255,0,0), (x1, y1), (x2, y2)) # Anti-Aliased
x1, y1 = x2, y2
length += 3
angle = (angle + incr) % 360
pygame.display.flip()
|
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.
|
#FreeBASIC
|
FreeBASIC
|
#Include "crt.bi" 'for rounding only
Type vector
Dim As Double element(Any)
End Type
Type matrix
Dim As Double element(Any,Any)
Declare Function inverse() As matrix
Declare Function transpose() As matrix
private:
Declare Function GaussJordan(As vector) As vector
End Type
'mult operators
Operator *(m1 As matrix,m2 As matrix) As matrix
Dim rows As Integer=Ubound(m1.element,1)
Dim columns As Integer=Ubound(m2.element,2)
If Ubound(m1.element,2)<>Ubound(m2.element,1) Then
Print "Can't do"
Exit Operator
End If
Dim As matrix ans
Redim ans.element(rows,columns)
Dim rxc As Double
For r As Integer=1 To rows
For c As Integer=1 To columns
rxc=0
For k As Integer = 1 To Ubound(m1.element,2)
rxc=rxc+m1.element(r,k)*m2.element(k,c)
Next k
ans.element(r,c)=rxc
Next c
Next r
Operator= ans
End Operator
Operator *(m1 As matrix,m2 As vector) As vector
Dim rows As Integer=Ubound(m1.element,1)
Dim columns As Integer=Ubound(m2.element,2)
If Ubound(m1.element,2)<>Ubound(m2.element) Then
Print "Can't do"
Exit Operator
End If
Dim As vector ans
Redim ans.element(rows)
Dim rxc As Double
For r As Integer=1 To rows
rxc=0
For k As Integer = 1 To Ubound(m1.element,2)
rxc=rxc+m1.element(r,k)*m2.element(k)
Next k
ans.element(r)=rxc
Next r
Operator= ans
End Operator
Function matrix.transpose() As matrix
Dim As matrix b
Redim b.element(1 To Ubound(this.element,2),1 To Ubound(this.element,1))
For i As Long=1 To Ubound(this.element,1)
For j As Long=1 To Ubound(this.element,2)
b.element(j,i)=this.element(i,j)
Next
Next
Return b
End Function
Function matrix.GaussJordan(rhs As vector) As vector
Dim As Integer n=Ubound(rhs.element)
Dim As vector ans=rhs,r=rhs
Dim As matrix b=This
#macro pivot(num)
For p1 As Integer = num To n - 1
For p2 As Integer = p1 + 1 To n
If Abs(b.element(p1,num))<Abs(b.element(p2,num)) Then
Swap r.element(p1),r.element(p2)
For g As Integer=1 To n
Swap b.element(p1,g),b.element(p2,g)
Next g
End If
Next p2
Next p1
#endmacro
For k As Integer=1 To n-1
pivot(k)
For row As Integer =k To n-1
If b.element(row+1,k)=0 Then Exit For
Var f=b.element(k,k)/b.element(row+1,k)
r.element(row+1)=r.element(row+1)*f-r.element(k)
For g As Integer=1 To n
b.element((row+1),g)=b.element((row+1),g)*f-b.element(k,g)
Next g
Next row
Next k
'back substitute
For z As Integer=n To 1 Step -1
ans.element(z)=r.element(z)/b.element(z,z)
For j As Integer = n To z+1 Step -1
ans.element(z)=ans.element(z)-(b.element(z,j)*ans.element(j)/b.element(z,z))
Next j
Next z
Function = ans
End Function
Function matrix.inverse() As matrix
Var ub1=Ubound(this.element,1),ub2=Ubound(this.element,2)
Dim As matrix ans
Dim As vector temp,null_
Redim temp.element(1 To ub1):Redim null_.element(1 To ub1)
Redim ans.element(1 To ub1,1 To ub2)
For a As Integer=1 To ub1
temp=null_
temp.element(a)=1
temp=GaussJordan(temp)
For b As Integer=1 To ub1
ans.element(b,a)=temp.element(b)
Next b
Next a
Return ans
End Function
'vandermode of x
Function vandermonde(x_values() As Double,w As Long) As matrix
Dim As matrix mat
Var n=Ubound(x_values)
Redim mat.element(1 To n,1 To w)
For a As Integer=1 To n
For b As Integer=1 To w
mat.element(a,b)=x_values(a)^(b-1)
Next b
Next a
Return mat
End Function
'main preocedure
Sub regress(x_values() As Double,y_values() As Double,ans() As Double,n As Long)
Redim ans(1 To Ubound(x_values))
Dim As matrix m1= vandermonde(x_values(),n)
Dim As matrix T=m1.transpose
Dim As vector y
Redim y.element(1 To Ubound(ans))
For n As Long=1 To Ubound(y_values)
y.element(n)=y_values(n)
Next n
Dim As vector result=(((T*m1).inverse)*T)*y
Redim Preserve ans(1 To n)
For n As Long=1 To Ubound(ans)
ans(n)=result.element(n)
Next n
End Sub
'Evaluate a polynomial at x
Function polyeval(Coefficients() As Double,Byval x As Double) As Double
Dim As Double acc
For i As Long=Ubound(Coefficients) To Lbound(Coefficients) Step -1
acc=acc*x+Coefficients(i)
Next i
Return acc
End Function
Function CRound(Byval x As Double,Byval precision As Integer=30) As String
If precision>30 Then precision=30
Dim As zstring * 40 z:Var s="%." &str(Abs(precision)) &"f"
sprintf(z,s,x)
If Val(z) Then Return Rtrim(Rtrim(z,"0"),".")Else Return "0"
End Function
Function show(a() As Double,places as long=10) As String
Dim As String s,g
For n As Long=Lbound(a) To Ubound(a)
If n<3 Then g="" Else g="^"+Str(n-1)
if val(cround(a(n),places))<>0 then
s+= Iif(Sgn(a(n))>=0,"+","")+cround(a(n),places)+ Iif(n=Lbound(a),"","*x"+g)+" "
end if
Next n
Return s
End Function
dim as double x(1 to ...)={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
dim as double y(1 to ...)={1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
Redim As Double ans()
regress(x(),y(),ans(),3)
print show(ans())
sleep
|
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.
|
#C.2B.2B
|
C++
|
#include <iostream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
typedef std::set<int> set_type;
typedef std::set<set_type> powerset_type;
powerset_type powerset(set_type const& set)
{
typedef set_type::const_iterator set_iter;
typedef std::vector<set_iter> vec;
typedef vec::iterator vec_iter;
struct local
{
static int dereference(set_iter v) { return *v; }
};
powerset_type result;
vec elements;
do
{
set_type tmp;
std::transform(elements.begin(), elements.end(),
std::inserter(tmp, tmp.end()),
local::dereference);
result.insert(tmp);
if (!elements.empty() && ++elements.back() == set.end())
{
elements.pop_back();
}
else
{
set_iter iter;
if (elements.empty())
{
iter = set.begin();
}
else
{
iter = elements.back();
++iter;
}
for (; iter != set.end(); ++iter)
{
elements.push_back(iter);
}
}
} while (!elements.empty());
return result;
}
int main()
{
int values[4] = { 2, 3, 5, 7 };
set_type test_set(values, values+4);
powerset_type test_powerset = powerset(test_set);
for (powerset_type::iterator iter = test_powerset.begin();
iter != test_powerset.end();
++iter)
{
std::cout << "{ ";
char const* prefix = "";
for (set_type::iterator iter2 = iter->begin();
iter2 != iter->end();
++iter2)
{
std::cout << prefix << *iter2;
prefix = ", ";
}
std::cout << " }\n";
}
}
|
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
|
#BASIC256
|
BASIC256
|
for i = 1 to 99
if isPrime(i) then print string(i); " ";
next i
end
function isPrime(v)
if v < 2 then return False
if v mod 2 = 0 then return v = 2
if v mod 3 = 0 then return v = 3
d = 5
while d * d <= v
if v mod d = 0 then return False else d += 2
end while
return True
end function
|
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
|
#Elixir
|
Elixir
|
defmodule Price do
@table [ {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} ]
def fraction(value) when value in 0..1 do
{_, standard_value} = Enum.find(@table, fn {upper_limit, _} -> value < upper_limit end)
standard_value
end
end
val = for i <- 0..100, do: i/100
Enum.each(val, fn x ->
:io.format "~5.2f ->~5.2f~n", [x, Price.fraction(x)]
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
|
#GFA_Basic
|
GFA Basic
|
OPENW 1
CLEARW 1
'
' Array f% is used to hold the divisors
DIM f%(SQR(20000)) ! cannot redim arrays, so set size to largest needed
'
' 1. Show proper divisors of 1 to 10, inclusive
'
FOR i%=1 TO 10
num%=@proper_divisors(i%)
PRINT "Divisors for ";i%;":";
FOR j%=1 TO num%
PRINT " ";f%(j%);
NEXT j%
PRINT
NEXT i%
'
' 2. Find (smallest) number <= 20000 with largest number of proper divisors
'
result%=1 ! largest so far
number%=0 ! its number of divisors
FOR i%=1 TO 20000
num%=@proper_divisors(i%)
IF num%>number%
result%=i%
number%=num%
ENDIF
NEXT i%
PRINT "Largest number of divisors is ";number%;" for ";result%
'
~INP(2)
CLOSEW 1
'
' find the proper divisors of n%, placing results in f%
' and return the number found
'
FUNCTION proper_divisors(n%)
LOCAL i%,root%,count%
'
ARRAYFILL f%(),0
count%=1 ! index of next slot in f% to fill
'
IF n%>1
f%(count%)=1
count%=count%+1
root%=SQR(n%)
FOR i%=2 TO root%
IF n% MOD i%=0
f%(count%)=i%
count%=count%+1
IF i%*i%<>n% ! root% is an integer, so check if i% is actual squa- lists:seq(1,10)].
X: 1, N: []
X: 2, N: [1]
X: 3, N: [1]
X: 4, N: [1,2]
X: 5, N: [1]
X: 6, N: [1,2,3]
X: 7, N: [1]
X: 8, N: [1,2,4]
X: 9, N: [1,3]
X: 10, N: [1,2,5]
[ok,ok,ok,ok,ok,ok,ok,ok,ok,ok]
2> properdivs:longest(20000).
With 79, Number 15120 has the most divisors
re root of n%
f%(count%)=n%/i%
count%=count%+1
ENDIF
ENDIF
NEXT i%
ENDIF
'
RETURN count%-1
ENDFUNC
|
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)
|
#Nim
|
Nim
|
import tables, random, strformat, times
var start = cpuTime()
const
NumTrials = 1_000_000
Probabilities = {"aleph": 1 / 5, "beth": 1 / 6, "gimel": 1 / 7, "daleth": 1 / 8,
"he": 1 / 9, "waw": 1 / 10, "zayin": 1 / 11, "heth": 1759 / 27720}.toTable
var samples: CountTable[string]
randomize()
for i in 1 .. NumTrials:
var z = rand(1.0)
for item, prob in Probabilities.pairs:
if z < prob:
samples.inc(item)
break
else:
z -= prob
var s1, s2 = 0.0
echo " Item Target Results Differences"
echo "====== ======== ======== ==========="
for item, prob in Probabilities.pairs:
let r = samples[item] / NumTrials
s1 += r * 100
s2 += prob * 100
echo &"{item:<6} {prob:.6f} {r:.6f} {100 * (1 - r / prob):9.6f} %"
echo "====== ======== ======== "
echo &"Total: {s2:^8.2f} {s1:^8.2f}"
echo &"\nExecution time: {cpuTime()-start:.2f} s"
|
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)
|
#OCaml
|
OCaml
|
let p = [
"Aleph", 1.0 /. 5.0;
"Beth", 1.0 /. 6.0;
"Gimel", 1.0 /. 7.0;
"Daleth", 1.0 /. 8.0;
"He", 1.0 /. 9.0;
"Waw", 1.0 /. 10.0;
"Zayin", 1.0 /. 11.0;
"Heth", 1759.0 /. 27720.0;
]
let rec take k = function
| (v, p)::tl -> if k < p then v else take (k -. p) tl
| _ -> invalid_arg "take"
let () =
let n = 1_000_000 in
Random.self_init();
let h = Hashtbl.create 3 in
List.iter (fun (v, _) -> Hashtbl.add h v 0) p;
let tot = List.fold_left (fun acc (_, p) -> acc +. p) 0.0 p in
for i = 1 to n do
let sel = take (Random.float tot) p in
let n = Hashtbl.find h sel in
Hashtbl.replace h sel (succ n) (* count the number of each item *)
done;
List.iter (fun (v, p) ->
let d = Hashtbl.find h v in
Printf.printf "%s \t %f %f\n" v p (float d /. float n)
) p
|
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.
|
#Julia
|
Julia
|
using Base.Collections
test = ["Clear drains" 3;
"Feed cat" 4;
"Make tea" 5;
"Solve RC tasks" 1;
"Tax return" 2]
task = PriorityQueue(Base.Order.Reverse)
for i in 1:size(test)[1]
enqueue!(task, test[i,1], test[i,2])
end
println("Tasks, completed according to priority:")
while !isempty(task)
(t, p) = peek(task)
dequeue!(task)
println(" \"", t, "\" has priority ", p)
end
|
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.
|
#VBA
|
VBA
|
Option Explicit
Option Base 0
Private Const intBase As Integer = 0
Private Type tPoint
X As Double
Y As Double
End Type
Private Type tCircle
Centre As tPoint
Radius As Double
End Type
Private Sub sApollonius()
Dim Circle1 As tCircle
Dim Circle2 As tCircle
Dim Circle3 As tCircle
Dim CTanTanTan(intBase + 0 to intBase + 7) As tCircle
With Circle1
With .Centre
.X = 0
.Y = 0
End With
.Radius = 1
End With
With Circle2
With .Centre
.X = 4
.Y = 0
End With
.Radius = 1
End With
With Circle3
With .Centre
.X = 2
.Y = 4
End With
.Radius = 2
End With
Call fApollonius(Circle1,Circle2,Circle3,CTanTanTan()))
End Sub
Public Function fApollonius(ByRef C1 As tCircle, _
ByRef C2 As tCircle, _
ByRef C3 As tCircle, _
ByRef CTanTanTan() As tCircle) As Boolean
' Solves the Problem of Apollonius (finding a circle tangent to three other circles in the plane)
' (x_s - x_1)^2 + (y_s - y_1)^2 = (r_s - Tan_1 * r_1)^2
' (x_s - x_2)^2 + (y_s - y_2)^2 = (r_s - Tan_2 * r_2)^2
' (x_s - x_3)^2 + (y_s - y_3)^2 = (r_s - Tan_3 * r_3)^2
' x_s = M + N * r_s
' y_s = P + Q * r_s
' Parameters:
' C1, C2, C3 (circles in the problem)
' Tan1 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle1 (C1)
' Tan2 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle2 (C2)
' Tan3 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle3 (C3)
Dim Tangent(intBase + 0 To intBase + 7, intBase + 0 To intBase + 2) As Integer
Dim lgTangent As Long
Dim Tan1 As Integer
Dim Tan2 As Integer
Dim Tan3 As Integer
Dim v11 As Double
Dim v12 As Double
Dim v13 As Double
Dim v14 As Double
Dim v21 As Double
Dim v22 As Double
Dim v23 As Double
Dim v24 As Double
Dim w12 As Double
Dim w13 As Double
Dim w14 As Double
Dim w22 As Double
Dim w23 As Double
Dim w24 As Double
Dim p As Double
Dim Q As Double
Dim M As Double
Dim N As Double
Dim A As Double
Dim b As Double
Dim c As Double
Dim D As Double
'Check if circle centers are colinear
If fColinearPoints(C1.Centre, C2.Centre, C3.Centre) Then
fApollonius = False
Exit Function
End If
Tangent(intBase + 0, intBase + 0) = -1
Tangent(intBase + 0, intBase + 1) = -1
Tangent(intBase + 0, intBase + 2) = -1
Tangent(intBase + 1, intBase + 0) = -1
Tangent(intBase + 1, intBase + 1) = -1
Tangent(intBase + 1, intBase + 2) = 1
Tangent(intBase + 2, intBase + 0) = -1
Tangent(intBase + 2, intBase + 1) = 1
Tangent(intBase + 2, intBase + 2) = -1
Tangent(intBase + 3, intBase + 0) = -1
Tangent(intBase + 3, intBase + 1) = 1
Tangent(intBase + 3, intBase + 2) = 1
Tangent(intBase + 4, intBase + 0) = 1
Tangent(intBase + 4, intBase + 1) = -1
Tangent(intBase + 4, intBase + 2) = -1
Tangent(intBase + 5, intBase + 0) = 1
Tangent(intBase + 5, intBase + 1) = -1
Tangent(intBase + 5, intBase + 2) = 1
Tangent(intBase + 6, intBase + 0) = 1
Tangent(intBase + 6, intBase + 1) = 1
Tangent(intBase + 6, intBase + 2) = -1
Tangent(intBase + 7, intBase + 0) = 1
Tangent(intBase + 7, intBase + 1) = 1
Tangent(intBase + 7, intBase + 2) = 1
For lgTangent = LBound(Tangent) To UBound(Tangent)
Tan1 = Tangent(lgTangent, intBase + 0)
Tan2 = Tangent(lgTangent, intBase + 1)
Tan3 = Tangent(lgTangent, intBase + 2)
v11 = 2 * (C2.Centre.X - C1.Centre.X)
v12 = 2 * (C2.Centre.Y - C1.Centre.Y)
v13 = (C1.Centre.X * C1.Centre.X) _
- (C2.Centre.X * C2.Centre.X) _
+ (C1.Centre.Y * C1.Centre.Y) _
- (C2.Centre.Y * C2.Centre.Y) _
- (C1.Radius * C1.Radius) _
+ (C2.Radius * C2.Radius)
v14 = 2 * (Tan2 * C2.Radius - Tan1 * C1.Radius)
v21 = 2 * (C3.Centre.X - C2.Centre.X)
v22 = 2 * (C3.Centre.Y - C2.Centre.Y)
v23 = (C2.Centre.X * C2.Centre.X) _
- (C3.Centre.X * C3.Centre.X) _
+ (C2.Centre.Y * C2.Centre.Y) _
- (C3.Centre.Y * C3.Centre.Y) _
- (C2.Radius * C2.Radius) _
+ (C3.Radius * C3.Radius)
v24 = 2 * ((Tan3 * C3.Radius) - (Tan2 * 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) - (N * C1.Centre.X) + (p * Q) - (Q * C1.Centre.Y) + (Tan1 * C1.Radius))
c = (C1.Centre.X * C1.Centre.X) _
+ (M * M) _
- (2 * M * C1.Centre.X) _
+ (p * p) _
+ (C1.Centre.Y * C1.Centre.Y) _
- (2 * p * C1.Centre.Y) _
- (C1.Radius * C1.Radius)
'Find a root of a quadratic equation (requires the circle centers not to be e.g. colinear)
D = (b * b) - (4 * A * c)
With CTanTanTan(lgTangent)
.Radius = (-b - VBA.Sqr(D)) / (2 * A)
.Centre.X = M + (N * .Radius)
.Centre.Y = p + (Q * .Radius)
End With
Next lgTangent
fApollonius = True
End Function
|
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.
|
#Wren
|
Wren
|
import "/dynamic" for Tuple
var Circle = Tuple.create("Circle", ["x", "y", "r"])
var solveApollonius = Fn.new { |c1, c2, c3, s1, s2, s3|
var x1 = c1.x
var y1 = c1.y
var r1 = c1.r
var x2 = c2.x
var y2 = c2.y
var r2 = c2.r
var x3 = c3.x
var y3 = c3.y
var r3 = c3.r
var v11 = 2 * x2 - 2 * x1
var v12 = 2 * y2 - 2 * y1
var v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2
var v14 = 2 * s2 * r2 - 2 * s1 * r1
var v21 = 2 * x3 - 2 * x2
var v22 = 2 * y3 - 2 * y2
var v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3
var v24 = 2 * s3 * r3 - 2 * s2 * r2
var w12 = v12 / v11
var w13 = v13 / v11
var w14 = v14 / v11
var w22 = v22 / v21 - w12
var w23 = v23 / v21 - w13
var w24 = v24 / v21 - w14
var p = -w23 / w22
var q = w24 / w22
var m = -w12 * p - w13
var n = w14 - w12 * q
var a = n * n + q * q - 1
var b = 2 * m * n - 2 * n * x1 + 2 * p * q - 2 * q * y1 + 2 * s1 * r1
var c = x1 * x1 + m * m - 2 * m * x1 + p * p + y1 * y1 - 2 * p * y1 - r1 * r1
var d = b * b - 4 * a * c
var rs = (-b - d.sqrt) / (2 * a)
var xs = m + n * rs
var ys = p + q * rs
return Circle.new(xs, ys, rs)
}
var c1 = Circle.new(0, 0, 1)
var c2 = Circle.new(4, 0, 1)
var c3 = Circle.new(2, 4, 2)
System.print("Circle%(solveApollonius.call(c1, c2, c3, 1, 1, 1))")
System.print("Circle%(solveApollonius.call(c1, c2, c3, -1, -1, -1))")
|
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.
|
#Yabasic
|
Yabasic
|
print peek$("program_name")
s$ = system$("cd")
n = len(s$)
print left$(s$, n - 2), "\\", peek$("program_name")
|
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.
|
#Zig
|
Zig
|
const std = @import("std");
const debug = std.debug;
const heap = std.heap;
const process = std.process;
pub fn main() !void {
var args = process.args();
const program_name = try args.next(heap.page_allocator) orelse unreachable;
defer heap.page_allocator.free(program_name);
debug.warn("{}\n", .{program_name});
}
|
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.
|
#zkl
|
zkl
|
#!/Homer/craigd/Bin/zkl
println(System.argv);
|
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
|
#Scheme
|
Scheme
|
(use srfi-42)
(define (py perim)
(define prim 0)
(values
(sum-ec
(: c perim) (: b c) (: a b)
(if (and (<= (+ a b c) perim)
(= (square c) (+ (square b) (square a)))))
(begin (when (= 1 (gcd a b)) (inc! prim)))
1)
prim))
|
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.
|
#Scala
|
Scala
|
if (problem) {
// sys.exit returns type "Nothing"
sys.exit(0)
// conventionally, error code 0 is the code for "OK",
// while anything else is an actual problem
}
|
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.
|
#Scheme
|
Scheme
|
(if problem
(exit)) ; exit successfully
|
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
|
#REXX
|
REXX
|
/*REXX pgm tests for primality via Wilson's theorem: a # is prime if p divides (p-1)! +1*/
parse arg LO zz /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 120 /*Not specified? Then use the default.*/
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 /*use default?*/
sw= linesize() - 1; if sw<1 then sw= 79 /*obtain the terminal's screen width. */
digs = digits() /*the current number of decimal digits.*/
#= 0 /*number of (LO) primes found so far.*/
!.= 1 /*placeholder for factorial memoization*/
$= /* " to hold a list of primes.*/
do p=1 until #=LO; oDigs= digs /*remember the number of decimal digits*/
?= isPrimeW(p) /*test primality using Wilson's theorem*/
if digs>Odigs then numeric digits digs /*use larger number for decimal digits?*/
if \? then iterate /*if not prime, then ignore this number*/
#= # + 1; $= $ p /*bump prime counter; add prime to list*/
end /*p*/
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1))) /*used to align the number being tested*/
@is.0= " isn't"; @is.1= 'is' /*2 literals used for display: is/ain't*/
say
do z=1 for words(zz); oDigs= digs /*remember the number of decimal digits*/
p= word(zz, z) /*get a number from user─supplied list.*/
?= isPrimeW(p) /*test primality using Wilson's theorem*/
if digs>Odigs then numeric digits digs /*use larger number for decimal digits?*/
say right(p, max(w,length(p) ) ) @is.? "prime."
end /*z*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0 /*is the number too small to be prime? */
if x==2 | x==5 then return 1 /*is the number a two or a five? */
if last//2==0 | last==5 then return 0 /*is the last decimal digit even or 5? */
if !.xm\==1 then != !.xm /*has the factorial been pre─computed? */
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2 /* [↑] use shortcut.*/
do j=!.0+1 to xm; != ! * j /*compute factorial.*/
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end /* [↑] has exponent,*/
end /*j*/ /*bump numeric digs.*/
if xm<999 then do; !.xm=!; !.0=xm; end /*assign factorial. */
end /*only save small #s*/
if (!+1)//x==0 then return 1 /*X is a prime.*/
return 0 /*" isn't " " */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: parse arg header,oo; say header /*display header for the first N primes*/
w= length( word($, LO) ) /*used to align prime numbers in $ list*/
do k=1 for LO; _= right( word($, k), w) /*build list for displaying the primes.*/
if length(oo _)>sw then do; say substr(oo,2); oo=; end /*a line overflowed?*/
oo= oo _ /*display a line. */
end /*k*/ /*does pretty print.*/
if oo\='' then say substr(oo, 2); return /*display residual (if any overflowed).*/
|
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 %
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "float.s7i";
const func set of integer: eratosthenes (in integer: n) is func
result
var set of integer: sieve is EMPTY_SET;
local
var integer: i is 0;
var integer: j is 0;
begin
sieve := {2 .. n};
for i range 2 to sqrt(n) do
if i in sieve then
for j range i ** 2 to n step i do
excl(sieve, j);
end for;
end if;
end for;
end func;
const type: countHashType is hash [string] integer;
const proc: main is func
local
const set of integer: primes is eratosthenes(15485863);
var integer: lastPrime is 0;
var integer: currentPrime is 0;
var string: aKey is "";
var countHashType: countHash is countHashType.value;
var integer: count is 0;
var integer: total is 0;
begin
for currentPrime range primes do
if lastPrime <> 0 then
incr(total);
aKey := str(lastPrime rem 10) <& " -> " <& str(currentPrime rem 10);
if aKey in countHash then
incr(countHash[aKey]);
else
countHash @:= [aKey] 1;
end if;
end if;
lastPrime := currentPrime;
end for;
for aKey range sort(keys(countHash)) do
count := countHash[aKey];
writeln(aKey <& " count: " <& count lpad 5 <& " frequency: " <&
flt(count * 100)/flt(total) digits 2 lpad 4 <& " %");
end for;
end func;
|
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
|
#Delphi
|
Delphi
|
program Prime_decomposition;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function IsPrime(n: UInt64): Boolean;
var
i: Integer;
begin
if n <= 1 then
exit(False);
i := 2;
while i < Sqrt(n) do
begin
if n mod i = 0 then
exit(False);
inc(i);
end;
Result := True;
end;
function GetPrimes(n: UInt64): TArray<UInt64>;
var
i: Integer;
begin
while n > 1 do
begin
i := 1;
while True do
begin
if IsPrime(i) then
begin
if n / i = (round(n / i)) then
begin
n := n div i;
SetLength(Result, Length(Result) + 1);
Result[High(Result)] := i;
Break;
end;
end;
inc(i);
end;
end;
end;
begin
for var v in GetPrimes(12) do
write(v, ' ');
readln;
end.
|
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.
|
#Go
|
Go
|
var p *int // declare p to be a pointer to an int
i = &p // assign i to be the int value pointed to by p
|
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.
|
#Haskell
|
Haskell
|
import Data.STRef
example :: ST s ()
example = do
p <- newSTRef 1
k <- readSTRef p
writeSTRef p (k+1)
|
http://rosettacode.org/wiki/Plot_coordinate_pairs
|
Plot coordinate pairs
|
Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#Clojure
|
Clojure
|
(use '(incanter core stats charts))
(def x (range 0 10))
(def y '(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0))
(view (xy-plot x y))
|
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
|
#Ceylon
|
Ceylon
|
import ceylon.language {
consolePrint = print
}
shared void run() {
class Point {
shared variable Integer x;
shared variable Integer y;
shared new(Integer x = 0, Integer y = 0) {
this.x = x;
this.y = y;
}
shared new copy(Point p) {
this.x = p.x;
this.y = p.y;
}
shared default void print() {
consolePrint("[Point ``x`` ``y``]");
}
}
class Circle extends Point {
shared variable Integer r;
shared new(Integer x = 0, Integer y = 0, Integer r = 0) extends Point(x, y) {
this.r = r;
}
shared new copy(Circle c) extends Point.copy(c){
this.r = c.r;
}
shared actual void print() {
consolePrint("[Circle ``x`` ``y`` ``r``]");
}
}
value shapes = [
Point(), Point(1), Point(1, 2), Point {y = 3;}, Point.copy(Point(4, 5)),
Circle(), Circle(1), Circle(2, 3), Circle(4, 5, 6), Circle {y = 7; r = 8;}, Circle.copy(Circle(9, 10, 11))
];
for(shape in shapes) {
shape.print();
}
}
|
http://rosettacode.org/wiki/Poker_hand_analyser
|
Poker hand analyser
|
Task
Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
Example
2d (two of diamonds).
Faces are: a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, k
Suits are: h (hearts), d (diamonds), c (clubs), and s (spades), or
alternatively, the unicode card-suit characters: ♥ ♦ ♣ ♠
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
Examples
2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind
2♥ 5♥ 7♦ 8♣ 9♠: high-card
a♥ 2♦ 3♣ 4♣ 5♦: straight
2♥ 3♥ 2♦ 3♣ 3♦: full-house
2♥ 7♥ 2♦ 3♣ 3♦: two-pair
2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind
10♥ j♥ q♥ k♥ a♥: straight-flush
4♥ 4♠ k♠ 5♦ 10♠: one-pair
q♣ 10♣ 7♣ 6♣ q♣: invalid
The programs output for the above examples should be displayed here on this page.
Extra credit
use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
allow two jokers
use the symbol joker
duplicates would be allowed (for jokers only)
five-of-a-kind would then be the highest hand
More extra credit examples
joker 2♦ 2♠ k♠ q♦: three-of-a-kind
joker 5♥ 7♦ 8♠ 9♦: straight
joker 2♦ 3♠ 4♠ 5♠: straight
joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind
joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind
joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind
joker j♥ q♥ k♥ A♥: straight-flush
joker 4♣ k♣ 5♦ 10♠: one-pair
joker k♣ 7♣ 6♣ 4♣: flush
joker 2♦ joker 4♠ 5♠: straight
joker Q♦ joker A♠ 10♠: straight
joker Q♦ joker A♦ 10♦: straight-flush
joker 2♦ 2♠ joker q♦: four-of-a-kind
Related tasks
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Go Fish
|
#Elixir
|
Elixir
|
defmodule Card do
@faces ~w(2 3 4 5 6 7 8 9 10 j q k a)
@suits ~w(♥ ♦ ♣ ♠) # ~w(h d c s)
@ordinal @faces |> Enum.with_index |> Map.new
defstruct ~w[face suit ordinal]a
def new(str) do
{face, suit} = String.split_at(str, -1)
if face in @faces and suit in @suits do
ordinal = @ordinal[face]
%__MODULE__{face: face, suit: suit, ordinal: ordinal}
else
raise ArgumentError, "invalid card: #{str}"
end
end
def deck do
for face <- @faces, suit <- @suits, do: "#{face}#{suit}"
end
end
defmodule Hand do
@ranks ~w(high-card one-pair two-pair three-of-a-kind straight flush
full-house four-of-a-kind straight-flush five-of-a-kind)a |>
Enum.with_index |> Map.new
@wheel_faces ~w(2 3 4 5 a)
def new(str_of_cards) do
cards = String.downcase(str_of_cards) |>
String.split([" ", ","], trim: true) |>
Enum.map(&Card.new &1)
grouped = Enum.group_by(cards, &(&1.ordinal)) |> Map.values
face_pattern = Enum.map(grouped, &(length &1)) |> Enum.sort
{consecutive, wheel_faces} = consecutive?(cards)
rank = categorize(cards, face_pattern, consecutive)
rank_num = @ranks[rank]
tiebreaker = if wheel_faces do
for ord <- 3..-1, do: {1,ord}
else
Enum.map(grouped, &{length(&1), hd(&1).ordinal}) |>
Enum.sort |> Enum.reverse
end
{rank_num, tiebreaker, str_of_cards, rank}
end
defp one_suit?(cards) do
Enum.map(cards, &(&1.suit)) |> Enum.uniq |> length == 1
end
defp consecutive?(cards) do
sorted = Enum.sort_by(cards, &(&1.ordinal))
if Enum.map(sorted, &(&1.face)) == @wheel_faces do
{true, true}
else
flag = Enum.map(sorted, &(&1.ordinal)) |>
Enum.chunk(2,1) |>
Enum.all?(fn [a,b] -> a+1 == b end)
{flag, false}
end
end
defp categorize(cards, face_pattern, consecutive) do
case {consecutive, one_suit?(cards)} do
{true, true} -> :"straight-flush"
{true, false} -> :straight
{false, true} -> :flush
_ -> case face_pattern do
[1,1,1,1,1] -> :"high-card"
[1,1,1,2] -> :"one-pair"
[1,2,2] -> :"two-pair"
[1,1,3] -> :"three-of-a-kind"
[2,3] -> :"full-house"
[1,4] -> :"four-of-a-kind"
[5] -> :"five-of-a-kind"
end
end
end
end
test_hands = """
2♥ 2♦ 2♣ k♣ q♦
2♥ 5♥ 7♦ 8♣ 9♠
a♥ 2♦ 3♣ 4♣ 5♦
2♥ 3♥ 2♦ 3♣ 3♦
2♥ 7♥ 2♦ 3♣ 3♦
2♥ 6♥ 2♦ 3♣ 3♦
10♥ j♥ q♥ k♥ a♥
4♥ 4♠ k♠ 2♦ 10♠
4♥ 4♠ k♠ 3♦ 10♠
q♣ 10♣ 7♣ 6♣ 4♣
q♣ 10♣ 7♣ 6♣ 3♣
9♥ 10♥ q♥ k♥ j♣
2♥ 3♥ 4♥ 5♥ a♥
2♥ 2♥ 2♦ 3♣ 3♦
"""
hands = String.split(test_hands, "\n", trim: true) |> Enum.map(&Hand.new(&1))
IO.puts "High to low"
Enum.sort(hands) |> Enum.reverse |>
Enum.each(fn hand -> IO.puts "#{elem(hand,2)}: \t#{elem(hand,3)}" end)
# Extra Credit 2. Examples:
IO.puts "\nExtra Credit 2"
extra_hands = """
joker 2♦ 2♠ k♠ q♦
joker 5♥ 7♦ 8♠ 9♦
joker 2♦ 3♠ 4♠ 5♠
joker 3♥ 2♦ 3♠ 3♦
joker 7♥ 2♦ 3♠ 3♦
joker 7♥ 7♦ 7♠ 7♣
joker j♥ q♥ k♥ A♥
joker 4♣ k♣ 5♦ 10♠
joker k♣ 7♣ 6♣ 4♣
joker 2♦ joker 4♠ 5♠
joker Q♦ joker A♠ 10♠
joker Q♦ joker A♦ 10♦
joker 2♦ 2♠ joker q♦
"""
deck = Card.deck
String.split(extra_hands, "\n", trim: true) |>
Enum.each(fn hand ->
[a,b,c,d,e] = String.split(hand) |>
Enum.map(fn c -> if c=="joker", do: deck, else: [c] end)
cards_list = for v<-a, w<-b, x<-c, y<-d, z<-e, do: "#{v} #{w} #{x} #{y} #{z}"
best = Enum.map(cards_list, &Hand.new &1) |> Enum.max
IO.puts "#{hand}:\t#{elem(best,3)}"
end)
|
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.
|
#BASIC256
|
BASIC256
|
print "Pop cont (3^x): ";
for i = 0 to 29
print population(3^i); " "; #los últimos números no los muestra correctamente
next i
print : print
print "Evil numbers: ";
call EvilOdious(30, 0)
print : print
print "Odious numbers: ";
call EvilOdious(30, 1)
end
subroutine EvilOdious(limit, type)
i = 0 : cont = 0
do
eo = (population(i) mod 2)
if (type and eo) or (not type and not eo) then
cont += 1 : print i; " ";
end if
i += 1
until (cont = limit)
end subroutine
function population(number)
popul = 0
binary$ = tobinary(number)
for i = 1 to length(binary$)
popul += int(mid(binary$, i, 1))
next i
return popul
end function
|
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
|
#Elixir
|
Elixir
|
defmodule Polynomial do
def division(_, []), do: raise ArgumentError, "denominator is zero"
def division(_, [0]), do: raise ArgumentError, "denominator is zero"
def division(f, g) when length(f) < length(g), do: {[0], f}
def division(f, g) do
{q, r} = division(g, [], f)
if q==[], do: q = [0]
if r==[], do: r = [0]
{q, r}
end
defp division(g, q, r) when length(r) < length(g), do: {q, r}
defp division(g, q, r) do
p = hd(r) / hd(g)
r2 = Enum.zip(r, g)
|> Enum.with_index
|> Enum.reduce(r, fn {{pn,pg},i},acc ->
List.replace_at(acc, i, pn - p * pg)
end)
division(g, q++[p], tl(r2))
end
end
[ { [1, -12, 0, -42], [1, -3] },
{ [1, -12, 0, -42], [1, 1, -3] },
{ [1, 3, 2], [1, 1] },
{ [1, -4, 6, 5, 3], [1, 2, 1] } ]
|> Enum.each(fn {f,g} ->
{q, r} = Polynomial.division(f, g)
IO.puts "#{inspect f} / #{inspect g} => #{inspect q} remainder #{inspect r}"
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
class T()
method a(); write("This is T's a"); end
end
class S: T()
method a(); write("This is S's a"); end
end
procedure main()
write("S:",deepcopy(S()).a())
end
procedure deepcopy(A, cache) #: return a deepcopy of A
local k
/cache := table() # used to handle multireferenced objects
if \cache[A] then return cache[A]
case type(A) of {
"table"|"list": {
cache[A] := copy(A)
every cache[A][k := key(A)] := deepcopy(A[k], cache)
}
"set": {
cache[A] := set()
every insert(cache[A], deepcopy(!A, cache))
}
default: { # records and objects (encoded as records)
cache[A] := copy(A)
if match("record ",image(A)) then {
every cache[A][k := key(A)] := deepcopy(A[k], cache)
}
}
}
return .cache[A]
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
|
#Racket
|
Racket
|
#lang racket
(require 2htdp/universe pict racket/draw)
(define ((polyspiral width height segment-length-increment n-segments) tick/s/28)
(define turn-angle (degrees->radians (/ tick/s/28 8)))
(pict->bitmap
(dc (λ (dc dx dy)
(define old-brush (send dc get-brush))
(define old-pen (send dc get-pen))
(define path (new dc-path%))
(define x (/ width #i2))
(define y (/ height #i2))
(send path move-to x y)
(for/fold ((x x) (y y) (l segment-length-increment) (a #i0))
((seg n-segments))
(define x′ (+ x (* l (cos a))))
(define y′ (+ y (* l (sin a))))
(send path line-to x y)
(values x′ y′ (+ l segment-length-increment) (+ a turn-angle)))
(send dc draw-path path dx dy)
(send* dc (set-brush old-brush) (set-pen old-pen)))
width height)))
(animate (polyspiral 400 400 2 1000))
|
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
|
#Raku
|
Raku
|
use SVG;
my $w = 600;
my $h = 600;
for 3..33 -> $a {
my $angle = $a/τ;
my $x1 = $w/2;
my $y1 = $h/2;
my @lines;
for 1..144 {
my $length = 3 * $_;
my ($x2, $y2) = ($x1, $y1) «+« |cis($angle * $_).reals».round(.01) »*» $length ;
@lines.push: 'line' => [:x1($x1.clone), :y1($y1.clone), :x2($x2.clone), :y2($y2.clone),
:style("stroke:rgb({hsv2rgb(($_*5 % 360)/360,1,1).join: ','})")];
($x1, $y1) = $x2, $y2;
}
my $fname = "./polyspiral-perl6.svg".IO.open(:w);
$fname.say( SVG.serialize(
svg => [
width => $w, height => $h, style => 'stroke:rgb(0,0,0)',
:rect[:width<100%>, :height<100%>, :fill<black>],
|@lines,
],)
);
$fname.close;
sleep .15;
}
sub hsv2rgb ( $h, $s, $v ){ # inputs normalized 0-1
my $c = $v * $s;
my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) );
my $m = $v - $c;
my ($r, $g, $b) = do given $h {
when 0..^(1/6) { $c, $x, 0 }
when 1/6..^(1/3) { $x, $c, 0 }
when 1/3..^(1/2) { 0, $c, $x }
when 1/2..^(2/3) { 0, $x, $c }
when 2/3..^(5/6) { $x, 0, $c }
when 5/6..1 { $c, 0, $x }
}
( $r, $g, $b ).map: ((*+$m) * 255).Int
}
|
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.
|
#GAP
|
GAP
|
PolynomialRegression := function(x, y, n)
local a;
a := List([0 .. n], i -> List(x, s -> s^i));
return TransposedMat((a * TransposedMat(a))^-1 * a * TransposedMat([y]))[1];
end;
x := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
y := [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
# Return coefficients in ascending degree order
PolynomialRegression(x, y, 2);
# [ 1, 2, 3 ]
|
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.
|
#Clojure
|
Clojure
|
(use '[clojure.math.combinatorics :only [subsets] ])
(def S #{1 2 3 4})
user> (subsets S)
(() (1) (2) (3) (4) (1 2) (1 3) (1 4) (2 3) (2 4) (3 4) (1 2 3) (1 2 4) (1 3 4) (2 3 4) (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
|
#BBC_BASIC
|
BBC BASIC
|
FOR i% = -1 TO 100
IF FNisprime(i%) PRINT ; i% " is prime"
NEXT
END
DEF FNisprime(n%)
IF n% <= 1 THEN = FALSE
IF n% <= 3 THEN = TRUE
IF (n% AND 1) = 0 THEN = FALSE
LOCAL t%
FOR t% = 3 TO SQR(n%) STEP 2
IF n% MOD t% = 0 THEN = FALSE
NEXT
= TRUE
|
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
|
#Erlang
|
Erlang
|
priceFraction(N) when N < 0 orelse N > 1 ->
erlang:error('Values must be between 0 and 1.');
priceFraction(N) when N < 0.06 -> 0.10;
priceFraction(N) when N < 0.11 -> 0.18;
priceFraction(N) when N < 0.16 -> 0.26;
priceFraction(N) when N < 0.21 -> 0.32;
priceFraction(N) when N < 0.26 -> 0.38;
priceFraction(N) when N < 0.31 -> 0.44;
priceFraction(N) when N < 0.36 -> 0.50;
priceFraction(N) when N < 0.41 -> 0.54;
priceFraction(N) when N < 0.46 -> 0.58;
priceFraction(N) when N < 0.51 -> 0.62;
priceFraction(N) when N < 0.56 -> 0.66;
priceFraction(N) when N < 0.61 -> 0.70;
priceFraction(N) when N < 0.66 -> 0.74;
priceFraction(N) when N < 0.71 -> 0.78;
priceFraction(N) when N < 0.76 -> 0.82;
priceFraction(N) when N < 0.81 -> 0.86;
priceFraction(N) when N < 0.86 -> 0.90;
priceFraction(N) when N < 0.91 -> 0.94;
priceFraction(N) when N < 0.96 -> 0.98;
priceFraction(N) -> 1.00.
|
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
|
#Go
|
Go
|
package main
import (
"fmt"
"strconv"
)
func listProperDivisors(limit int) {
if limit < 1 {
return
}
width := len(strconv.Itoa(limit))
for i := 1; i <= limit; i++ {
fmt.Printf("%*d -> ", width, i)
if i == 1 {
fmt.Println("(None)")
continue
}
for j := 1; j <= i/2; j++ {
if i%j == 0 {
fmt.Printf(" %d", j)
}
}
fmt.Println()
}
}
func countProperDivisors(n int) int {
if n < 2 {
return 0
}
count := 0
for i := 1; i <= n/2; i++ {
if n%i == 0 {
count++
}
}
return count
}
func main() {
fmt.Println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
fmt.Println()
maxCount := 0
most := []int{1}
for n := 2; n <= 20000; n++ {
count := countProperDivisors(n)
if count == maxCount {
most = append(most, n)
} else if count > maxCount {
maxCount = count
most = most[0:1]
most[0] = n
}
}
fmt.Print("The following number(s) <= 20000 have the most proper divisors, ")
fmt.Println("namely", maxCount, "\b\n")
for _, n := range most {
fmt.Println(n)
}
}
|
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)
|
#PARI.2FGP
|
PARI/GP
|
pc()={
my(v=[5544,10164,14124,17589,20669,23441,25961,27720],u=vector(8),e);
for(i=1,1e6,
my(r=random(27720));
for(j=1,8,
if(r<v[j], u[j]++; break)
)
);
e=precision([1/5,1/6,1/7,1/8,1/9,1/10,1/11,1759/27720]*1e6,9); \\ truncate to 9 decimal places
print("Totals: "u);
print("Expected: "e);
print("Diff: ",u-e);
print("StDev: ",vector(8,i,sqrt(abs(u[i]-v[i])/e[i])));
};
|
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.
|
#Kotlin
|
Kotlin
|
import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
}
|
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.
|
#zkl
|
zkl
|
class Circle{
fcn init(xpos,ypos,radius){
var [const] x=xpos.toFloat(), y=ypos.toFloat(),r=radius.toFloat();
}
fcn toString{ "Circle(%f,%f,%f)".fmt(x,y,r) }
fcn apollonius(c2,c3,outside=True){
s1:=s2:=s3:=outside and 1 or -1;
v11:=2.0*(c2.x - x);
v12:=2.0*(c2.y - y);
v13:=x.pow(2) - c2.x.pow(2) +
y.pow(2) - c2.y.pow(2) -
r.pow(2) + c2.r.pow(2);
v14:=2.0*(s2*c2.r - s1*r);
v21:=2.0*(c3.x - c2.x);
v22:=2.0*(c3.y - c2.y);
v23:=c2.x.pow(2) - c3.x.pow(2) +
c2.y.pow(2) - c3.y.pow(2) -
c2.r.pow(2) + c3.r.pow(2);
v24:=2.0*(s3*c3.r - s2*c2.r);
w12,w13,w14:=v12/v11, v13/v11, v14/v11;
w22,w23,w24:=v22/v21 - w12, v23/v21 - w13, 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.0*(M*N - N*x + P*Q - Q*y + s1*r);
c:=x*x + M*M - 2.0*M*x + P*P + y*y - 2.0*P*y - r*r;
// find a root of a quadratic equation.
// This requires the circle centers not to be e.g. colinear
D:=b*b - 4.0*a*c;
rs:=(-b - D.sqrt())/(2.0*a);
Circle(M + N*rs, P + Q*rs, rs);
}
}
|
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
|
#Scratch
|
Scratch
|
$ include "seed7_05.s7i";
include "bigint.s7i";
var bigInteger: total is 0_;
var bigInteger: prim is 0_;
var bigInteger: max_peri is 10_;
const proc: new_tri (in bigInteger: a, in bigInteger: b, in bigInteger: c) is func
local
var bigInteger: p is 0_;
begin
p := a + b + c;
if p <= max_peri then
incr(prim);
total +:= max_peri div p;
new_tri( a - 2_*b + 2_*c, 2_*a - b + 2_*c, 2_*a - 2_*b + 3_*c);
new_tri( a + 2_*b + 2_*c, 2_*a + b + 2_*c, 2_*a + 2_*b + 3_*c);
new_tri(-a + 2_*b + 2_*c, -2_*a + b + 2_*c, -2_*a + 2_*b + 3_*c);
end if;
end func;
const proc: main is func
begin
while max_peri <= 100000000_ do
total := 0_;
prim := 0_;
new_tri(3_, 4_, 5_);
writeln("Up to " <& max_peri <& ": " <& total <& " triples, " <& prim <& " primitives.");
max_peri *:= 10_;
end while;
end func;
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
const proc: main is func
begin
# whatever logic is required in your main procedure
if some_condition then
exit(PROGRAM);
end if;
end func;
|
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.
|
#SenseTalk
|
SenseTalk
|
if problemCondition then exit all
|
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
|
#Ring
|
Ring
|
load "stdlib.ring"
decimals(0)
limit = 19
for n = 2 to limit
fact = factorial(n-1) + 1
see "Is " + n + " prime: "
if fact % n = 0
see "1" + nl
else
see "0" + nl
ok
next
|
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
|
#Ruby
|
Ruby
|
def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
|
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 %
|
#Sidef
|
Sidef
|
var primes = (^Inf -> lazy.grep{.is_prime})
var upto = 1e6
var conspiracy = Hash()
primes.first(upto+1).reduce { |a,b|
var d = b%10
conspiracy{"#{a} → #{d}"} := 0 ++
d
}
for k,v in (conspiracy.sort_by{|k,_v| k }) {
printf("%s count: %6s\tfrequency: %2.2f %\n", k, v.commify, v / upto * 100)
}
|
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
|
#E
|
E
|
def primes := {
var primesCache := [2]
/** A collection of all prime numbers. */
def primes {
to iterate(f) {
primesCache.iterate(f)
for x in (int > primesCache.last()) {
if (isPrime(x)) {
f(primesCache.size(), x)
primesCache with= x
}
}
}
}
}
def primeDecomposition(var x :(int > 0)) {
var factors := []
for p in primes {
while (x % p <=> 0) {
factors with= p
x //= p
}
if (x <=> 1) {
break
}
}
return factors
}
|
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.
|
#Icon_and_Unicon
|
Icon and Unicon
|
public class Foo { public int x = 0; }
void somefunction() {
Foo a; // this declares a reference to Foo object; if this is a class field, it is initialized to null
a = new Foo(); // this assigns a to point to a new Foo object
Foo b = a; // this declares another reference to point to the same object that "a" points to
a.x = 5; // this modifies the "x" field of the object pointed to by "a"
System.out.println(b.x); // this prints 5, because "b" points to the same object as "a"
}
|
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.
|
#J
|
J
|
public class Foo { public int x = 0; }
void somefunction() {
Foo a; // this declares a reference to Foo object; if this is a class field, it is initialized to null
a = new Foo(); // this assigns a to point to a new Foo object
Foo b = a; // this declares another reference to point to the same object that "a" points to
a.x = 5; // this modifies the "x" field of the object pointed to by "a"
System.out.println(b.x); // this prints 5, because "b" points to the same object as "a"
}
|
http://rosettacode.org/wiki/Plot_coordinate_pairs
|
Plot coordinate pairs
|
Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#Delphi
|
Delphi
|
program Plot_coordinate_pairs;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Process;
var
x: TArray<Integer>;
y: TArray<Double>;
begin
x := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
y := [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0];
var plot := TPipe.Create('gnuplot -p', True);
plot.WriteA('unset key; plot ''-'''#10);
for var i := 0 to High(x) do
plot.WriteA(format('%d %f'#10, [x[i], y[i]]));
plot.writeA('e'#10);
writeln('Press enter to close');
Readln;
plot.Kill;
plot.Free;
readln;
end.
|
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
|
#Clojure
|
Clojure
|
(defprotocol Printable
(print-it [this] "Prints out the Printable."))
(deftype Point [x y]
Printable
(print-it [this] (println (str "Point: " x " " y))))
(defn create-point
"Redundant constructor function."
[x y] (Point. x y))
(deftype Circle [x y r]
Printable
(print-it [this] (println (str "Circle: " x " " y " " r))))
(defn create-circle
"Redundant consturctor function."
[x y r] (Circle. x y r))
|
http://rosettacode.org/wiki/Poker_hand_analyser
|
Poker hand analyser
|
Task
Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
Example
2d (two of diamonds).
Faces are: a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, k
Suits are: h (hearts), d (diamonds), c (clubs), and s (spades), or
alternatively, the unicode card-suit characters: ♥ ♦ ♣ ♠
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
Examples
2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind
2♥ 5♥ 7♦ 8♣ 9♠: high-card
a♥ 2♦ 3♣ 4♣ 5♦: straight
2♥ 3♥ 2♦ 3♣ 3♦: full-house
2♥ 7♥ 2♦ 3♣ 3♦: two-pair
2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind
10♥ j♥ q♥ k♥ a♥: straight-flush
4♥ 4♠ k♠ 5♦ 10♠: one-pair
q♣ 10♣ 7♣ 6♣ q♣: invalid
The programs output for the above examples should be displayed here on this page.
Extra credit
use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
allow two jokers
use the symbol joker
duplicates would be allowed (for jokers only)
five-of-a-kind would then be the highest hand
More extra credit examples
joker 2♦ 2♠ k♠ q♦: three-of-a-kind
joker 5♥ 7♦ 8♠ 9♦: straight
joker 2♦ 3♠ 4♠ 5♠: straight
joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind
joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind
joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind
joker j♥ q♥ k♥ A♥: straight-flush
joker 4♣ k♣ 5♦ 10♠: one-pair
joker k♣ 7♣ 6♣ 4♣: flush
joker 2♦ joker 4♠ 5♠: straight
joker Q♦ joker A♠ 10♠: straight
joker Q♦ joker A♦ 10♦: straight-flush
joker 2♦ 2♠ joker q♦: four-of-a-kind
Related tasks
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Go Fish
|
#F.23
|
F#
|
type Card = int * int
type Cards = Card list
let joker = (69,69)
let rankInvalid = "invalid", 99
let allCards = {0..12} |> Seq.collect (fun x->({0..3} |> Seq.map (fun y->x,y)))
let allSame = function | y::ys -> List.forall ((=) y) ys | _-> false
let straightList (xs:int list) = xs |> List.sort |> List.mapi (fun i n->n - i) |> allSame
let cardList (s:string): Cards =
s.Split() |> Seq.map (fun s->s.ToLower())
|> Seq.map (fun s ->
if s="joker" then joker
else
match (s |> List.ofSeq) with
| '1'::'0'::xs -> (9, xs) | '!'::xs -> (-1, xs) | x::xs-> ("a23456789!jqk".IndexOf(x), xs) | _ as xs-> (-1, xs)
|> function | -1, _ -> (-1, '!') | x, y::[] -> (x, y) | _ -> (-1, '!')
|> function
| x, 'h' | x, '♥' -> (x, 0) | x, 'd' | x, '♦' -> (x, 1) | x, 'c' | x, '♣' -> (x, 2)
| x, 's' | x, '♠' -> (x, 3) | _ -> (-1, -1)
)
|> Seq.filter (fst >> ((<>) -1)) |> List.ofSeq
let rank (cards: Cards) =
if cards.Length<>5 then rankInvalid
else
let cts = cards |> Seq.groupBy fst |> Seq.map (snd >> Seq.length) |> List.ofSeq |> List.sort |> List.rev
if cts.[0]=5 then ("five-of-a-kind", 1)
else
let flush = cards |> List.map snd |> allSame
let straight =
let (ACE, ALT_ACE) = 0, 13
let faces = cards |> List.map fst |> List.sort
(straightList faces) || (if faces.Head<>ACE then false else (straightList (ALT_ACE::(faces.Tail))))
if straight && flush then ("straight-flush", 2)
else
let cts = cards |> Seq.groupBy fst |> Seq.map (snd >> Seq.length) |> List.ofSeq |> List.sort |> List.rev
if cts.[0]=4 then ("four-of-a-kind", 3)
elif cts.[0]=3 && cts.[1]=2 then ("full-house", 4)
elif flush then ("flush", 5)
elif straight then ("straight", 6)
elif cts.[0]=3 then ("three-of-a-kind", 7)
elif cts.[0]=2 && cts.[1]=2 then ("two-pair", 8)
elif cts.[0]=2 then ("one-pair", 9)
else ("high-card", 10)
let pickBest (xs: seq<Cards>) =
let cmp a b = (<) (snd a) (snd b)
let pick currentBest x = if (cmp (snd x) (snd currentBest)) then x else currentBest
xs |> Seq.map (fun x->x, (rank x)) |> Seq.fold pick ([], rankInvalid)
let calcHandRank handStr =
let cards = handStr |> cardList
if cards.Length<>5
then (cards, rankInvalid)
else
cards |> List.partition ((=) joker) |> fun (x,y) -> x.Length, y
|> function
| (0,xs) when (xs |> Seq.distinct |> Seq.length)=5 -> xs, (rank xs)
| (1,xs) -> allCards |> Seq.map (fun x->x::xs) |> pickBest
| (2,xs) -> allCards |> Seq.collect (fun x->allCards |> Seq.map (fun y->y::x::xs)) |> pickBest
| _ -> cards, rankInvalid
let showHandRank handStr =
// handStr |> calcHandRank |> fun (cards, (rankName,_)) -> printfn "%s: %A %s" handStr cards rankName
handStr |> calcHandRank |> (snd >> fst) |> printfn "%s: %s" handStr
[
"2♥ 2♦ 2♣ k♣ q♦"
"2♥ 5♥ 7♦ 8♣ 9♠"
"a♥ 2♦ 3♣ 4♣ 5♦"
"2♥ 3♥ 2♦ 3♣ 3♦"
"2♥ 7♥ 2♦ 3♣ 3♦"
"2♥ 7♥ 7♦ 7♣ 7♠"
"10♥ j♥ q♥ k♥ a♥"
"4♥ 4♠ k♠ 5♦ 10♠"
"q♣ 10♣ 7♣ 6♣ 4♣"
"joker 2♦ 2♠ k♠ q♦"
"joker 5♥ 7♦ 8♠ 9♦"
"joker 2♦ 3♠ 4♠ 5♠"
"joker 3♥ 2♦ 3♠ 3♦"
"joker 7♥ 2♦ 3♠ 3♦"
"joker 7♥ 7♦ 7♠ 7♣"
"joker j♥ q♥ k♥ A♥"
"joker 4♣ k♣ 5♦ 10♠"
"joker k♣ 7♣ 6♣ 4♣"
"joker 2♦ joker 4♠ 5♠"
"joker Q♦ joker A♠ 10♠"
"joker Q♦ joker A♦ 10♦"
"joker 2♦ 2♠ joker q♦"
]
|> List.iter showHandRank
|
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.
|
#BCPL
|
BCPL
|
get "libhdr"
// Definitions
let popcount(n) = n=0 -> 0, (n&1) + popcount(n >> 1)
let evil(n) = (popcount(n) & 1) = 0
let odious(n) = (popcount(n) & 1) = 1
// The BCPL word size is implementation-dependent,
// but very unlikely to be big enough to store 3^29.
// This implements a 48-bit integer using byte strings.
let move48(dest, src) be
for i=0 to 5 do dest%i := src%i
let set48(dest, n) be
for i=5 to 0 by -1
$( dest%i := n & #XFF
n := n >> 8
$)
let add48(dest, src) be
$( let temp = ? and carry = 0
for i=5 to 0 by -1
$( temp := dest%i + src%i + carry
carry := temp > #XFF -> 1, 0
dest%i := temp & #XFF
$)
$)
let mul3(n) be
$( let temp = vec 2 // big enough even on a 16-bit machine
move48(temp, n)
add48(n, n)
add48(n, temp)
$)
let popcount48(n) = valof
$( let total = 0
for i=0 to 5 do
total := total + popcount(n%i)
resultis total
$)
// print the first N numbers
let printFirst(amt, prec) be
$( let seen = 0 and n = 0
until seen >= amt
$( if prec(n)
$( writed(n, 3)
seen := seen + 1
$)
n := n + 1
$)
wrch('*N')
$)
let start() be
$( let pow3 = vec 2
// print 3^0 to 3^29
set48(pow3, 1)
for i = 0 to 29
$( writed(popcount48(pow3), 3)
mul3(pow3)
$)
wrch('*N')
// print the first 30 evil and odious numbers
printFirst(30, evil)
printFirst(30, odious)
$)
|
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
|
#F.23
|
F#
|
let rec shift n l = if n <= 0 then l else shift (n-1) (l @ [0.0])
let rec pad n l = if n <= 0 then l else pad (n-1) (0.0 :: l)
let rec norm = function | 0.0 :: tl -> norm tl | x -> x
let deg l = List.length (norm l) - 1
let zip op p q =
let d = (List.length p) - (List.length q) in
List.map2 op (pad (-d) p) (pad d q)
let polydiv f g =
let rec aux f s q =
let ddif = (deg f) - (deg s) in
if ddif < 0 then (q, f) else
let k = (List.head f) / (List.head s) in
let ks = List.map ((*) k) (shift ddif s) in
let q' = zip (+) q (shift ddif [k])
let f' = norm (List.tail (zip (-) f ks)) in
aux f' s q' in
aux (norm f) (norm g) []
let str_poly l =
let term v p = match (v, p) with
| ( _, 0) -> string v
| (1.0, 1) -> "x"
| ( _, 1) -> (string v) + "*x"
| (1.0, _) -> "x^" + (string p)
| _ -> (string v) + "*x^" + (string p) in
let rec terms = function
| [] -> []
| h :: t ->
if h = 0.0 then (terms t) else (term h (List.length t)) :: (terms t) in
String.concat " + " (terms l)
let _ =
let f,g = [1.0; -4.0; 6.0; 5.0; 3.0], [1.0; 2.0; 1.0] in
let q, r = polydiv f g in
Printf.printf
" (%s) div (%s)\ngives\nquotient:\t(%s)\nremainder:\t(%s)\n"
(str_poly f) (str_poly g) (str_poly q) (str_poly 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.
|
#J
|
J
|
def=: abc
|
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.
|
#Java
|
Java
|
class T implements Cloneable {
public String name() { return "T"; }
public T copy() {
try {
return (T)super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
class S extends T {
public String name() { return "S"; }
}
public class PolymorphicCopy {
public static T copier(T x) { return x.copy(); }
public static void main(String[] args) {
T obj1 = new T();
S obj2 = new S();
System.out.println(copier(obj1).name()); // prints "T"
System.out.println(copier(obj2).name()); // prints "S"
}
}
|
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
|
#Ring
|
Ring
|
# Project : Polyspiral
load "guilib.ring"
paint = null
incr = 1
x1 = 1000
y1 = 1080
angle = 10
length = 10
new qapp
{
win1 = new qwidget() {
setwindowtitle("")
setgeometry(10,10,1000,1080)
label1 = new qlabel(win1) {
setgeometry(10,10,1000,1080)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,30,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
for i = 1 to 150
x2 = x1 + cos(angle) * length
y2 = y1 + sin(angle) * length
drawline(x1, y1, x2, y2)
x1 = x2
y1 = y2
length = length + 3
angle = (angle + incr) % 360
next
endpaint()
}
label1 { setpicture(p1) show() }
|
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
|
#Scala
|
Scala
|
import java.awt._
import java.awt.event.ActionEvent
import javax.swing._
object PolySpiral extends App {
SwingUtilities.invokeLater(() =>
new JFrame("PolySpiral") {
class PolySpiral extends JPanel {
private var inc = 0.0
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawSpiral(g: Graphics2D, l: Int, angleIncrement: Double): Unit = {
var len = l
var (x1, y1) = (getWidth / 2d, getHeight / 2d)
var angle = angleIncrement
for (i <- 0 until 150) {
g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f))
val x2 = x1 + math.cos(angle) * len
val y2 = y1 - math.sin(angle) * len
g.drawLine(x1.toInt, y1.toInt, x2.toInt, y2.toInt)
x1 = x2
y1 = y2
len += 3
angle = (angle + angleIncrement) % (math.Pi * 2)
}
}
super.paintComponent(gg)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawSpiral(g, 5, math.toRadians(inc))
}
setBackground(Color.white)
setPreferredSize(new Dimension(640, 640))
new Timer(40, (_: ActionEvent) => {
inc = (inc + 0.05) % 360
repaint()
}).start()
}
add(new PolySpiral, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(true)
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.
|
#gnuplot
|
gnuplot
|
# The polynomial approximation
f(x) = a*x**2 + b*x + c
# Initial values for parameters
a = 0.1
b = 0.1
c = 0.1
# Fit f to the following data by modifying the variables a, b, c
fit f(x) '-' via a, b, c
0 1
1 6
2 17
3 34
4 57
5 86
6 121
7 162
8 209
9 262
10 321
e
print sprintf("\n --- \n Polynomial fit: %.4f x^2 + %.4f x + %.4f\n", a, b, c)
|
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.
|
#CoffeeScript
|
CoffeeScript
|
print_power_set = (arr) ->
console.log "POWER SET of #{arr}"
for subset in power_set(arr)
console.log subset
power_set = (arr) ->
result = []
binary = (false for elem in arr)
n = arr.length
while binary.length <= n
result.push bin_to_arr binary, arr
i = 0
while true
if binary[i]
binary[i] = false
i += 1
else
binary[i] = true
break
binary[i] = true
result
bin_to_arr = (binary, arr) ->
(arr[i] for i of binary when binary[arr.length - i - 1])
print_power_set []
print_power_set [4, 2, 1]
print_power_set ['dog', 'c', 'b', 'a']
|
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
|
#bc
|
bc
|
/* Return 1 if n is prime, 0 otherwise */
define p(n) {
auto i
if (n < 2) return(0)
if (n == 2) return(1)
if (n % 2 == 0) return(0)
for (i = 3; i * i <= n; i += 2) {
if (n % i == 0) return(0)
}
return(1)
}
|
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
|
#Euphoria
|
Euphoria
|
constant table = {
{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}
}
function price_fix(atom x)
for i = 1 to length(table) do
if x < table[i][1] then
return table[i][2]
end if
end for
return -1
end function
for i = 0 to 99 do
printf(1, "%.2f %.2f\n", { i/100, price_fix(i/100) })
end for
|
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
|
#Haskell
|
Haskell
|
import Data.Ord
import Data.List
divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
main :: IO ()
main = do
putStrLn "divisors of 1 to 10:"
mapM_ (print . divisors) [1 .. 10]
putStrLn "a number with the most divisors within 1 to 20000 (number, count):"
print $ maximumBy (comparing snd)
[(n, length $ divisors n) | n <- [1 .. 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)
|
#Perl
|
Perl
|
use List::Util qw(first sum);
use constant TRIALS => 1e6;
sub prob_choice_picker {
my %options = @_;
my ($n, @a) = 0;
while (my ($k,$v) = each %options) {
$n += $v;
push @a, [$n, $k];
}
return sub {
my $r = rand;
( first {$r <= $_->[0]} @a )->[1];
};
}
my %ps =
(aleph => 1/5,
beth => 1/6,
gimel => 1/7,
daleth => 1/8,
he => 1/9,
waw => 1/10,
zayin => 1/11);
$ps{heth} = 1 - sum values %ps;
my $picker = prob_choice_picker %ps;
my %results;
for (my $n = 0 ; $n < TRIALS ; ++$n) {
++$results{$picker->()};
}
print "Event Occurred Expected Difference\n";
foreach (sort {$results{$b} <=> $results{$a}} keys %results) {
printf "%-6s %f %f %f\n",
$_, $results{$_}/TRIALS, $ps{$_},
abs($results{$_}/TRIALS - $ps{$_});
}
|
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.
|
#Lasso
|
Lasso
|
define priorityQueue => type {
data
store = map,
cur_priority = void
public push(priority::integer, value) => {
local(store) = .`store`->find(#priority)
if(#store->isA(::array)) => {
#store->insert(#value)
return
}
.`store`->insert(#priority=array(#value))
.`cur_priority`->isA(::void) or #priority < .`cur_priority`
? .`cur_priority` = #priority
}
public pop => {
.`cur_priority` == void
? return void
local(store) = .`store`->find(.`cur_priority`)
local(retVal) = #store->first
#store->removeFirst&size > 0
? return #retVal
// Need to find next priority
.`store`->remove(.`cur_priority`)
if(.`store`->size == 0) => {
.`cur_priority` = void
else
// There are better / faster ways to do this
// The keys are actually already sorted, but the order of
// storage in a map is not actually defined, can't rely on it
.`cur_priority` = .`store`->keys->asArray->sort&first
}
return #retVal
}
public isEmpty => (.`store`->size == 0)
}
local(test) = priorityQueue
#test->push(2,`e`)
#test->push(1,`H`)
#test->push(5,`o`)
#test->push(2,`l`)
#test->push(5,`!`)
#test->push(4,`l`)
while(not #test->isEmpty) => {
stdout(#test->pop)
}
|
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
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "bigint.s7i";
var bigInteger: total is 0_;
var bigInteger: prim is 0_;
var bigInteger: max_peri is 10_;
const proc: new_tri (in bigInteger: a, in bigInteger: b, in bigInteger: c) is func
local
var bigInteger: p is 0_;
begin
p := a + b + c;
if p <= max_peri then
incr(prim);
total +:= max_peri div p;
new_tri( a - 2_*b + 2_*c, 2_*a - b + 2_*c, 2_*a - 2_*b + 3_*c);
new_tri( a + 2_*b + 2_*c, 2_*a + b + 2_*c, 2_*a + 2_*b + 3_*c);
new_tri(-a + 2_*b + 2_*c, -2_*a + b + 2_*c, -2_*a + 2_*b + 3_*c);
end if;
end func;
const proc: main is func
begin
while max_peri <= 100000000_ do
total := 0_;
prim := 0_;
new_tri(3_, 4_, 5_);
writeln("Up to " <& max_peri <& ": " <& total <& " triples, " <& prim <& " primitives.");
max_peri *:= 10_;
end while;
end func;
|
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.
|
#Sidef
|
Sidef
|
if (problem) {
Sys.exit(code);
}
|
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.
|
#Simula
|
Simula
|
IF terminallyIll THEN terminate_program;
|
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
|
#Rust
|
Rust
|
fn factorial_mod(mut n: u32, p: u32) -> u32 {
let mut f = 1;
while n != 0 && f != 0 {
f = (f * n) % p;
n -= 1;
}
f
}
fn is_prime(p: u32) -> bool {
p > 1 && factorial_mod(p - 1, p) == p - 1
}
fn main() {
println!(" n | prime?\n------------");
for p in vec![2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659] {
println!("{:>3} | {}", p, is_prime(p));
}
println!("\nFirst 120 primes by Wilson's theorem:");
let mut n = 0;
let mut p = 1;
while n < 120 {
if is_prime(p) {
n += 1;
print!("{:>3}{}", p, if n % 20 == 0 { '\n' } else { ' ' });
}
p += 1;
}
println!("\n1000th through 1015th primes:");
let mut i = 0;
while n < 1015 {
if is_prime(p) {
n += 1;
if n >= 1000 {
i += 1;
print!("{:>3}{}", p, if i % 16 == 0 { '\n' } else { ' ' });
}
}
p += 1;
}
}
|
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
|
#Sidef
|
Sidef
|
func is_wilson_prime_slow(n) {
n > 1 || return false
(n-1)! % n == n-1
}
func is_wilson_prime_fast(n) {
n > 1 || return false
factorialmod(n-1, n) == n-1
}
say 25.by(is_wilson_prime_slow) #=> [2, 3, 5, ..., 83, 89, 97]
say 25.by(is_wilson_prime_fast) #=> [2, 3, 5, ..., 83, 89, 97]
say is_wilson_prime_fast(2**43 - 1) #=> false
say is_wilson_prime_fast(2**61 - 1) #=> true
|
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 %
|
#VBA
|
VBA
|
Option Explicit
Sub Main()
Dim Dict As Object, L() As Long
Dim t As Single
Init Dict
L = ListPrimes(100000000)
t = Timer
PrimeConspiracy L, Dict, 1000000
Debug.Print "----------------------------"
Debug.Print "Execution time : " & Format(Timer - t, "0.000s.")
Debug.Print ""
Init Dict
t = Timer
PrimeConspiracy L, Dict, 5000000
Debug.Print "----------------------------"
Debug.Print "Execution time : " & Format(Timer - t, "0.000s.")
End Sub
Private Function ListPrimes(MAX As Long) As Long()
'http://rosettacode.org/wiki/Extensible_prime_generator#VBA
Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long
ReDim t(2 To MAX)
ReDim L(MAX \ 2)
s = Sqr(MAX)
For i = 3 To s Step 2
If t(i) = False Then
For j = i * i To MAX Step i
t(j) = True
Next
End If
Next i
L(0) = 2
For i = 3 To MAX Step 2
If t(i) = False Then
c = c + 1
L(c) = i
End If
Next i
ReDim Preserve L(c)
ListPrimes = L
End Function
Private Sub Init(d As Object)
Set d = CreateObject("Scripting.Dictionary")
d("1 to 1") = 0
d("1 to 3") = 0
d("1 to 7") = 0
d("1 to 9") = 0
d("2 to 3") = 0
d("3 to 1") = 0
d("3 to 3") = 0
d("3 to 5") = 0
d("3 to 7") = 0
d("3 to 9") = 0
d("5 to 7") = 0
d("7 to 1") = 0
d("7 to 3") = 0
d("7 to 7") = 0
d("7 to 9") = 0
d("9 to 1") = 0
d("9 to 3") = 0
d("9 to 7") = 0
d("9 to 9") = 0
End Sub
Private Sub PrimeConspiracy(Primes() As Long, Dict As Object, Nb)
Dim n As Long, temp As String, r, s, K
For n = LBound(Primes) To Nb
r = CStr((Primes(n)))
s = CStr((Primes(n + 1)))
temp = Right(r, 1) & " to " & Right(s, 1)
If Dict.Exists(temp) Then Dict(temp) = Dict(temp) + 1
Next
Debug.Print Nb & " primes, last prime considered: " & Primes(Nb)
Debug.Print "Transition Count Frequency"
Debug.Print "========== ======= ========="
For Each K In Dict.Keys
Debug.Print K & " " & Right(" " & Dict(K), 6) & " " & Dict(K) / Nb * 100 & "%"
Next
End Sub
|
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
|
#EchoLisp
|
EchoLisp
|
(prime-factors 1024)
→ (2 2 2 2 2 2 2 2 2 2)
(lib 'bigint)
;; 2^59 - 1
(prime-factors (1- (expt 2 59)))
→ (179951 3203431780337)
(prime-factors 100000000000000000037)
→ (31 821 66590107 59004541)
|
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.
|
#Java
|
Java
|
public class Foo { public int x = 0; }
void somefunction() {
Foo a; // this declares a reference to Foo object; if this is a class field, it is initialized to null
a = new Foo(); // this assigns a to point to a new Foo object
Foo b = a; // this declares another reference to point to the same object that "a" points to
a.x = 5; // this modifies the "x" field of the object pointed to by "a"
System.out.println(b.x); // this prints 5, because "b" points to the same object as "a"
}
|
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.
|
#Julia
|
Julia
|
x = [1, 2, 3, 7]
parr = pointer(x)
xx = unsafe_load(parr, 4)
println(xx) # Prints 7
|
http://rosettacode.org/wiki/Plot_coordinate_pairs
|
Plot coordinate pairs
|
Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#EasyLang
|
EasyLang
|
x[] = [ 0 1 2 3 4 5 6 7 8 9 ]
y[] = [ 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0 ]
#
clear
linewidth 0.5
move 10 3
line 10 95
line 95 95
textsize 3
n = len x[]
m = 0
for i range n
m = higher y[i] m
.
linewidth 0.1
sty = m div 9
for i range 10
move 2 94 - i * 10
text i * sty
move 10 95 - i * 10
line 95 95 - i * 10
.
stx = x[n - 1] div 9
for i range 10
move i * 9 + 10 96.5
text i * stx
move i * 9 + 10 95
line i * 9 + 10 3
.
color 900
linewidth 0.5
for i range n
x = x[i] * 9 / stx + 10
y = 100 - (y[i] / sty * 10 + 5)
if i = 0
move x y
else
line x y
.
.
|
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
|
#Common_Lisp
|
Common Lisp
|
(defclass point ()
((x :initarg :x :initform 0 :accessor x)
(y :initarg :y :initform 0 :accessor y)))
(defclass circle (point)
((radius :initarg :radius :initform 0 :accessor radius)))
(defgeneric shallow-copy (object))
(defmethod shallow-copy ((p point))
(make-instance 'point :x (x p) :y (y p)))
(defmethod shallow-copy ((c circle))
(make-instance 'circle :x (x c) :y (y c) :radius (radius c)))
(defgeneric print-shape (shape))
(defmethod print-shape ((p point))
(print 'point))
(defmethod print-shape ((c circle))
(print 'circle))
(let ((p (make-instance 'point :x 10))
(c (make-instance 'circle :radius 5)))
(print-shape p)
(print-shape c))
|
http://rosettacode.org/wiki/Poker_hand_analyser
|
Poker hand analyser
|
Task
Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
Example
2d (two of diamonds).
Faces are: a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, k
Suits are: h (hearts), d (diamonds), c (clubs), and s (spades), or
alternatively, the unicode card-suit characters: ♥ ♦ ♣ ♠
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
Examples
2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind
2♥ 5♥ 7♦ 8♣ 9♠: high-card
a♥ 2♦ 3♣ 4♣ 5♦: straight
2♥ 3♥ 2♦ 3♣ 3♦: full-house
2♥ 7♥ 2♦ 3♣ 3♦: two-pair
2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind
10♥ j♥ q♥ k♥ a♥: straight-flush
4♥ 4♠ k♠ 5♦ 10♠: one-pair
q♣ 10♣ 7♣ 6♣ q♣: invalid
The programs output for the above examples should be displayed here on this page.
Extra credit
use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
allow two jokers
use the symbol joker
duplicates would be allowed (for jokers only)
five-of-a-kind would then be the highest hand
More extra credit examples
joker 2♦ 2♠ k♠ q♦: three-of-a-kind
joker 5♥ 7♦ 8♠ 9♦: straight
joker 2♦ 3♠ 4♠ 5♠: straight
joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind
joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind
joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind
joker j♥ q♥ k♥ A♥: straight-flush
joker 4♣ k♣ 5♦ 10♠: one-pair
joker k♣ 7♣ 6♣ 4♣: flush
joker 2♦ joker 4♠ 5♠: straight
joker Q♦ joker A♠ 10♠: straight
joker Q♦ joker A♦ 10♦: straight-flush
joker 2♦ 2♠ joker q♦: four-of-a-kind
Related tasks
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Go Fish
|
#Factor
|
Factor
|
USING: formatting kernel poker sequences ;
{
"2H 2D 2C KC QD"
"2H 5H 7D 8C 9S"
"AH 2D 3C 4C 5D"
"2H 3H 2D 3C 3D"
"2H 7H 2D 3C 3D"
"2H 7H 7D 7C 7S"
"TH JH QH KH AH"
"4H 4S KS 5D TS"
"QC TC 7C 6C 4C"
} [ dup string>hand-name "%s: %s\n" printf ] each
|
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.
|
#BQN
|
BQN
|
PopCount ← {(2|𝕩)+𝕊⍟×⌊𝕩÷2}
Odious ← 2|PopCount
Evil ← ¬Odious
_List ← {𝕩↑𝔽¨⊸/↕2×𝕩}
>⟨PopCount¨ 3⋆↕30,
Evil _List 30,
Odious _List 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
|
#Factor
|
Factor
|
USE: math.polynomials
{ -42 0 -12 1 } { -3 1 } p/mod ptrim [ . ] bi@
|
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.
|
#JavaScript
|
JavaScript
|
function clone(obj){
if (obj == null || typeof(obj) != 'object')
return obj;
var temp = {};
for (var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
|
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.
|
#Julia
|
Julia
|
abstract type Jewel end
mutable struct RoseQuartz <: Jewel
carats::Float64
quality::String
end
mutable struct Sapphire <: Jewel
color::String
carats::Float64
quality::String
end
color(j::RoseQuartz) = "rosepink"
color(j::Jewel) = "Use the loupe."
color(j::Sapphire) = j.color
function testtypecopy()
a = Sapphire("blue", 5.0, "good")
b = RoseQuartz(3.5, "excellent")
j::Jewel = deepcopy(b)
println("a is a Jewel? ", a isa Jewel)
println("b is a Jewel? ", a isa Jewel)
println("j is a Jewel? ", a isa Jewel)
println("a is a Sapphire? ", a isa Sapphire)
println("a is a RoseQuartz? ", a isa RoseQuartz)
println("b is a Sapphire? ", b isa Sapphire)
println("b is a RoseQuartz? ", b isa RoseQuartz)
println("j is a Sapphire? ", j isa Sapphire)
println("j is a RoseQuartz? ", j isa RoseQuartz)
println("The color of j is ", color(j), ".")
println("j is the same as b? ", j == b)
end
testtypecopy()
|
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
|
#SPL
|
SPL
|
width,height = #.scrsize()
#.angle(#.degrees)
#.scroff()
incr = 0
>
incr = (incr+0.05)%360
x = width/2
y = height/2
length = 5
angle = incr
#.scrclear()
#.drawline(x,y,x,y)
> i, 1..150
x += length*#.cos(angle)
y += length*#.sin(angle)
#.drawcolor(#.hsv2rgb(angle,1,1):3)
#.drawline(x,y)
length += 3
angle = (angle+incr)%360
<
#.scr()
<
|
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
|
#SVG
|
SVG
|
<svg viewBox="0 0 100 100" stroke="#000" stroke-width="0.3">
<g>
<line x1="50" y1="50" x2="54" y2="50"></line>
<animateTransform attributeName="transform" type="rotate" from="-120 50 50" to="240 50 50" dur="2400s" repeatCount="indefinite"></animateTransform>
<g>
<line x1="54" y1="50" x2="58.16" y2="50"></line>
<animateTransform attributeName="transform" type="rotate" from="-120 54 50" to="240 54 50" dur="2400s" repeatCount="indefinite"></animateTransform>
<g>
<line x1="58.16" y1="50" x2="62.48639" y2="50"></line>
<animateTransform attributeName="transform" type="rotate" dur="2400s" repeatCount="indefinite" to="240 58.16 50" from="-120 58.16 50"></animateTransform>
<!-- ad nauseam -->
</g>
</g>
</g>
</svg>
|
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.
|
#Go
|
Go
|
package main
import (
"fmt"
"log"
"gonum.org/v1/gonum/mat"
)
func main() {
var (
x = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
y = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
degree = 2
a = Vandermonde(x, degree+1)
b = mat.NewDense(len(y), 1, y)
c = mat.NewDense(degree+1, 1, nil)
)
var qr mat.QR
qr.Factorize(a)
const trans = false
err := qr.SolveTo(c, trans, b)
if err != nil {
log.Fatalf("could not solve QR: %+v", err)
}
fmt.Printf("%.3f\n", mat.Formatted(c))
}
func Vandermonde(a []float64, d int) *mat.Dense {
x := mat.NewDense(len(a), d, nil)
for i := range a {
for j, p := 0, 1.0; j < d; j, p = j+1, p*a[i] {
x.Set(i, j, p)
}
}
return 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.
|
#ColdFusion
|
ColdFusion
|
public array function powerset(required array data)
{
var ps = [""];
var d = arguments.data;
var lenData = arrayLen(d);
var lenPS = 0;
for (var i=1; i LTE lenData; i++)
{
lenPS = arrayLen(ps);
for (var j = 1; j LTE lenPS; j++)
{
arrayAppend(ps, listAppend(ps[j], d[i]));
}
}
return ps;
}
var res = 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
|
#BCPL
|
BCPL
|
get "libhdr"
let sqrt(s) =
s <= 1 -> 1,
valof
$( let x0 = s >> 1
let x1 = (x0 + s/x0) >> 1
while x1 < x0
$( x0 := x1
x1 := (x0 + s/x0) >> 1
$)
resultis x0
$)
let isprime(n) =
n < 2 -> false,
(n & 1) = 0 -> n = 2,
valof
$( for i = 3 to sqrt(n) by 2
if n rem i = 0 resultis false
resultis true
$)
let start() be
$( for i=1 to 100
if isprime(i) then writef("%N ",i)
wrch('*N')
$)
|
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
|
#F.23
|
F#
|
let cin = [ 0.06m .. 0.05m ..1.01m ]
let cout = [0.1m; 0.18m] @ [0.26m .. 0.06m .. 0.44m] @ [0.50m .. 0.04m .. 0.98m] @ [1.m]
let priceadjuster p =
let rec bisect lo hi =
if lo < hi then
let mid = (lo+hi)/2.
let left = p < cin.[int mid]
bisect (if left then lo else mid+1.) (if left then mid else hi)
else lo
if p < 0.m || 1.m < p then p
else cout.[int (bisect 0. (float cin.Length))]
[ 0.m .. 0.01m .. 1.m ]
|> Seq.ofList
|> Seq.iter (fun p -> printfn "%.2f -> %.2f" p (priceadjuster p))
|
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
|
#J
|
J
|
factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
properDivisors=: factors -. ]
|
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)
|
#Phix
|
Phix
|
with javascript_semantics
constant lim = 1000000,
{names, probs} = columnize({{"aleph", 1/5},
{"beth", 1/6},
{"gimel", 1/7},
{"daleth", 1/8},
{"he", 1/9},
{"waw", 1/10},
{"zayin", 1/11},
{"heth", 1759/27720}})
sequence results = repeat(0,length(names))
for j=1 to lim do
atom r = rnd()
for i=1 to length(probs) do
r -= probs[i]
if r<=0 then
results[i]+=1
exit
end if
end for
end for
printf(1," Name Actual Expected\n")
for i=1 to length(probs) do
printf(1,"%6s %8.6f %8.6f\n",{names[i],results[i]/lim,probs[i]})
end for
|
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.
|
#Lua
|
Lua
|
PriorityQueue = {
__index = {
put = function(self, p, v)
local q = self[p]
if not q then
q = {first = 1, last = 0}
self[p] = q
end
q.last = q.last + 1
q[q.last] = v
end,
pop = function(self)
for p, q in pairs(self) do
if q.first <= q.last then
local v = q[q.first]
q[q.first] = nil
q.first = q.first + 1
return p, v
else
self[p] = nil
end
end
end
},
__call = function(cls)
return setmetatable({}, cls)
end
}
setmetatable(PriorityQueue, PriorityQueue)
-- Usage:
pq = PriorityQueue()
tasks = {
{3, 'Clear drains'},
{4, 'Feed cat'},
{5, 'Make tea'},
{1, 'Solve RC tasks'},
{2, 'Tax return'}
}
for _, task in ipairs(tasks) do
print(string.format("Putting: %d - %s", unpack(task)))
pq:put(unpack(task))
end
for prio, task in pq.pop, pq do
print(string.format("Popped: %d - %s", prio, task))
end
|
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
|
#Sidef
|
Sidef
|
func triples(limit) {
var primitive = 0
var civilized = 0
func oyako(a, b, c) {
(var perim = a+b+c) > limit || (
primitive++
civilized += int(limit / perim)
oyako( a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c)
oyako( a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c)
oyako(-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c)
)
}
oyako(3,4,5)
"#{limit} => (#{primitive} #{civilized})"
}
for n (1..Inf) {
say triples(10**n)
}
|
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.
|
#Slate
|
Slate
|
problem ifTrue: [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.
|
#SNOBOL4
|
SNOBOL4
|
&code = condition errlevel :s(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
|
#Swift
|
Swift
|
import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
|
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
|
#Tiny_BASIC
|
Tiny BASIC
|
PRINT "Number to test"
INPUT N
IF N < 0 THEN LET N = -N
IF N = 2 THEN GOTO 30
IF N < 2 THEN GOTO 40
LET F = 1
LET J = 1
10 LET J = J + 1
REM exploits the fact that (F mod N)*J = (F*J mod N)
REM to do the factorial without overflowing
LET F = F * J
GOSUB 20
IF J < N - 1 THEN GOTO 10
IF F = N - 1 THEN PRINT "It is prime"
IF F <> N - 1 THEN PRINT "It is not prime"
END
20 REM modulo by repeated subtraction
IF F < N THEN RETURN
LET F = F - N
GOTO 20
30 REM special case N=2
PRINT "It is prime"
END
40 REM zero and one are nonprimes by definition
PRINT "It is not prime"
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
|
#Wren
|
Wren
|
import "/math" for Int
import "/fmt" for Fmt
var wilson = Fn.new { |p|
if (p < 2) return false
return (Int.factorial(p-1) + 1) % p == 0
}
for (p in 1..19) {
Fmt.print("$2d -> $s", p, wilson.call(p) ? "prime" : "not prime")
}
|
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 %
|
#Wren
|
Wren
|
import "/fmt" for Fmt
import "/math" for Int
import "/sort" for Sort
var reportTransitions = Fn.new { |transMap, num|
var keys = transMap.keys.toList
Sort.quick(keys)
System.print("First %(Fmt.dc(0, num)) primes. Transitions prime \% 10 -> next-prime \% 10.")
for (key in keys) {
var count = transMap[key]
var freq = count / num * 100
System.write("%((key/10).floor) -> %(key%10) count: %(Fmt.dc(8, count))")
System.print(" frequency: %(Fmt.f(4, freq, 2))\%")
}
System.print()
}
// sieve up to the 10 millionth prime
var start = System.clock
var sieved = Int.primeSieve(179424673)
var transMap = {}
var i = 2 // last digit of first prime (2)
var n = 1 // index of next prime (3) in sieved
for (num in [1e4, 1e5, 1e6, 1e7]) {
while(n < num) {
var p = sieved[n]
// count transition of i -> j
var j = p % 10
var k = i*10 + j
var t = transMap[k]
if (!t) {
transMap[k] = 1
} else {
transMap[k] = t + 1
}
i = j
n = n + 1
}
reportTransitions.call(transMap, n)
}
System.print("Took %(System.clock - start) seconds.")
|
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
|
#Eiffel
|
Eiffel
|
class
PRIME_DECOMPOSITION
feature
factor (p: INTEGER): ARRAY [INTEGER]
-- Prime decomposition of 'p'.
require
p_positive: p > 0
local
div, i, next, rest: INTEGER
do
create Result.make_empty
if p = 1 then
Result.force (1, 1)
end
div := 2
next := 3
rest := p
from
i := 1
until
rest = 1
loop
from
until
rest \\ div /= 0
loop
Result.force (div, i)
rest := (rest / div).floor
i := i + 1
end
div := next
next := next + 2
end
ensure
is_divisor: across Result as r all p \\ r.item = 0 end
is_prime: across Result as r all prime (r.item) end
end
|
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.
|
#Kotlin
|
Kotlin
|
// Kotlin Native v0.3
import kotlinx.cinterop.*
fun main(args: Array<String>) {
// allocate space for an 'int' on the native heap and wrap a pointer to it in an IntVar object
val intVar: IntVar = nativeHeap.alloc<IntVar>()
intVar.value = 3 // set its value
println(intVar.value) // print it
println(intVar.ptr) // corresponding CPointer object
println(intVar.rawPtr) // the actual address wrapped by the CPointer
// change the value and print that
intVar.value = 333
println()
println(intVar.value)
println(intVar.ptr) // same as before, of course
// implicitly convert to an opaque pointer which is the supertype of all pointer types
val op: COpaquePointer = intVar.ptr
// cast opaque pointer to a pointer to ByteVar
println()
var bytePtr: CPointer<ByteVar> = op.reinterpret<ByteVar>()
println(bytePtr.pointed.value) // value of first byte i.e. 333 - 256 = 77 on Linux
bytePtr = (bytePtr + 1)!! // increment pointer
println(bytePtr.pointed.value) // value of second byte i.e. 1 on Linux
println(bytePtr) // one byte more than before
bytePtr = (bytePtr + (-1))!! // decrement pointer
println(bytePtr) // back to original value
nativeHeap.free(intVar) // free native memory
// allocate space for an array of 3 'int's on the native heap
println()
var intArray: CPointer<IntVar> = nativeHeap.allocArray<IntVar>(3)
for (i in 0..2) intArray[i] = i // set them
println(intArray[2]) // print the last element
nativeHeap.free(intArray) // free native memory
}
|
http://rosettacode.org/wiki/Plot_coordinate_pairs
|
Plot coordinate pairs
|
Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
|
#EchoLisp
|
EchoLisp
|
(lib 'plot)
(define ys #(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0) )
(define (f n) [ys n])
(plot-sequence f 9)
→ (("x:auto" 0 9) ("y:auto" 2 198))
(plot-grid 1 20)
(plot-text " Rosetta plot coordinate pairs" 0 10 "white")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.