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/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
| #Java | Java | class Point {
protected int x, y;
public Point() { this(0); }
public Point(int x) { this(x, 0); }
public Point(int x, int y) { this.x = x; this.y = y; }
public Point(Point p) { this(p.x, p.y); }
public int getX() { return this.x; }
public int getY() { return this.y; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public void print() { System.out.println("Point x: " + this.x + " y: " + this.y); }
}
class Circle extends Point {
private int r;
public Circle(Point p) { this(p, 0); }
public Circle(Point p, int r) { super(p); this.r = r; }
public Circle() { this(0); }
public Circle(int x) { this(x, 0); }
public Circle(int x, int y) { this(x, y, 0); }
public Circle(int x, int y, int r) { super(x, y); this.r = r; }
public Circle(Circle c) { this(c.x, c.y, c.r); }
public int getR() { return this.r; }
public void setR(int r) { this.r = r; }
public void print() { System.out.println("Circle x: " + this.x + " y: " + this.y + " r: " + this.r); }
}
public class test {
public static void main(String args[]) {
Point p = new Point();
Point c = new Circle();
p.print();
c.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
| #Python | Python | from collections import namedtuple
class Card(namedtuple('Card', 'face, suit')):
def __repr__(self):
return ''.join(self)
suit = '♥ ♦ ♣ ♠'.split()
# ordered strings of faces
faces = '2 3 4 5 6 7 8 9 10 j q k a'
lowaces = 'a 2 3 4 5 6 7 8 9 10 j q k'
# faces as lists
face = faces.split()
lowace = lowaces.split()
def straightflush(hand):
f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand)
else (face, faces) )
ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit))
first, rest = ordered[0], ordered[1:]
if ( all(card.suit == first.suit for card in rest) and
' '.join(card.face for card in ordered) in fs ):
return 'straight-flush', ordered[-1].face
return False
def fourofakind(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
if len(allftypes) != 2:
return False
for f in allftypes:
if allfaces.count(f) == 4:
allftypes.remove(f)
return 'four-of-a-kind', [f, allftypes.pop()]
else:
return False
def fullhouse(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
if len(allftypes) != 2:
return False
for f in allftypes:
if allfaces.count(f) == 3:
allftypes.remove(f)
return 'full-house', [f, allftypes.pop()]
else:
return False
def flush(hand):
allstypes = {s for f, s in hand}
if len(allstypes) == 1:
allfaces = [f for f,s in hand]
return 'flush', sorted(allfaces,
key=lambda f: face.index(f),
reverse=True)
return False
def straight(hand):
f,fs = ( (lowace, lowaces) if any(card.face == '2' for card in hand)
else (face, faces) )
ordered = sorted(hand, key=lambda card: (f.index(card.face), card.suit))
first, rest = ordered[0], ordered[1:]
if ' '.join(card.face for card in ordered) in fs:
return 'straight', ordered[-1].face
return False
def threeofakind(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
if len(allftypes) <= 2:
return False
for f in allftypes:
if allfaces.count(f) == 3:
allftypes.remove(f)
return ('three-of-a-kind', [f] +
sorted(allftypes,
key=lambda f: face.index(f),
reverse=True))
else:
return False
def twopair(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
pairs = [f for f in allftypes if allfaces.count(f) == 2]
if len(pairs) != 2:
return False
p0, p1 = pairs
other = [(allftypes - set(pairs)).pop()]
return 'two-pair', pairs + other if face.index(p0) > face.index(p1) else pairs[::-1] + other
def onepair(hand):
allfaces = [f for f,s in hand]
allftypes = set(allfaces)
pairs = [f for f in allftypes if allfaces.count(f) == 2]
if len(pairs) != 1:
return False
allftypes.remove(pairs[0])
return 'one-pair', pairs + sorted(allftypes,
key=lambda f: face.index(f),
reverse=True)
def highcard(hand):
allfaces = [f for f,s in hand]
return 'high-card', sorted(allfaces,
key=lambda f: face.index(f),
reverse=True)
handrankorder = (straightflush, fourofakind, fullhouse,
flush, straight, threeofakind,
twopair, onepair, highcard)
def rank(cards):
hand = handy(cards)
for ranker in handrankorder:
rank = ranker(hand)
if rank:
break
assert rank, "Invalid: Failed to rank cards: %r" % cards
return rank
def handy(cards='2♥ 2♦ 2♣ k♣ q♦'):
hand = []
for card in cards.split():
f, s = card[:-1], card[-1]
assert f in face, "Invalid: Don't understand card face %r" % f
assert s in suit, "Invalid: Don't understand card suit %r" % s
hand.append(Card(f, s))
assert len(hand) == 5, "Invalid: Must be 5 cards in a hand, not %i" % len(hand)
assert len(set(hand)) == 5, "Invalid: All cards in the hand must be unique %r" % cards
return hand
if __name__ == '__main__':
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♥ 7♥ 7♦ 7♣ 7♠",
"10♥ j♥ q♥ k♥ a♥"] + [
"4♥ 4♠ k♠ 5♦ 10♠",
"q♣ 10♣ 7♣ 6♣ 4♣",
]
print("%-18s %-15s %s" % ("HAND", "CATEGORY", "TIE-BREAKER"))
for cards in hands:
r = rank(cards)
print("%-18r %-15s %r" % (cards, r[0], r[1])) |
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.
| #Fermat | Fermat | Func Popcount(n) = if n = 0 then 0 else if 2*(n\2)=n then Popcount(n\2) else Popcount((n-1)\2)+1 fi fi.
Func Odiousness(n) = p:=Popcount(n);if 2*(p\2) = p then 0 else 1 fi.
for n=0 to 29 do !Popcount(3^n);!' ' od
e:=0
n:=0
while e<30 do if Odiousness(n)=0 then !n;!' ';e:=e+1 fi; n:=n+1 od
e:=0
n:=0
while e<30 do if Odiousness(n)=1 then !n;!' ';e:=e+1 fi; n:=n+1 od |
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
| #Phix | Phix | -- demo\rosetta\Polynomial_long_division.exw
with javascript_semantics
function degree(sequence p)
for i=length(p) to 1 by -1 do
if p[i]!=0 then return i end if
end for
return -1
end function
function poly_div(sequence n, d)
d = deep_copy(d)
while length(d)<length(n) do d &=0 end while
integer dn = degree(n),
dd = degree(d)
if dd<0 then throw("divide by zero") end if
sequence quo = repeat(0,dn),
rem = deep_copy(n)
while dn>=dd do
integer k = dn-dd, qk = rem[dn]/d[dd]
sequence d2 = d[1..length(d)-k]
quo[k+1] = qk
for i=1 to length(d2) do
integer mi = -i
rem[mi] -= d2[mi]*qk
end for
dn = degree(rem)
end while
return {quo,rem}
end function
function poly(sequence si)
-- display helper
string r = ""
for t=length(si) to 1 by -1 do
integer sit = si[t]
if sit!=0 then
if sit=1 and t>1 then
r &= iff(r=""? "":" + ")
elsif sit=-1 and t>1 then
r &= iff(r=""?"-":" - ")
else
if r!="" then
r &= iff(sit<0?" - ":" + ")
sit = abs(sit)
end if
r &= sprintf("%d",sit)
end if
r &= iff(t>1?"x"&iff(t>2?sprintf("^%d",t-1):""):"")
end if
end for
if r="" then r="0" end if
return r
end function
constant tests = {{{-42,0,-12,1},{-3,1}},
{{-3,1},{-42,0,-12,1}},
{{-42,0,-12,1},{-3,1,1}},
{{2,3,1},{1,1}},
{{3,5,6,-4,1},{1,2,1}},
{{3,0,7,0,0,0,0,0,3,0,0,1},{1,0,0,5,0,0,0,1}},
{{-56,87,-94,-55,22,-7},{2,0,1}},
}
constant fmt = "%40s / %-16s = %25s rem %s\n"
for i=1 to length(tests) do
sequence {num,den} = tests[i],
{quo,rem} = poly_div(num,den)
printf(1,fmt,apply({num,den,quo,rem},poly))
end for
|
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.
| #OCaml | OCaml | open Base
open Stdio
let mean fa =
let open Float in
(Array.reduce_exn fa ~f:(+)) / (of_int (Array.length fa))
let regression xs ys =
let open Float in
let xm = mean xs in
let ym = mean ys in
let x2m = Array.map xs ~f:(fun x -> x * x) |> mean in
let x3m = Array.map xs ~f:(fun x -> x * x * x) |> mean in
let x4m = Array.map xs ~f:(fun x -> let x2 = x * x in x2 * x2) |> mean in
let xzipy = Array.zip_exn xs ys in
let xym = Array.map xzipy ~f:(fun (x, y) -> x * y) |> mean in
let x2ym = Array.map xzipy ~f:(fun (x, y) -> x * x * y) |> mean in
let sxx = x2m - xm * xm in
let sxy = xym - xm * ym in
let sxx2 = x3m - xm * x2m in
let sx2x2 = x4m - x2m * x2m in
let sx2y = x2ym - x2m * ym in
let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) in
let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) in
let a = ym - b * xm - c * x2m in
let abc xx = a + b * xx + c * xx * xx in
printf "y = %.1f + %.1fx + %.1fx^2\n\n" a b c;
printf " Input Approximation\n";
printf " x y y1\n";
Array.iter xzipy ~f:(fun (xi, yi) ->
printf "%2g %3g %5.1f\n" xi yi (abc xi)
)
let () =
let x = Array.init 11 ~f:Float.of_int in
let y = [| 1.; 6.; 17.; 34.; 57.; 86.; 121.; 162.; 209.; 262.; 321. |] in
regression x y |
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.
| #Go | Go | package main
import (
"fmt"
"strconv"
"strings"
)
// types needed to implement general purpose sets are element and set
// element is an interface, allowing different kinds of elements to be
// implemented and stored in sets.
type elem interface {
// an element must be distinguishable from other elements to satisfy
// the mathematical definition of a set. a.eq(b) must give the same
// result as b.eq(a).
Eq(elem) bool
// String result is used only for printable output. Given a, b where
// a.eq(b), it is not required that a.String() == b.String().
fmt.Stringer
}
// integer type satisfying element interface
type Int int
func (i Int) Eq(e elem) bool {
j, ok := e.(Int)
return ok && i == j
}
func (i Int) String() string {
return strconv.Itoa(int(i))
}
// a set is a slice of elem's. methods are added to implement
// the element interface, to allow nesting.
type set []elem
// uniqueness of elements can be ensured by using add method
func (s *set) add(e elem) {
if !s.has(e) {
*s = append(*s, e)
}
}
func (s *set) has(e elem) bool {
for _, ex := range *s {
if e.Eq(ex) {
return true
}
}
return false
}
func (s set) ok() bool {
for i, e0 := range s {
for _, e1 := range s[i+1:] {
if e0.Eq(e1) {
return false
}
}
}
return true
}
// elem.Eq
func (s set) Eq(e elem) bool {
t, ok := e.(set)
if !ok {
return false
}
if len(s) != len(t) {
return false
}
for _, se := range s {
if !t.has(se) {
return false
}
}
return true
}
// elem.String
func (s set) String() string {
if len(s) == 0 {
return "∅"
}
var buf strings.Builder
buf.WriteRune('{')
for i, e := range s {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(e.String())
}
buf.WriteRune('}')
return buf.String()
}
// method required for task
func (s set) powerSet() set {
r := set{set{}}
for _, es := range s {
var u set
for _, er := range r {
er := er.(set)
u = append(u, append(er[:len(er):len(er)], es))
}
r = append(r, u...)
}
return r
}
func main() {
var s set
for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} {
s.add(i)
}
fmt.Println(" s:", s, "length:", len(s))
ps := s.powerSet()
fmt.Println(" 𝑷(s):", ps, "length:", len(ps))
fmt.Println("\n(extra credit)")
var empty set
fmt.Println(" empty:", empty, "len:", len(empty))
ps = empty.powerSet()
fmt.Println(" 𝑷(∅):", ps, "len:", len(ps))
ps = ps.powerSet()
fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps))
fmt.Println("\n(regression test for earlier bug)")
s = set{Int(1), Int(2), Int(3), Int(4), Int(5)}
fmt.Println(" s:", s, "length:", len(s), "ok:", s.ok())
ps = s.powerSet()
fmt.Println(" 𝑷(s):", "length:", len(ps), "ok:", ps.ok())
for _, e := range ps {
if !e.(set).ok() {
panic("invalid set in ps")
}
}
} |
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
| #Crystal | Crystal | Mathematicaly basis of Prime Generators
https://www.academia.edu/19786419/PRIMES-UTILS_HANDBOOK
https://www.academia.edu/42734410/Improved_Primality_Testing_and_Factorization_in_Ruby_revised
|
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
| #K | K |
le:- 0.96 0.91 0.86 0.81 0.76 0.71 0.66 0.61 0.56 0.51 0.46 0.41 0.36 0.31 0.26 0.21 0.16 0.11 0.06 0.0
out: 1.00 0.98 0.94 0.90 0.86 0.82 0.78 0.74 0.70 0.66 0.62 0.58 0.54 0.50 0.44 0.38 0.32 0.26 0.18 0.1
pf:{out@_bin[le;-x]}'
|
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
| #Kotlin | Kotlin | // version 1.0.6
fun rescale(price: Double): Double =
when {
price < 0.06 -> 0.10
price < 0.11 -> 0.18
price < 0.16 -> 0.26
price < 0.21 -> 0.32
price < 0.26 -> 0.38
price < 0.31 -> 0.44
price < 0.36 -> 0.50
price < 0.41 -> 0.54
price < 0.46 -> 0.58
price < 0.51 -> 0.62
price < 0.56 -> 0.66
price < 0.61 -> 0.70
price < 0.66 -> 0.74
price < 0.71 -> 0.78
price < 0.76 -> 0.82
price < 0.81 -> 0.86
price < 0.86 -> 0.90
price < 0.91 -> 0.94
price < 0.96 -> 0.98
else -> 1.00
}
fun main(args: Array<String>) {
var d: Double
for (i in 1..100) {
d = i / 100.0
print(String.format("%4.2f -> %4.2f ", d, rescale(d)))
if (i % 5 == 0) println()
}
} |
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
| #Pascal | Pascal | {$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
sysutils;
const
MAXPROPERDIVS = 1920;
type
tRes = array[0..MAXPROPERDIVS] of LongWord;
tPot = record
potPrim,
potMax :LongWord;
end;
tprimeFac = record
pfPrims : array[1..10] of tPot;
pfCnt,
pfNum : LongWord;
end;
tSmallPrimes = array[0..6541] of longWord;
var
SmallPrimes: tSmallPrimes;
procedure InitSmallPrimes;
var
pr,testPr,j,maxprimidx: Longword;
isPrime : boolean;
Begin
maxprimidx := 0;
SmallPrimes[0] := 2;
pr := 3;
repeat
isprime := true;
j := 0;
repeat
testPr := SmallPrimes[j];
IF testPr*testPr > pr then
break;
If pr mod testPr = 0 then
Begin
isprime := false;
break;
end;
inc(j);
until false;
if isprime then
Begin
inc(maxprimidx);
SmallPrimes[maxprimidx]:= pr;
end;
inc(pr,2);
until pr > 1 shl 16 -1;
end;
procedure PrimeFacOut(primeDecomp:tprimeFac);
var
i : LongWord;
begin
with primeDecomp do
Begin
write(pfNum,' = ');
For i := 1 to pfCnt-1 do
with pfPrims[i] do
If potMax = 1 then
write(potPrim,'*')
else
write(potPrim,'^',potMax,'*');
with pfPrims[pfCnt] do
If potMax = 1 then
write(potPrim)
else
write(potPrim,'^',potMax);
end;
end;
procedure PrimeDecomposition(n:LongWord;var res:tprimeFac);
var
i,pr,cnt,quot{to minimize divisions} : LongWord;
Begin
res.pfNum := n;
res.pfCnt:= 0;
i := 0;
cnt := 0;
repeat
pr := SmallPrimes[i];
IF pr*pr>n then
Break;
quot := n div pr;
IF pr*quot = n then
with res do
Begin
inc(pfCnt);
with pfPrims[pfCnt] do
Begin
potPrim := pr;
potMax := 0;
repeat
n := quot;
quot := quot div pr;
inc(potMax);
until pr*quot <> n;
end;
end;
inc(i);
until false;
//a big prime left over?
IF n <> 1 then
with res do
Begin
inc(pfCnt);
with pfPrims[pfCnt] do
Begin
potPrim := n;
potMax := 1;
end;
end;
end;
function CntProperDivs(const primeDecomp:tprimeFac):LongWord;
//count of proper divisors
var
i: LongWord;
begin
result := 1;
with primeDecomp do
For i := 1 to pfCnt do
result := result*(pfPrims[i].potMax+1);
//remove
dec(result);
end;
function findProperdivs(n:LongWord;var res:TRes):LongWord;
//simple trial division to get a sorted list of all proper divisors
var
i,j: LongWord;
Begin
result := 0;
i := 1;
j := n;
while j>i do
begin
j := n DIV i;
IF i*j = n then
Begin
//smaller factor part at the beginning upwards
res[result]:= i;
IF i <> j then
//bigger factor at the end downwards
res[MAXPROPERDIVS-result]:= j
else
//n is square number
res[MAXPROPERDIVS-result]:= 0;
inc(result);
end;
inc(i);
end;
If result>0 then
Begin
//move close together
i := result;
j := MAXPROPERDIVS-result+1;
result := 2*result-1;
repeat
res[i] := res[j];
inc(j);
inc(i);
until i > result;
if res[result-1] = 0 then
dec(result);
end;
end;
procedure AllFacsOut(n: Longword);
var
res:TRes;
i,k,j:LongInt;
Begin
j := findProperdivs(n,res);
write(n:5,' : ');
For k := 0 to j-2 do write(res[k],',');
IF j>=1 then
write(res[j-1]);
writeln;
end;
var
primeDecomp: tprimeFac;
rs : tRes;
i,j,max,maxcnt: LongWord;
BEGIN
InitSmallPrimes;
For i := 1 to 10 do
AllFacsOut(i);
writeln;
max := 0;
maxCnt := 0;
For i := 1 to 20*1000 do
Begin
PrimeDecomposition(i,primeDecomp);
j := CntProperDivs(primeDecomp);
IF j> maxCnt then
Begin
maxcnt := j;
max := i;
end;
end;
PrimeDecomposition(max,primeDecomp);
j := CntProperDivs(primeDecomp);
PrimeFacOut(primeDecomp);writeln(' ',j:10,' factors'); writeln;
//https://en.wikipedia.org/wiki/Highly_composite_number <= HCN
//http://wwwhomes.uni-bielefeld.de/achim/highly.txt the first 1200 HCN
max := 3491888400;
PrimeDecomposition(max,primeDecomp);
j := CntProperDivs(primeDecomp);
PrimeFacOut(primeDecomp);writeln(' ',j:10,' factors'); writeln;
END. |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Ursala | Ursala | #import std
#import nat
#import flo
outcomes = <'aleph ','beth ','gimel ','daleth','he ','waw ','zayin ','heth '>
probabilities = ^lrNCT(~&,minus/1.+ plus:-0) div/*1. float* skip/5 iota12
simulation =
^(~&rn,div+ float~~rmPlX)^*D/~& iota; ^A(~&h,length)*K2+ * stochasm@p/probabilities !* outcomes
format =
:/' frequency probability'+ * ^lrlrTPT/~&n (printf/'%12.8f')^~/~&m outcomes-$probabilities@n
#show+
results = format simulation 1000000 |
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.
| #PicoLisp | PicoLisp | # Insert item into priority queue
(de insertPQ (Queue Prio Item)
(idx Queue (cons Prio Item) T) )
# Remove and return top item from priority queue
(de removePQ (Queue)
(cdar (idx Queue (peekPQ Queue) NIL)) )
# Find top element in priority queue
(de peekPQ (Queue)
(let V (val Queue)
(while (cadr V)
(setq V @) )
(car V) ) )
# Merge second queue into first
(de mergePQ (Queue1 Queue2)
(balance Queue1 (sort (conc (idx Queue1) (idx Queue2)))) ) |
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
| #Groovy | Groovy | def factorize = { long target ->
if (target == 1) return [1L]
if (target < 4) return [1L, target]
def targetSqrt = Math.sqrt(target)
def lowfactors = (2L..targetSqrt).findAll { (target % it) == 0 }
if (lowfactors == []) return [1L, target]
def nhalf = lowfactors.size() - ((lowfactors[-1]**2 == target) ? 1 : 0)
[1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
}
def decomposePrimes = { target ->
def factors = factorize(target) - [1]
def primeFactors = []
factors.eachWithIndex { f, i ->
if (i==0 || factors[0..<i].every {f % it != 0}) {
primeFactors << f
def pfPower = f*f
while (target % pfPower == 0) {
primeFactors << f
pfPower *= f
}
}
}
primeFactors
} |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Pairs {
\\ written in version 9.5 rev. 13
\\ use Gdi+ antialiasing (not work with Wine in Linux, but we get no error)
smooth on
Const center=2, right=3, left=1, blue=1, angle=0, dotline=3
Const size9pt=9, size11pt=11
Cls ,0 ' use current background color, set split screen from line 0
Cursor 0,3
Report center, "Coordinate pairs"
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)
dx=scale.x/2/len(x)
dy=dx 'ratio 1:1
graH=dy*len(x)
Basex=scale.x/4
Basey=(scale.y+graH)/2
Move Basex, Basey
\\ draw use relative coordinates
Draw 0,-graH
\\ Step just move graphic cursor
Step 0, graH
Draw scale.x/2
Step -scale.x/2
\\ scX is 1, not used
max=Y#max()
\\ Auto scale for Y, using 0 for start of axis Y
scY=-graH/((max+5^log(max) ) div 100)/100
\\ make vertical axis using dots with numbers center per dx
j=1
For i=basex+dx to basex+dx*x#max() Step dx
Move i, basey
Step 0, twipsy*10
Legend format$("{0}",array(x,j)), "courier", size9pt, angle, center
Width 1, dotline { draw 0, -graH-twipsy*10,7}
j++
Next i
\\ the same for horizontal axis
HalfTextHeight=Size.y("1","courier", size9pt)/2
For i=basey-dy to basey-dy*x#max() Step dy
Move basex, i
Step -twipsx*10
Width 1, dotline { draw scale.x/2+twipsx*10,,7}
Move basex-100, i+HalfTextHeight
Legend format$("{0}",(i-basey)/scY), "courier", size9pt, angle, left
Next i
ex=each(x) : ey=each(y)
\\ start from first point. We use Draw to for absolute coordinates
Move array(x,0)*dx+Basex, array(y,0)*scy+Basey
While ex, ey {
Width 2 {
Draw to array(ex)*dx+Basex, array(ey)*scy+Basey, blue
}
}
\\ second pass for marks and labels
ex=each(x) : ey=each(y)
While ex, ey {
Move array(ex)*dx+Basex, array(ey)*scy+Basey
Step -75, -75
Pen 12 {draw 150: draw 0,150 : draw -150 : draw 0,-150}
Pen 13 {
Step 200, -200
Legend format$("({0}-{1})",array(ex),array(ey) ), "courier bold", size11pt, angle, right
}
}
\\ screenshot to clipboard
Screenshot$=""
Move 0,0
Copy scale.x, scale.y to Screenshot$
Clipboard Screenshot$
a$=key$
}
Pairs
|
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
| #JavaScript | JavaScript | /* create new Point in one of these ways:
* var p = new Point(x,y);
* var p = new Point(a_point);
* default value for x,y is 0
*/
function Point() {
var arg1 = arguments[0];
var arg2 = arguments[1];
if (arg1 instanceof Point) {
this.x = arg1.x;
this.y = arg1.y;
}
else {
this.x = arg1 == null ? 0 : arg1;
this.y = arg2 == null ? 0 : arg1;
}
this.set_x = function(_x) {this.x = _x;}
this.set_y = function(_y) {this.y = _y;}
}
Point.prototype.print = function() {
var out = "Point(" + this.x + "," + this.y + ")";
print(out);
}
/* create new Circle in one of these ways:
* var c = new Circle(x,y,r);
* var c = new Circle(a_circle);
* var c = new Circle(a_point,r);
* default value for x,y,r is 0
*/
function Circle() {
var arg1 = arguments[0];
var arg2 = arguments[1];
var arg3 = arguments[2];
if (arg1 instanceof Circle) {
this.x = arg1.x;
this.y = arg1.y;
this.r = arg1.r;
}
else if (arg1 instanceof Point) {
this.x = arg1.x;
this.y = arg1.y;
this.r = arg2 == null ? 0 : arg2;
}
else {
this.x = arg1 == null ? 0 : arg1;
this.y = arg2 == null ? 0 : arg2;
this.r = arg3 == null ? 0 : arg3;
}
this.set_x = function(_x) {this.x = _x;}
this.set_y = function(_y) {this.y = _y;}
this.set_r = function(_r) {this.r = _r;}
}
Circle.prototype.print = function() {
var out = "Circle(" + this.x + "," + this.y + "," + this.r + ")";
print(out);
} |
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
| #Racket | Racket | #lang racket
(require (only-in srfi/1 car+cdr))
;;; --------------------------------------------------------------------------------------------------
;;; The analyser is first... the rest of it is prettiness surrounding strings and parsing!
;;; --------------------------------------------------------------------------------------------------
;; (cons f _) and (cons _ s) appear too frequently in patterns to not factor out
(define-match-expander F._ (λ (stx) (syntax-case stx () [(_ f) #'(cons f _)])))
(define-match-expander _.S (λ (stx) (syntax-case stx () [(_ s) #'(cons _ s)])))
;; Matches are easier when the cards are lined up by face: and I always put the cards in my hand with
;; the highest card on the left (should I be telling this?)... anyway face<? is written to leave high
;; cards on the left. There is no need to sort by suit, flushes are all-or-nothing
(define (face-sort hand)
(sort hand (match-lambda** [(_ 'joker) #f] [('joker _) #t] [((F._ f1) (F._ f2)) (> f1 f2)])))
;; even playing poker for money, I never managed to consistently determine what effect jokers were
;; having on my hand... so I'll do an exhaustive search of what's best!
;;
;; scoring hands allows us to choose a best value for joker(s)
;; hand-names provides an order (and therefore a score) for each of the available hands
(define hand-names (list 'five-of-a-kind 'straight-flush 'four-of-a-kind 'full-house 'flush 'straight
'three-of-a-kind 'two-pair 'one-pair 'high-card))
(define hand-order# (for/hash ((h hand-names) (i (in-range (add1 (length hand-names)) 0 -1)))
(values h i)))
;; The score of a hand is (its order*15^5)+(first tiebreaker*15^4)+(2nd tiebreaker*15^3)...
;; powers of 15 because we have a maxmium face value of 14 (ace) -- even though there are 13 cards
;; in a suit.
(define (calculate-score analysis)
(define-values (hand-name tiebreakers) (car+cdr analysis))
(for/sum ((n (in-naturals)) (tb (cons (hash-ref hand-order# hand-name -1) tiebreakers)))
(* tb (expt 15 (- 5 n)))))
;; score hand produces an analysis of a hand (which can then be returned to analyse-sorted-hand,
;; and a score that can be maximised by choosing the right jokers.
(define (score-hand hand . jokers) ; gives an orderable list of hands with tiebreakers
(define analysis (analyse-sorted-hand (face-sort (append jokers hand))))
(cons analysis (calculate-score analysis)))
;; if we have two (or more) jokers, they will be consumed by the recursive call to
;; analyse-sorted-hand score-hand
(define all-cards/promise (delay (for*/list ((f (in-range 2 15)) (s '(h d s c))) (cons f s))))
(define (best-jokered-hand cards) ; we've lost the first joker from cards
(define-values (best-hand _bhs)
(for*/fold ((best-hand #f) (best-score 0))
((joker (in-list (force all-cards/promise)))
(score (in-value (score-hand cards joker)))
#:when (> (cdr score) best-score))
(car+cdr score)))
best-hand)
;; we can abbreviate 2/3/4/5-of-a-kind 2-pair full-house with 2 and 3
(define-match-expander F*2 (λ (stx) (syntax-case stx () [(_ f) #'(list (F._ f) (F._ f))])))
(define-match-expander F*3 (λ (stx) (syntax-case stx () [(_ f) #'(list (F._ f) (F._ f) (F._ f))])))
;; note that flush? is cheaper to calculate than straight?, so do it first when we test for
;; straight-flush
(define flush?
(match-lambda [(and `(,(_.S s) ,(_.S s) ,(_.S s) ,(_.S s) ,(_.S s)) `(,(F._ fs) ...)) `(flush ,@fs)]
[_ #f]))
(define straight?
(match-lambda
;; '(straight 5) puts this at the bottom of the pile w.r.t the ordering of straights
[`(,(F._ 14) ,(F._ 5) ,(F._ 4) ,(F._ 3) ,(F._ 2)) '(straight 5)]
[`(,(F._ f5) ,(F._ f4) ,(F._ f3) ,(F._ f2) ,(F._ f1))
(and (= f1 (- f5 4)) (< f1 f2 f3 f4 f5) `(straight ,f5))]))
(define analyse-sorted-hand
(match-lambda
[(list 'joker cards ...) (best-jokered-hand cards)]
[`(,@(F*3 f) ,@(F*2 f)) `(five-of-a-kind ,f)]
;; get "top" from the straight. a the top card of the flush when there is a (straight 5) will
;; be the ace ... putting it in the wrong place for the ordering.
[(and (? flush?) (app straight? (list 'straight top _ ...))) `(straight-flush ,top)]
[(or `(,@(F*2 f) ,@(F*2 f) ,_) `(,_ ,@(F*2 f) ,@(F*2 f))) `(four-of-a-kind ,f)]
[(or `(,@(F*3 fh) ,@(F*2 fl)) `(,@(F*2 fh) ,@(F*3 fl))) `(full-house ,fh, fl)]
[(app flush? (and rv (list 'flush _ ...))) rv]
[(app straight? (and rv (list 'straight _ ...))) rv]
;; pairs and threes may be padded to the left, middle and right with tie-breakers; the lists of
;; which we will call l, m and r, respectively (four and 5-of-a-kind don't need tiebreaking,
;; they're well hard!)
[`(,(F._ l) ... ,@(F*3 f) ,(F._ r) ...) `(three-of-a-kind ,f ,@l ,@r)]
[`(,(F._ l) ... ,@(F*2 f1) ,(F._ m) ... ,@(F*2 f2) ,(F._ r) ...) `(two-pair ,f1 ,f2 ,@l ,@m ,@r)]
[`(,(F._ l) ... ,@(F*2 f) ,(F._ r) ...) `(one-pair ,f ,@l ,@r)]
[`(,(F._ f) ...) `(high-card ,@f)]
[hand (error 'invalid-hand hand)]))
(define (analyse-hand/string hand-string)
(analyse-sorted-hand (face-sort (string->hand hand-string))))
;;; --------------------------------------------------------------------------------------------------
;;; Strings to cards, cards to strings -- that kind of thing
;;; --------------------------------------------------------------------------------------------------
(define suit->unicode (match-lambda ('h "♥") ('d "♦") ('c "♣") ('s "♠") (x x)))
(define unicode->suit (match-lambda ("♥" 'h) ("♦" 'd) ("♣" 'c) ("♠" 's) (x x)))
(define (face->number f)
(match (string-upcase f)
["T" 10] ["J" 11] ["Q" 12] ["K" 13] ["A" 14] [(app string->number (? number? n)) n] [else 0]))
(define number->face (match-lambda (10 "T") (11 "J") (12 "Q") (13 "K") (14 "A") ((app ~s x) x)))
(define string->card
(match-lambda
("joker" 'joker)
((regexp #px"^(.*)(.)$" (list _ (app face->number num) (app unicode->suit suit)))
(cons num suit))))
(define (string->hand str)
(map string->card (regexp-split #rx" +" (string-trim str))))
(define card->string
(match-lambda ['joker "[]"]
[(cons (app number->face f) (app suit->unicode s)) (format "~a~a" f s)]))
(define (hand->string h)
(string-join (map card->string h) " "))
;; used for both testing and output
(define e.g.-hands
(list " 2♥ 2♦ 2♣ k♣ q♦" " 2♥ 5♥ 7♦ 8♣ 9♠" " a♥ 2♦ 3♣ 4♣ 5♦" "10♥ j♦ q♣ k♣ a♦"
" 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♦"))
;;; --------------------------------------------------------------------------------------------------
;;; Main and test modules
;;; --------------------------------------------------------------------------------------------------
(module+ main
(define scored-hands
(for/list ((h (map string->hand e.g.-hands)))
(define-values (analysis score) (car+cdr (score-hand h)))
(list h analysis score)))
(for ((a.s (sort scored-hands > #:key third)))
(match-define (list (app hand->string h) a _) a.s)
(printf "~a: ~a ~a" h (~a (first a) #:min-width 15) (number->face (second a)))
(when (pair? (cddr a)) (printf " [tiebreak: ~a]" (string-join (map number->face (cddr a)) ", ")))
(newline)))
(module+ test
(require rackunit)
(let ((e.g.-strght-flsh '((14 . h) (13 . h) (12 . h) (11 . h) (10 . h))))
(check-match (straight? e.g.-strght-flsh) '(straight 14))
(check-match (flush? e.g.-strght-flsh) '(flush 14 13 12 11 10))
(check-match e.g.-strght-flsh (and (? flush?) (app straight? (list 'straight top _ ...)))))
(define expected-results
'((three-of-a-kind 2 13 12)
(high-card 9 8 7 5 2) (straight 5) (straight 14) (full-house 3 2) (two-pair 3 2 7)
(four-of-a-kind 7) (straight-flush 14) (one-pair 4 13 10 5) (flush 12 10 7 6 4)
(three-of-a-kind 2 13 12) (straight 9) (straight 6) (four-of-a-kind 3) (three-of-a-kind 3 7 2)
(five-of-a-kind 7) (straight-flush 14) (one-pair 13 10 5 4) (flush 14 13 7 6 4) (straight 6)
(straight 14) (straight-flush 14) (four-of-a-kind 2)))
(for ((h e.g.-hands) (r expected-results)) (check-equal? (analyse-hand/string h) r))) |
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.
| #Forth | Forth | : popcnt ( n -- u) 0 swap
BEGIN dup WHILE tuck 1 AND + swap 1 rshift REPEAT
DROP ;
: odious? ( n -- t|f) popcnt 1 AND ;
: evil? ( n -- t|f) odious? 0= ;
CREATE A 30 ,
: task1 1 0 ." 3**i popcnt: "
BEGIN dup A @ < WHILE
over popcnt . 1+ swap 3 * swap
REPEAT DROP DROP CR ;
: task2 0 0 ." evil : "
BEGIN dup A @ < WHILE
over evil? IF over . 1+ THEN swap 1+ swap
REPEAT DROP DROP CR ;
: task3 0 0 ." odious : "
BEGIN dup A @ < WHILE
over odious? IF over . 1+ THEN swap 1+ swap
REPEAT DROP DROP CR ;
task1 task2 task3 BYE |
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
| #PicoLisp | PicoLisp | (de degree (P)
(let I NIL
(for (N . C) P
(or (=0 C) (setq I N)) )
(dec I) ) )
(de divPoly (N D)
(if (lt0 (degree D))
(quit "Div/0" D)
(let (Q NIL Diff)
(while (ge0 (setq Diff (- (degree N) (degree D))))
(setq Q (need (- -1 Diff) Q 0))
(let E D
(do Diff (push 'E 0))
(let F (/ (get N (inc (degree N))) (get E (inc (degree E))))
(set (nth Q (inc Diff)) F)
(setq N (mapcar '((N E) (- N (* E F))) N E)) ) ) )
(list Q N) ) ) ) |
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
| #Python | Python | # -*- coding: utf-8 -*-
from itertools import izip
def degree(poly):
while poly and poly[-1] == 0:
poly.pop() # normalize
return len(poly)-1
def poly_div(N, D):
dD = degree(D)
dN = degree(N)
if dD < 0: raise ZeroDivisionError
if dN >= dD:
q = [0] * dN
while dN >= dD:
d = [0]*(dN - dD) + D
mult = q[dN - dD] = N[-1] / float(d[-1])
d = [coeff*mult for coeff in d]
N = [coeffN - coeffd for coeffN, coeffd in izip(N, d)]
dN = degree(N)
r = N
else:
q = [0]
r = N
return q, r
if __name__ == '__main__':
print "POLYNOMIAL LONG DIVISION"
N = [-42, 0, -12, 1]
D = [-3, 1, 0, 0]
print " %s / %s =" % (N,D),
print " %s remainder %s" % poly_div(N, D) |
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.
| #Octave | Octave | x = [0:10];
y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
coeffs = polyfit(x, y, 2) |
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.
| #Groovy | Groovy |
def powerSetRec(head, tail) {
if (!tail) return [head]
powerSetRec(head, tail.tail()) + powerSetRec(head + [tail.head()], tail.tail())
}
def powerSet(set) { powerSetRec([], set as List) as Set}
|
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
| #D | D | import std.stdio, std.algorithm, std.range, std.math;
bool isPrime1(in int n) pure nothrow {
if (n == 2)
return true;
if (n <= 1 || (n & 1) == 0)
return false;
for(int i = 3; i <= real(n).sqrt; i += 2)
if (n % i == 0)
return false;
return true;
}
void main() {
iota(2, 40).filter!isPrime1.writeln;
} |
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
| #langur | langur | # using an implied parameter .f ...
val .pricefrac = f given .f {
case >= 0.00, < 0.06: 0.10
case >= 0.06, < 0.11: 0.18
case >= 0.11, < 0.16: 0.26
case >= 0.16, < 0.21: 0.32
case >= 0.21, < 0.26: 0.38
case >= 0.26, < 0.31: 0.44
case >= 0.31, < 0.36: 0.50
case >= 0.36, < 0.41: 0.54
case >= 0.41, < 0.46: 0.58
case >= 0.46, < 0.51: 0.62
case >= 0.51, < 0.56: 0.66
case >= 0.56, < 0.61: 0.70
case >= 0.61, < 0.66: 0.74
case >= 0.66, < 0.71: 0.78
case >= 0.71, < 0.76: 0.82
case >= 0.76, < 0.81: 0.86
case >= 0.81, < 0.86: 0.90
case >= 0.86, < 0.91: 0.94
case >= 0.91, < 0.96: 0.98
case >= 0.96, <= 1.00: 1.00
default: throw "bad data"
# The default operator between test cases is "and".
# That is, writing "case" without a logical operator is the same as writing "case and".
# To make a given case act as a switch case does in other languages, use "case or".
}
writeln .pricefrac(0.17)
writeln .pricefrac(0.71) |
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
| #Perl | Perl | use ntheory qw/divisors/;
sub proper_divisors {
my $n = shift;
# Like Pari/GP, divisors(0) = (0,1) and divisors(1) = ()
return 1 if $n == 0;
my @d = divisors($n);
pop @d; # divisors are in sorted order, so last entry is the input
@d;
}
say "$_: ", join " ", proper_divisors($_) for 1..10;
# 1. For the max, we can do a traditional loop.
my($max,$ind) = (0,0);
for (1..20000) {
my $nd = scalar proper_divisors($_);
($max,$ind) = ($nd,$_) if $nd > $max;
}
say "$max $ind";
# 2. Or we can use List::Util's max with decoration (this exploits its implementation)
{
use List::Util qw/max/;
no warnings 'numeric';
say max(map { scalar(proper_divisors($_)) . " $_" } 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)
| #VBScript | VBScript |
item = Array("aleph","beth","gimel","daleth","he","waw","zayin","heth")
prob = Array(1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720)
Dim cnt(7)
'Terminate script if sum of probabilities <> 1.
sum = 0
For i = 0 To UBound(prob)
sum = sum + prob(i)
Next
If sum <> 1 Then
WScript.Quit
End If
For trial = 1 To 1000000
r = Rnd(1)
p = 0
For i = 0 To UBound(prob)
p = p + prob(i)
If r < p Then
cnt(i) = cnt(i) + 1
Exit For
End If
Next
Next
WScript.StdOut.Write "item" & vbTab & "actual" & vbTab & vbTab & "theoretical"
WScript.StdOut.WriteLine
For i = 0 To UBound(item)
WScript.StdOut.Write item(i) & vbTab & FormatNumber(cnt(i)/1000000,6) & vbTab & FormatNumber(prob(i),6)
WScript.StdOut.WriteLine
Next |
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.
| #Prolog | Prolog | priority-queue :-
TL0 = [3-'Clear drains',
4-'Feed cat'],
% we can create a priority queue from a list
list_to_heap(TL0, Heap0),
% alternatively we can start from an empty queue
% get from empty_heap/1.
% now we add the other elements
add_to_heap(Heap0, 5, 'Make tea', Heap1),
add_to_heap(Heap1, 1, 'Solve RC tasks', Heap2),
add_to_heap(Heap2, 2, 'Tax return', Heap3),
% we list the content of the heap:
heap_to_list(Heap3, TL1),
writeln('Content of the queue'), maplist(writeln, TL1),
nl,
% now we retrieve the minimum-priority pair
get_from_heap(Heap3, Priority, Key, Heap4),
format('Retrieve top of the queue : Priority ~w, Element ~w~n', [Priority, Key]),
nl,
% we list the content of the heap:
heap_to_list(Heap4, TL2),
writeln('Content of the queue'), maplist(writeln, TL2).
|
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
| #Haskell | Haskell | factorize n = [ d | p <- [2..n], isPrime p, d <- divs n p ]
-- [2..n] >>= (\p-> [p|isPrime p]) >>= divs n
where
divs n p | rem n p == 0 = p : divs (quot n p) p
| otherwise = [] |
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.
| #Maple | Maple | x := Vector([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
y := Vector([2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]):
plot(x,y,style="point"); |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 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};
ListPlot[{x, y} // Transpose] |
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
| #jq | jq |
def Point(x;y): {"type": "Point", "x": x, "y": y};
def Point(x): Point(x;0);
def Point: Point(0);
def Circle(x;y;r): {"type": "Circle", "x": x, "y": y, "r": r};
def Circle(x;y): Circle(x;y;0);
def Circle(x): Circle(x;0);
def Circle: Circle(0);
def print:
if .type == "Circle" then "\(.type)(\(.x); \(.y); \(.r))"
elif .type == "Point" then "\(.type)(\(.x); \(.y))"
else empty
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
| #Julia | Julia | mutable struct Point
x::Float64
y::Float64
end
Base.show(io::IO, p::Point) = print(io, "Point($(p.x), $(p.y))")
getx(p::Point) = p.x
gety(p::Point) = p.y
setx(p::Point, x) = (p.x = x)
sety(p::Point, y) = (p.y = y)
mutable struct Circle
x::Float64
y::Float64
r::Float64
end
getx(c::Circle) = c.x
gety(c::Circle) = c.y
getr(c::Circle) = c.r
setx(c::Circle, x) = (c.x = x)
sety(c::Circle, y) = (c.y = y)
setr(c::Circle, r) = (c.r = r)
Base.show(io::IO, c::Circle) = print(io, "Circle($(c.x), $(c.y), $(c.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
| #Raku | Raku | use v6;
grammar PokerHand {
# Raku Grammar to parse and rank 5-card poker hands
# E.g. PokerHand.parse("2♥ 3♥ 2♦ 3♣ 3♦");
# 2013-12-21: handle 'joker' wildcards; maximum of two
rule TOP {
:my %*PLAYED;
{ %*PLAYED = () }
[ <face-card> | <joker> ]**5
}
token face-card {<face><suit> <?{
my $card = ~$/.lc;
# disallow duplicates
++%*PLAYED{$card} <= 1;
}>
}
token joker {:i 'joker' <?{
my $card = ~$/.lc;
# allow two jokers in a hand
++%*PLAYED{$card} <= 2;
}>
}
token face {:i <[2..9 jqka]> | 10 }
token suit {<[♥ ♦ ♣ ♠]>}
}
class PokerHand::Actions {
method TOP($/) {
my UInt @n = n-of-a-kind($/);
my $flush = 'flush' if flush($/);
my $straight = 'straight' if straight($/);
make rank(@n[0], @n[1], $flush, $straight);
}
multi sub rank(5,*@) { 'five-of-a-kind' }
multi sub rank($,$,'flush','straight') { 'straight-flush' }
multi sub rank(4,*@) { 'four-of-a-kind' }
multi sub rank($,$,'flush',$) { 'flush' }
multi sub rank($,$,$,'straight') { 'straight' }
multi sub rank(3,2,*@) { 'full-house' }
multi sub rank(3,*@) { 'three-of-a-kind' }
multi sub rank(2,2,*@) { 'two-pair' }
multi sub rank(2,*@) { 'one-pair' }
multi sub rank(*@) { 'high-card' }
sub n-of-a-kind($/) {
my %faces := bag @<face-card>.map: -> $/ {~$<face>.lc};
my @counts = %faces.values.sort.reverse;
@counts[0] += @<joker>;
return @counts;
}
sub flush($/) {
my @suits = unique @<face-card>.map: -> $/ {~$<suit>};
return +@suits == 1;
}
sub straight($/) {
# allow both ace-low and ace-high straights
constant @Faces = [ "a 2 3 4 5 6 7 8 9 10 j q k a".split: ' ' ];
constant @Possible-Straights = [ (4 ..^ @Faces).map: { set @Faces[$_-4 .. $_] } ];
my $faces = set @<face-card>.map: -> $/ {~$<face>.lc};
my $jokers = +@<joker>;
return ?( @Possible-Straights.first: { +($faces ∩ $_) + $jokers == 5 } );
}
}
my PokerHand::Actions $actions .= new;
for ("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♣ 4♣", # flush
"a♥ a♥ 3♣ 4♣ 5♦", # invalid
## EXTRA CREDIT ##
"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
) {
my $rank = do with PokerHand.parse($_, :$actions) {
.ast;
}
else {
'invalid';
}
say "$_: $rank";
}
|
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.
| #Fortran | Fortran | program population_count
implicit none
integer, parameter :: i64 = selected_int_kind(18)
integer(i64) :: x
integer :: i, n
x = 1
write(*, "(a8)", advance = "no") "3**i :"
do i = 1, 30
write(*, "(i3)", advance = "no") popcnt(x)
x = x * 3
end do
write(*,*)
write(*, "(a8)", advance = "no") "Evil :"
n = 0
x = 0
do while(n < 30)
if(mod(popcnt(x), 2) == 0) then
n = n + 1
write(*, "(i3)", advance = "no") x
end if
x = x + 1
end do
write(*,*)
write(*, "(a8)", advance = "no") "Odious :"
n = 0
x = 0
do while(n < 30)
if(mod(popcnt(x), 2) /= 0) then
n = n + 1
write(*, "(i3)", advance = "no") x
end if
x = x + 1
end do
contains
integer function popcnt(x)
integer(i64), intent(in) :: x
integer :: i
popcnt = 0
do i = 0, 63
if(btest(x, i)) popcnt = popcnt + 1
end do
end function
end program |
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
| #R | R | polylongdiv <- function(n,d) {
gd <- length(d)
pv <- vector("numeric", length(n))
pv[1:gd] <- d
if ( length(n) >= gd ) {
q <- c()
while ( length(n) >= gd ) {
q <- c(q, n[1]/pv[1])
n <- n - pv * (n[1]/pv[1])
n <- n[2:length(n)]
pv <- pv[1:(length(pv)-1)]
}
list(q=q, r=n)
} else {
list(q=c(0), r=n)
}
}
# an utility function to print polynomial
print.polynomial <- function(p) {
i <- length(p)-1
for(a in p) {
if ( i == 0 ) {
cat(a, "\n")
} else {
cat(a, "x^", i, " + ", sep="")
}
i <- i - 1
}
}
r <- polylongdiv(c(1,-12,0,-42), c(1,-3))
print.polynomial(r$q)
print.polynomial(r$r) |
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.
| #PARI.2FGP | PARI/GP | polinterpolate([0,1,2,3,4,5,6,7,8,9,10],[1,6,17,34,57,86,121,162,209,262,321]) |
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.
| #Haskell | Haskell | import Data.Set
import Control.Monad
powerset :: Ord a => Set a -> Set (Set a)
powerset = fromList . fmap fromList . listPowerset . toList
listPowerset :: [a] -> [[a]]
listPowerset = filterM (const [True, False]) |
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
| #Delphi | Delphi | function IsPrime(aNumber: Integer): Boolean;
var
I: Integer;
begin
Result:= True;
if(aNumber = 2) then Exit;
Result:= not ((aNumber mod 2 = 0) or
(aNumber <= 1));
if not Result then Exit;
for I:=3 to Trunc(Sqrt(aNumber)) do
if(aNumber mod I = 0) then
begin
Result:= False;
Break;
end;
end; |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Liberty_BASIC | Liberty BASIC |
dim DR(38) 'decimal range
dim PF(38) 'corresponding price fraction
range$="0.06 0.11 0.16 0.21 0.26 0.31 0.36 0.41 0.46 0.51 0.56 0.61 0.66 0.71 0.76 0.81 0.86 0.91 0.96 0.01"
frac$="0.10 0.18 0.26 0.32 0.38 0.44 0.50 0.54 0.58 0.62 0.66 0.70 0.74 0.78 0.82 0.86 0.90 0.94 0.98 1.00"
for i = 1 to 38
DR(i)=val(word$(range$,i))
PF(i)=val(word$(frac$,i))
next
for i = 0 to .99 step 0.03
print i;" -> ";PriceFraction(i)
next
end
Function PriceFraction(n)
PriceFraction=n 'return original if outside test bounds
for i = 1 to 38
if n<=DR(i) then
PriceFraction=PF(i)
exit for
end if
next
end function
|
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
| #Phix | Phix | global function factors(atom n, integer include1=0)
--
-- returns a list of all integer factors of n
-- if include1 is 0 (the default), result does not contain either 1 or n
-- if include1 is 1 the result contains 1 and n
-- if include1 is -1 the result contains 1 but not n
--
if n=0 then return {} end if
check_limits(n,"factors")
sequence lfactors = {}, hfactors = {}
atom hfactor
integer p = 2,
lim = floor(sqrt(n))
if include1!=0 then
lfactors = {1}
if n!=1 and include1=1 then
hfactors = {n}
end if
end if
while p<=lim do
if remainder(n,p)=0 then
lfactors = append(lfactors,p)
hfactor = n/p
if hfactor=p then exit end if
hfactors = prepend(hfactors,hfactor)
end if
p += 1
end while
return lfactors & hfactors
end function
|
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)
| #Wren | Wren | import "random" for Random
import "/fmt" for Fmt
var letters = ["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"]
var actual = [0] * 8
var probs = [1/5, 1/6, 1/7, 1/8, 1/9, 1/10, 1/11, 0]
var cumProbs = [0] * 8
cumProbs[0] = probs[0]
for (i in 1..6) cumProbs[i] = cumProbs[i-1] + probs[i]
cumProbs[7] = 1
probs[7] = 1 - cumProbs[6]
var n = 1e6
var rand = Random.new()
(1..n).each { |i|
var r = rand.float()
var index = (r <= cumProbs[0]) ? 0 :
(r <= cumProbs[1]) ? 1 :
(r <= cumProbs[2]) ? 2 :
(r <= cumProbs[3]) ? 3 :
(r <= cumProbs[4]) ? 4 :
(r <= cumProbs[5]) ? 5 :
(r <= cumProbs[6]) ? 6 : 7
actual[index] = actual[index] + 1
}
var sumActual = 0
System.print("Letter\t Actual Expected")
System.print("------\t-------- --------")
for (i in 0..7) {
var generated = actual[i]/n
Fmt.print("$s\t$8.6f $8.6f", letters[i], generated, probs[i])
sumActual = sumActual + generated
}
System.print("\t-------- --------")
Fmt.print("\t$8.6f 1.000000", sumActual) |
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.
| #PureBasic | PureBasic | Structure taskList
List description.s() ;implements FIFO queue
EndStructure
Structure task
*tl.tList ;pointer to a list of task descriptions
Priority.i ;tasks priority, lower value has more priority
EndStructure
Structure priorityQueue
maxHeapSize.i ;increases as needed
heapItemCount.i ;number of elements currently in heap
Array heap.task(0) ;elements hold FIFO queues ordered by priorities, lowest first
map heapMap.taskList() ;holds lists of tasks with the same priority that are FIFO queues
EndStructure
Procedure insertPQ(*PQ.priorityQueue, description.s, p)
If FindMapElement(*PQ\heapMap(), Str(p))
LastElement(*PQ\heapMap()\description())
AddElement(*PQ\heapMap()\description())
*PQ\heapMap()\description() = description
Else
Protected *tl.taskList = AddMapElement(*PQ\heapMap(), Str(p))
AddElement(*tl\description())
*tl\description() = description
Protected pos = *PQ\heapItemCount
*PQ\heapItemCount + 1
If *PQ\heapItemCount > *PQ\maxHeapSize
Select *PQ\maxHeapSize
Case 0
*PQ\maxHeapSize = 128
Default
*PQ\maxHeapSize * 2
EndSelect
Redim *PQ\heap.task(*PQ\maxHeapSize)
EndIf
While pos > 0 And p < *PQ\heap((pos - 1) / 2)\Priority
*PQ\heap(pos) = *PQ\heap((pos - 1) / 2)
pos = (pos - 1) / 2
Wend
*PQ\heap(pos)\tl = *tl
*PQ\heap(pos)\Priority = p
EndIf
EndProcedure
Procedure.s removePQ(*PQ.priorityQueue)
Protected *tl.taskList = *PQ\heap(0)\tl, description.s
FirstElement(*tl\description())
description = *tl\description()
If ListSize(*tl\description()) > 1
DeleteElement(*tl\description())
Else
DeleteMapElement(*PQ\heapMap(), Str(*PQ\heap(0)\Priority))
*PQ\heapItemCount - 1
*PQ\heap(0) = *PQ\heap(*PQ\heapItemCount)
Protected pos
Repeat
Protected child1 = 2 * pos + 1
Protected child2 = 2 * pos + 2
If child1 >= *PQ\heapItemCount
Break
EndIf
Protected smallestChild
If child2 >= *PQ\heapItemCount
smallestChild = child1
ElseIf *PQ\heap(child1)\Priority <= *PQ\heap(child2)\Priority
smallestChild = child1
Else
smallestChild = child2
EndIf
If (*PQ\heap(smallestChild)\Priority >= *PQ\heap(pos)\Priority)
Break
EndIf
Swap *PQ\heap(pos)\tl, *PQ\heap(smallestChild)\tl
Swap *PQ\heap(pos)\Priority, *PQ\heap(smallestChild)\Priority
pos = smallestChild
ForEver
EndIf
ProcedureReturn description
EndProcedure
Procedure isEmptyPQ(*PQ.priorityQueue) ;returns 1 if empty, otherwise returns 0
If *PQ\heapItemCount
ProcedureReturn 0
EndIf
ProcedureReturn 1
EndProcedure
If OpenConsole()
Define PQ.priorityQueue
insertPQ(PQ, "Clear drains", 3)
insertPQ(PQ, "Answer Phone 1", 8)
insertPQ(PQ, "Feed cat", 4)
insertPQ(PQ, "Answer Phone 2", 8)
insertPQ(PQ, "Make tea", 5)
insertPQ(PQ, "Sleep", 9)
insertPQ(PQ, "Check email", 3)
insertPQ(PQ, "Solve RC tasks", 1)
insertPQ(PQ, "Answer Phone 3", 8)
insertPQ(PQ, "Exercise", 9)
insertPQ(PQ, "Answer Phone 4", 8)
insertPQ(PQ, "Tax return", 2)
While Not isEmptyPQ(PQ)
PrintN(removePQ(PQ))
Wend
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
factors := primedecomp(2^43-1) # a big int
end
procedure primedecomp(n) #: return a list of factors
local F,o,x
F := []
every writes(o,n|(x := genfactors(n))) do {
\o := "*"
/o := "="
put(F,x) # build a list of factors to satisfy the task
}
write()
return F
end
link factors |
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.
| #MATLAB | MATLAB | >> 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];
>> plot(x,y,'.-') |
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.
| #Maxima | Maxima | (%i1) ".." (m, n) := makelist (i, i, m, n); infix ("..")$
(%i2) x: 0 .. 9$ y:[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]$
(%i3) plot2d(['discrete, x, y], [style, [points,5,1,1]], [gnuplot_term, png], [gnuplot_out_file, "qsort-range-10-9.png"])$ |
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
| #Kotlin | Kotlin | // version 1.1.2
open class Point(var x: Int, var y: Int) {
constructor(): this(0, 0)
constructor(x: Int) : this(x, 0)
constructor(p: Point) : this(p.x, p.y)
open protected fun finalize() = println("Finalizing $this...")
override fun toString() = "Point at ($x, $y)"
open fun print() = println(this)
}
class Circle(x: Int, y: Int, var r: Int) : Point(x, y) {
constructor(): this(0, 0, 0)
constructor(x: Int) : this(x, 0, 0)
constructor(x: Int, r: Int) : this(x, 0, r)
constructor(c: Circle) : this(c.x, c.y, c.r)
// for simplicity not calling super.finalize() below though this would normally be done in practice
override protected fun finalize() = println("Finalizing $this...")
override fun toString() = "Circle at center ($x, $y), radius $r"
override fun print() = println(this)
}
fun createObjects() {
val points = listOf(Point(), Point(1), Point(2, 3), Point(Point(3, 4)))
for (point in points) point.print()
val circles = listOf(Circle(), Circle(1), Circle(2, 3), Circle(4, 5, 6), Circle(Circle(7, 8, 9)))
for (circle in circles) circle.print()
println()
}
fun main(args: Array<String>) {
createObjects()
System.gc() // try and force garbage collection
Thread.sleep(2000) // allow time for finalizers to run
println()
val p = Point(5, 6)
p.print()
p.y = 7 // change y coordinate
p.print()
val c = Circle(5, 6, 7)
c.print()
c.r = 8
c.print() // change radius
/* note that finalizers for p and c are not called */
} |
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
| #REXX | REXX | /* REXX ---------------------------------------------------------------
* 10.12.2013 Walter Pachl
*--------------------------------------------------------------------*/
d.1='2h 2d 2s ks qd'; x.1='three-of-a-kind'
d.2='2h 5h 7d 8s 9d'; x.2='high-card'
d.3='ah 2d 3s 4s 5s'; x.3='straight'
d.4='2h 3h 2d 3s 3d'; x.4='full-house'
d.5='2h 7h 2d 3s 3d'; x.5='two-pair'
d.6='2h 7h 7d 7s 7c'; x.6='four-of-a-kind'
d.7='th jh qh kh ah'; x.7='straight-flush'
d.8='4h 4c kc 5d tc'; x.8='one-pair'
d.9='qc tc 7c 6c 4c'; x.9='flush'
d.10='ah 2h 3h 4h'
d.11='ah 2h 3h 4h 5h 6h'
d.12='2h 2h 3h 4h 5h'
d.13='xh 2h 3h 4h 5h'
d.14='2x 2h 3h 4h 5h'
Do ci=1 To 14
Call poker d.ci,x.ci
end
Exit
poker:
Parse Arg deck,expected
have.=0
f.=0; fmax=0
s.=0; smax=0
cnt.=0
If words(deck)<5 Then Return err('less than 5 cards')
If words(deck)>5 Then Return err('more than 5 cards')
Do i=1 To 5
c=word(deck,i)
Parse Var c f +1 s
If have.f.s=1 Then Return err('duplicate card:' c)
have.f.s=1
m=pos(f,'a23456789tjqk')
If m=0 Then Return err('invalid face' f 'in' c)
cnt.m=cnt.m+1
n=pos(s,'hdcs')
If n=0 Then Return err('invalid suit' s 'in' c)
f.m=f.m+1; fmax=max(fmax,f.m)
s.n=s.n+1; smax=max(smax,s.n)
End
cntl=''
cnt.14=cnt.1
Do i=1 To 14
cntl=cntl||cnt.i
End
Select
When fmax=4 Then res='four-of-a-kind'
When fmax=3 Then Do
If x_pair() Then
res='full-house'
Else
res='three-of-a-kind'
End
When fmax=2 Then Do
If x_2pair() Then
res='two-pair'
Else
res='one-pair'
End
When smax=5 Then Do
If x_street() Then
res='straight-flush'
Else
res='flush'
End
When x_street() Then
res='straight'
Otherwise
res='high-card'
End
Say deck res
If res<>expected Then
Say copies(' ',14) expected
Return
x_pair:
Do p=1 To 13
If f.p=2 Then return 1
End
Return 0
x_2pair:
pp=0
Do p=1 To 13
If f.p=2 Then pp=pp+1
End
Return pp=2
x_street:
Return pos('11111',cntl)>0
err:
Say deck 'Error:' arg(1)
Return 0 |
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.
| #Free_Pascal | Free Pascal | program populationCount(input, output, stdErr);
var
// general advice: iterator variables are _signed_
iterator: int64;
// the variable we’d like to count the set bits in
number: qWord;
// how many evil numbers we’ve already found
evilCount: int64;
// odious numbers
odiousNumber: array[1..30] of qWord;
odiousIterator: int64;
begin
// population count for powers of three
for iterator := 0 to 29 do
begin
number := round(exp(ln(3) * iterator));
write(popCnt(number):3);
end;
writeLn();
// evil numbers
// (while preserving calculated odious numbers for next sub-task)
evilCount := 0;
odiousIterator := low(odiousNumber);
// for-loop: because we (pretend to) don’t know,
// when and where we’ve found the first 30 numbers of each
for iterator := 0 to high(iterator) do
begin
// implicit typecast: popCnt only accepts _un_-signed integers
number := iterator;
if odd(popCnt(number)) then
begin
if odiousIterator <= high(odiousNumber) then
begin
odiousNumber[odiousIterator] := number;
inc(odiousIterator);
end;
end
else
begin
if evilCount < 30 then
begin
write(number:20);
inc(evilCount);
end;
end;
if evilCount + odiousIterator > 60 then
begin
break;
end;
end;
writeLn();
// odious numbers
for number in odiousNumber do
begin
write(number:20);
end;
writeLn();
end. |
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
| #Racket | Racket |
#lang racket
(define (deg p)
(for/fold ([d -inf.0]) ([(pi i) (in-indexed p)])
(if (zero? pi) d i)))
(define (lead p) (vector-ref p (deg p)))
(define (mono c d) (build-vector (+ d 1) (λ(i) (if (= i d) c 0))))
(define (poly*cx^n c n p) (vector-append (make-vector n 0) (for/vector ([pi p]) (* c pi))))
(define (poly+ p q) (poly/lin 1 p 1 q))
(define (poly- p q) (poly/lin 1 p -1 q))
(define (poly/lin a p b q)
(cond [(< (deg p) 0) q]
[(< (deg q) 0) p]
[(< (deg p) (deg q)) (poly/lin b q a p)]
[else (define ap+bq (for/vector #:length (+ (deg p) 1) #:fill 0
([pi p] [qi q]) (+ (* a pi) (* b qi))))
(for ([i (in-range (+ (deg q) 1) (+ (deg p) 1))])
(vector-set! ap+bq i (* a (vector-ref p i))))
ap+bq]))
(define (poly/ n d)
(define N (deg n))
(define D (deg d))
(cond
[(< N 0) (error 'poly/ "can't divide by zero")]
[(< N D) (values 0 n)]
[else (define c (/ (lead n) (lead d)))
(define q (mono c (- N D)))
(define r (poly- n (poly*cx^n c (- N D) d)))
(define-values (q1 r1) (poly/ r d))
(values (poly+ q q1) r1)]))
; Example:
(poly/ #(-42 0 -12 1) #(-3 1))
; Output:
'#(-27 -9 1)
'#(-123 0)
|
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.
| #Perl | Perl | use strict;
use warnings;
use Statistics::Regression;
my @x = <0 1 2 3 4 5 6 7 8 9 10>;
my @y = <1 6 17 34 57 86 121 162 209 262 321>;
my @model = ('const', 'X', 'X**2');
my $reg = Statistics::Regression->new( '', [@model] );
$reg->include( $y[$_], [ 1.0, $x[$_], $x[$_]**2 ]) for 0..@y-1;
my @coeff = $reg->theta();
printf "%-6s %8.3f\n", $model[$_], $coeff[$_] for 0..@model-1; |
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.
| #Icon_and_Unicon | Icon and Unicon |
procedure power_set (s)
result := set ()
if *s = 0
then insert (result, set ()) # empty set
else {
head := set(?s) # take a random element
# and find powerset of remaining part of set
tail_pset := power_set (x -- head)
result ++:= tail_pset # add powerset of remainder to results
every ps := !tail_pset do # and add head to each powerset from the remainder
insert (result, ps ++ head)
}
return result
end
|
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
| #E | E | def isPrime(n :int) {
if (n == 2) {
return true
} else if (n <= 1 || n %% 2 == 0) {
return false
} else {
def limit := (n :float64).sqrt().ceil()
var divisor := 1
while ((divisor += 2) <= limit) {
if (n %% divisor == 0) {
return false
}
}
return 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
| #Lua | Lua | scaleTable = {
{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 rescale (price)
if price < 0 or price > 1 then return "Out of range!" end
for k, v in pairs(scaleTable) do
if price < v[1] then return v[2] end
end
end
math.randomseed(os.time())
for i = 1, 5 do
rnd = math.random()
print("Random value:", rnd)
print("Adjusted price:", rescale(rnd))
print()
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
| #PHP | PHP | <?php
function ProperDivisors($n) {
yield 1;
$large_divisors = [];
for ($i = 2; $i <= sqrt($n); $i++) {
if ($n % $i == 0) {
yield $i;
if ($i*$i != $n) {
$large_divisors[] = $n / $i;
}
}
}
foreach (array_reverse($large_divisors) as $i) {
yield $i;
}
}
assert([1, 2, 4, 5, 10, 20, 25, 50] ==
iterator_to_array(ProperDivisors(100)));
foreach (range(1, 10) as $n) {
echo "$n =>";
foreach (ProperDivisors($n) as $divisor) {
echo " $divisor";
}
echo "\n";
}
$divisorsCount = [];
for ($i = 1; $i < 20000; $i++) {
$divisorsCount[sizeof(iterator_to_array(ProperDivisors($i)))][] = $i;
}
ksort($divisorsCount);
echo "Numbers with most divisors: ", implode(", ", end($divisorsCount)), ".\n";
echo "They have ", key($divisorsCount), " divisors.\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)
| #XPL0 | XPL0 | include c:\cxpl\codes;
def Size = 10_000_000;
int Tbl(12+1);
int I, J, N;
real X, S0, S1;
[for J:= 5 to 12 do Tbl(J):= 0;
for I:= 0 to 1_000_000-1 do \generate one million items
[N:= Ran(Size);
for J:= 5 to 11 do
[N:= N - Size/J;
if N < 0 then [Tbl(J):= Tbl(J)+1; J:= 100];
];
if J=12 then Tbl(12):= Tbl(12)+1;
];
S0:= 0.0; S1:= 0.0;
for J:= 5 to 11 do
[X:= 1.0/float(J); RlOut(0, X); S0:= S0+X;
X:= float(Tbl(J)) / 1_000_000.0; RlOut(0, X); S1:= S1+X;
CrLf(0);
];
X:= 1759.0 / 27720.0; RlOut(0, X); S0:= S0+X;
X:= float(Tbl(12)) / 1_000_000.0; RlOut(0, X); S1:= S1+X;
CrLf(0);
Text(0, " ------- -------
");
RlOut(0, S0); RlOut(0, S1);
] |
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)
| #Yabasic | Yabasic | dim letters$(7)
data "aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"
letters$(0) = "aleph"
letters$(1) = "beth"
letters$(2) = "gimel"
letters$(3) = "daleth"
letters$(4) = "he"
letters$(5) = "waw"
letters$(6) = "zayin"
letters$(7) = "heth"
dim actual(7)
dim probs(7)
probs(0) = 1/5.0
probs(1) = 1/6.0
probs(2) = 1/7.0
probs(3) = 1/8.0
probs(4) = 1/9.0
probs(5) = 1/10.0
probs(6) = 1/11.0
probs(7) = 1759/27720
dim cumProbs(7)
cumProbs(0) = probs(0)
for i = 1 to 6
cumProbs(i) = cumProbs(i - 1) + probs(i)
next i
cumProbs(7) = 1.0
n = 1000000
for test = 1 to n
r = ran(1)
p = 0.0
for i = 1 to arraysize(probs(),1)
p = p + probs(i)
if r < p then
actual(i) = actual(i) + 1
break
end if
next i
next t
sumActual = 0.0
tab$ = chr$(9)
print "Letter Actual Expected"
print "------ -------- --------"
for i = 0 to 7
print letters$(i), tab$,
print actual(i)/n using "#.######",
sumActual = sumActual + actual(i)/n
print probs(i) using "#.######"
next i
print " -------- --------"
print " ", sumActual using "#.######", tab$, "1.000000"
end |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| #Python | Python | >>> import queue
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
pq.put(item)
>>> while not pq.empty():
print(pq.get_nowait())
(1, 'Solve RC tasks')
(2, 'Tax return')
(3, 'Clear drains')
(4, 'Feed cat')
(5, 'Make tea')
>>> |
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
| #J | J | q: |
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.
| #Nim | Nim | import gnuplot
let
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]
plot(x, y, "Coordinate pairs")
discard stdin.readChar # Needed as when the program exits, “gnuplot” is closed. |
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.
| #OCaml | OCaml | #load "graphics.cma"
open Graphics
let round x = int_of_float (floor(x +. 0.5))
let x = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]
and y = [2.7; 2.8; 31.4; 38.1; 58.0; 76.2; 100.5; 130.0; 149.3; 180.0]
let () =
open_graph "";
List.iter2
(fun x y ->
(* scale to fit in the window *)
let _x = x * 30
and _y = round(y *. 2.0) in
plot _x _y)
x y;
ignore(wait_next_event [Key_pressed]);
close_graph();
;; |
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
| #Lua | Lua | -- Point
local Point = {x = 0, y = 0}
function Point:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Point:print()
print("Point(" .. self.x .. ", " .. self.y .. ")")
end
function Point:copy()
return Point:new{x = self.x, y = self.y}
end
-- Circle
local Circle = Point:new()
Circle.r = 0
function Circle:print()
print("Circle(" .. self.x .. ", " .. self.y .. ", " .. self.r .. ")")
end
function Circle:copy()
return Circle:new{x = self.x, y = self.y, r = self.r}
end |
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
| #Ruby | Ruby | class Card
include Comparable
attr_accessor :ordinal
attr_reader :suit, :face
SUITS = %i(♥ ♦ ♣ ♠)
FACES = %i(2 3 4 5 6 7 8 9 10 j q k a)
def initialize(str)
@face, @suit = parse(str)
@ordinal = FACES.index(@face)
end
def <=> (other) #used for sorting
self.ordinal <=> other.ordinal
end
def to_s
"#@face#@suit"
end
private
def parse(str)
face, suit = str.chop.to_sym, str[-1].to_sym
raise ArgumentError, "invalid card: #{str}" unless FACES.include?(face) && SUITS.include?(suit)
[face, suit]
end
end
class Hand
include Comparable
attr_reader :cards, :rank
RANKS = %i(high-card one-pair two-pair three-of-a-kind straight flush
full-house four-of-a-kind straight-flush five-of-a-kind)
WHEEL_FACES = %i(2 3 4 5 a)
def initialize(str_of_cards)
@cards = str_of_cards.downcase.tr(',',' ').split.map{|str| Card.new(str)}
grouped = @cards.group_by(&:face).values
@face_pattern = grouped.map(&:size).sort
@rank = categorize
@rank_num = RANKS.index(@rank)
@tiebreaker = grouped.map{|ar| [ar.size, ar.first.ordinal]}.sort.reverse
end
def <=> (other) # used for sorting and comparing
self.compare_value <=> other.compare_value
end
def to_s
@cards.map(&:to_s).join(" ")
end
protected # accessible for Hands
def compare_value
[@rank_num, @tiebreaker]
end
private
def one_suit?
@cards.map(&:suit).uniq.size == 1
end
def consecutive?
sort.each_cons(2).all? {|c1,c2| c2.ordinal - c1.ordinal == 1 }
end
def sort
if @cards.sort.map(&:face) == WHEEL_FACES
@cards.detect {|c| c.face == :a}.ordinal = -1
end
@cards.sort
end
def categorize
if consecutive?
one_suit? ? :'straight-flush' : :straight
elsif one_suit?
:flush
else
case @face_pattern
when [1,1,1,1,1] then :'high-card'
when [1,1,1,2] then :'one-pair'
when [1,2,2] then :'two-pair'
when [1,1,3] then :'three-of-a-kind'
when [2,3] then :'full-house'
when [1,4] then :'four-of-a-kind'
when [5] then :'five-of-a-kind'
end
end
end
end
# Demo
test_hands = <<EOS
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♦
EOS
hands = test_hands.each_line.map{|line| Hand.new(line) }
puts "High to low"
hands.sort.reverse.each{|hand| puts "#{hand}\t #{hand.rank}" }
puts
str = <<EOS
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♦
EOS
# Neither the Card nor the Hand class supports jokers
# but since hands are comparable, they are also sortable.
# Try every card from a deck for a joker and pick the largest hand:
DECK = Card::FACES.product(Card::SUITS).map(&:join)
str.each_line do |line|
cards_in_arrays = line.split.map{|c| c == "joker" ? DECK.dup : [c]} #joker is array of all cards
all_tries = cards_in_arrays.shift.product(*cards_in_arrays).map{|ar| Hand.new(ar.join" ")} #calculate the Whatshisname product
best = all_tries.max
puts "#{line.strip}: #{best.rank}"
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
#define NTERMS 30
function popcount( n as ulongint ) as uinteger
if n = 0 then return 0
if n = 1 then return 1
if n mod 2 = 0 then return popcount(n/2)
return 1 + popcount( (n - 1)/2 )
end function
dim as ulongint i=0, tp(0 to NTERMS-1), evil(0 to NTERMS-1),_
odious(0 to NTERMS-1), k, ne=0, no=0
while ne < NTERMS or no < NTERMS
if i<NTERMS then tp(i) = popcount(3^i)
k = popcount(i)
if k mod 2 = 0 and ne < NTERMS then
evil(ne) = i
ne += 1
endif
if k mod 2 = 1 and no < NTERMS then
odious(no) = i
no += 1
end if
i += 1
wend
dim as string s_tp = "", s_evil = "", s_odious = ""
for i = 0 to NTERMS-1
s_tp += str(tp(i))+" "
s_evil += str(evil(i))+" "
s_odious += str(odious(i))+" "
next i
print s_tp
print s_evil
print s_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
| #Raku | Raku | sub poly_long_div ( @n is copy, @d ) {
return [0], |@n if +@n < +@d;
my @q = gather while +@n >= +@d {
@n = @n Z- flat ( ( @d X* take ( @n[0] / @d[0] ) ), 0 xx * );
@n.shift;
}
return @q, @n;
}
sub xP ( $power ) { $power>1 ?? "x^$power" !! $power==1 ?? 'x' !! '' }
sub poly_print ( @c ) { join ' + ', @c.kv.map: { $^v ~ xP( @c.end - $^k ) } }
my @polys = [ [ 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 ] ];
say '<math>\begin{array}{rr}';
for @polys -> [ @a, @b ] {
printf Q"%s , & %s \\\\\n", poly_long_div( @a, @b ).map: { poly_print($_) };
}
say '\end{array}</math>'; |
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.
| #Phix | Phix | -- demo\rosetta\Polynomial_regression.exw
with javascript_semantics
constant x = {0,1,2,3,4,5,6,7,8,9,10},
y = {1,6,17,34,57,86,121,162,209,262,321},
n = length(x)
function regression()
atom xm = 0, ym = 0, x2m = 0, x3m = 0, x4m = 0, xym = 0, x2ym = 0
for i=1 to n do
atom xi = x[i],
yi = y[i]
xm += xi
ym += yi
x2m += power(xi,2)
x3m += power(xi,3)
x4m += power(xi,4)
xym += xi*yi
x2ym += power(xi,2)*yi
end for
xm /= n
ym /= n
x2m /= n
x3m /= n
x4m /= n
xym /= n
x2ym /= n
atom Sxx = x2m-power(xm,2),
Sxy = xym-xm*ym,
Sxx2 = x3m-xm*x2m,
Sx2x2 = x4m-power(x2m,2),
Sx2y = x2ym-x2m*ym,
B = (Sxy*Sx2x2-Sx2y*Sxx2)/(Sxx*Sx2x2-power(Sxx2,2)),
C = (Sx2y*Sxx-Sxy*Sxx2)/(Sxx*Sx2x2-power(Sxx2,2)),
A = ym-B*xm-C*x2m
return {C,B,A}
end function
atom {a,b,c} = regression()
function f(atom x)
return a*x*x+b*x+c
end function
printf(1,"y=%gx^2+%gx+%g\n",{a,b,c})
printf(1,"\n x y f(x)\n")
for i=1 to n do
printf(1," %2d %3d %3g\n",{x[i],y[i],f(x[i])})
end for
-- And a simple plot (re-using x,y from above)
include pGUI.e
include IupGraph.e
function get_data(Ihandle graph)
integer {w,h} = IupGetIntInt(graph,"DRAWSIZE")
IupSetInt(graph,"YTICK",iff(h<240?iff(h<150?80:40):20))
return {{x,y,CD_RED}}
end function
IupOpen()
Ihandle graph = IupGraph(get_data,"RASTERSIZE=640x440")
IupSetAttributes(graph,"XTICK=1,XMIN=0,XMAX=10")
IupSetAttributes(graph,"YTICK=20,YMIN=0,YMAX=320")
Ihandle dlg = IupDialog(graph,`TITLE="simple plot"`)
IupSetAttributes(dlg,"MINSIZE=245x150")
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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.
| #J | J | ps =: #~ 2 #:@i.@^ # |
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
| #EchoLisp | EchoLisp | (lib 'sequences)
;; Try divisors iff n = 2k + 1
(define (is-prime? p)
(cond
[(< p 2) #f]
[(zero? (modulo p 2)) (= p 2)]
[else
(for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))
(filter is-prime? (range 1 100))
→ (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)
;; Improve performance , try divisors iff n = 6k+1 or n = 6k+5
(define (is-prime? p)
(cond
[(< p 2) #f]
[(zero? (modulo p 2)) (= p 2)]
[(zero? (modulo p 3)) (= p 3)]
[(zero? (modulo p 5)) (= p 5)]
[else ;; step 6 : try divisors 6n+1 or 6n+5
(for ((d [7 13 .. (1+ (sqrt p))] ))
#:break (zero? (modulo p d)) => #f
#:break (zero? (modulo p (+ d 4))) => #f
#t )]))
(filter is-prime? (range 1 100))
→ (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97) |
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
| #Maple | Maple | priceFraction := proc(price)
local values, standard, newPrice, i;
values := [0, 0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61,
0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01];
standard := [0.10, 0.18, 0.26, 0.32, 0.38, 0.44, 0.50, 0.54, 0.58, 0.62, 0.66, 0.70,
0.74, 0.78, 0.82, 0.86, 0.90, 0.94, 0.98, 1.00];
for i to numelems(standard) do
if price >= values[i] and price < values[i+1] then
newPrice := standard[i];
end if;
end do;
printf("%f --> %.2f\n", price, newPrice);
end proc:
randomize():
for i to 5 do
priceFraction (rand(0.0..1.0)());
end do; |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | PriceFraction[x_]:=Piecewise[{{.1, 0 <= x < 0.06}, {.18, x < .11}, {.26,x < 0.16},
{.32, x < .21}, {.38, x < .26}, {.44, x < 0.31}, {.5, x < .36},
{.54, x < .41}, {.58, x < .46}, {.62, x < .51}, {.66, x < .56},
{.70, x < .61}, {.74, x < .66}, {.78, x < .71}, {.82, x < .76},
{.86, x < .81}, {.90, x < .86}, {.94, x < .91}, {.98, x < .96}}, 1] |
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
| #Picat | Picat | go =>
println(11111=proper_divisors(11111)),
nl,
foreach(N in 1..10)
println(N=proper_divisors(N))
end,
nl,
find_most_divisors(20_000),
nl.
% Proper divisors of number N
proper_divisors(N) = Divisors =>
Div1 = [ I : I in 1..ceiling(sqrt(N)), N mod I == 0],
Divisors = (Div1 ++ [N div I : I in Div1]).sort_remove_dups().delete(N).
% Find the number(s) with the most proper divisors below Limit
find_most_divisors(Limit) =>
MaxN = [],
MaxNumDivisors = [],
MaxLen = 1,
foreach(N in 1..Limit, not prime(N))
D = proper_divisors(N),
Len = D.len,
% Get all numbers with most proper divisors
if Len = MaxLen then
MaxN := MaxN ++ [N],
MaxNumDivisors := MaxNumDivisors ++ [[N=D]]
elseif Len > MaxLen then
MaxLen := Len,
MaxN := [N],
MaxNumDivisors := [N=D]
end
end,
println(maxN=MaxN),
println(maxLen=MaxLen),
nl. |
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)
| #zkl | zkl | var names=T("aleph", "beth", "gimel", "daleth",
"he", "waw", "zayin", "heth");
var ptable=T(5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0).apply('/.fp(1.0));
ptable=ptable.append(1.0-ptable.sum(0.0)); // add last weight to sum to 1.0
var [const] N=ptable.len();
fcn ridx{ i:=0; s:=(0.0).random(1);
while((s-=ptable[i]) > 0) { i+=1 }
i
}
const M=0d1_000_000;
var r=(0).pump(N,List,T(Ref,0)); // list of references to int 0
(0).pump(M,Void,fcn{r[ridx()].inc()}); // 1,000,000 weighted random #s
r=r.apply("value").apply("toFloat"); // (reference to int)-->int-->float
println(" Name Count Ratio Expected");
foreach i in (N){
"%6s%7d %7.4f%% %7.4f%%".fmt(names[i], r[i], r[i]/M*100,
ptable[i]*100).println();
} |
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.
| #Quackery | Quackery | ( ***** priotity queue ***** )
[ stack ] is heap.pq ( --> s )
[ stack ] is comp.pq ( --> s )
[ unpack
comp.pq put heap.pq put ] is pq->stacks ( p --> )
[ heap.pq take comp.pq take
2 pack ] is stacks->pq ( --> p )
[ heap.pq share swap peek ] is heapeek ( n --> x )
[ heap.pq take
swap poke heap.pq put ] is heapoke ( n x --> )
[ 1 - 1 >> ] is parent ( n --> n )
[ 0 > ] is has-parent ( n --> b )
[ 1 << 1+ ] is child ( n --> n )
[ child heap.pq share size < ] is has-child ( n --> b )
[ 1+ ] is sibling ( n --> n )
[ sibling
heap.pq share size < ] is has-sibling ( n --> b )
[ comp.pq share do ] is compare ( x x --> b )
[ 0 peek size ] is pqsize ( p --> n )
[ swap pq->stacks
heap.pq take tuck size
rot 0 join heap.pq put
[ dup has-parent while
dup parent
rot over heapeek
2dup compare iff
[ 2swap unrot heapoke ]
again
rot 2drop swap ]
heapoke
stacks->pq ] is topq ( p x --> p )
[ dup heapeek swap
[ dup has-child while
dup child
dup has-sibling if
[ dup sibling heapeek
over heapeek
compare if sibling ]
dip over dup heapeek
rot dip dup compare iff
[ rot heapoke ] again
2drop ]
heapoke ] is heapify.pq ( n --> )
[ dup pqsize 0 = if
[ $ "Unexpectedly empty priority queue."
fail ]
pq->stacks heap.pq share
behead
over [] = iff
[ swap heap.pq replace ]
else
[ swap -1 split
swap join heap.pq put
0 heapify.pq ]
stacks->pq swap ] is frompq ( p --> p x )
[ ]'[ 2 pack pq->stacks
heap.pq share
size 1 >> times
[ i heapify.pq ]
stacks->pq ] is pqwith ( [ --> p )
( ***** task ***** )
[ 2 pack topq ] is insert ( p n $ --> p )
[ frompq unpack ] is dequeue ( p --> p n $ )
[] pqwith [ 0 peek dip [ 0 peek ] < ]
3 $ "Clear drains" insert
4 $ "Feed cat" insert
5 $ "Make tea" insert
1 $ "Solve RC tasks" insert
2 $ "Tax return" insert
5 times
[ dequeue
swap echo say ": "
echo$ cr ]
drop |
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
| #Java | Java | public boolean prime(BigInteger i); |
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.
| #Octave | Octave | 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];
plot(x,y,"o");
pause; |
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
| #M2000_Interpreter | M2000 Interpreter |
\\ block For This {}, or For object [, object2] { }, where object is a group, or a pointer to group, or an item from an array contains a group
\\ This is "this context".
For This {
\\ any new definition here has a temporary use
\\ can be nested, but if we use object then we can use dots to access members of it. If we use a second one then we have to use double dots (..x for second object, for access to x member)
}
|
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
-- -----------------------------------------------------------------------------
class RCPolymorphism public final
method main(args = String[]) public constant
parry = [Point -
Point() -
, Point(1.0) -
, Point(1.0, 2.0) -
, Point(Point(0.3, 0.2)) -
, Circle() -
, Circle(2.0, 2.0) -
, Circle(5.0, 6.0, 7.0) -
, Circle(Point(8.0, 9.0)) -
, Circle(Point(8.0, 9.0), 4.0) -
, Circle(Circle(1.5, 1.4, 1.3)) -
]
loop pp = 0 to parry.length - 1
parry[pp].print
end pp
return
-- -----------------------------------------------------------------------------
class RCPolymorphism.Point public binary
properties private
x = double
y = double
className = Point.class.getSimpleName
method Point(x_ = double 0.0, y_ = double 0.0)
setX(x_)
setY(y_)
return
method Point(p = Point)
this(p.getX, p.getY)
return
method display public returns String
hx = '@'Rexx(Integer.toHexString(hashCode())).right(8, 0)
str = Rexx(className).left(10)':'hx': (x,y) = (' || -
Rexx(getX()).format(null, 3)',' -
Rexx(getY()).format(null, 3)')'
return str
method getX public returns double
return x
method getY public returns double
return y
method setX(x_ = double 0.0) inheritable
x = x_
return
method setY(y_ = double 0.0) inheritable
y = y_
return
method print inheritable
say display
return
-- -----------------------------------------------------------------------------
class RCPolymorphism.Circle public extends RCPolymorphism.Point binary
properties private
r = double
className = Circle.class.getSimpleName
method Circle(x_ = double 0.0, y_ = double 0.0, r_ = double 0.0)
super(x_, y_)
setR(r_)
return
method Circle(p_ = RCPolymorphism.Point, r_ = double 0.0)
this(p_.getX, p_.getY, r_)
return
method Circle(c_ = Circle)
this(c_.getX, c_.getY, c_.getR)
return
method getR public returns double
return r
method setR(r_ = double 0.0) inheritable
r = r_
return
method display public returns String
hx = '@'Rexx(Integer.toHexString(hashCode())).right(8, 0)
str = Rexx(className).left(10)':'hx': (x,y,r) = (' || -
Rexx(getX()).format(null, 3)',' -
Rexx(getY()).format(null, 3)',' -
Rexx(getR()).format(null, 3)')'
return str
|
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
| #Rust | Rust |
fn main() {
let hands = vec![
"🂡 🂮 🂭 🂫 🂪",
"🃏 🃂 🂢 🂮 🃍",
"🃏 🂵 🃇 🂨 🃉",
"🃏 🃂 🂣 🂤 🂥",
"🃏 🂳 🃂 🂣 🃃",
"🃏 🂷 🃂 🂣 🃃",
"🃏 🂷 🃇 🂧 🃗",
"🃏 🂻 🂽 🂾 🂱",
"🃏 🃔 🃞 🃅 🂪",
"🃏 🃞 🃗 🃖 🃔",
"🃏 🃂 🃟 🂤 🂥",
"🃏 🃍 🃟 🂡 🂪",
"🃏 🃍 🃟 🃁 🃊",
"🃏 🃂 🂢 🃟 🃍",
"🃏 🃂 🂢 🃍 🃍",
"🃂 🃞 🃍 🃁 🃊",
];
for hand in hands{
println!("{} {}", hand, poker_hand(hand));
}
}
fn poker_hand(cards: &str) -> &str {
let mut suits = vec![0u8; 4];
let mut faces = vec![0u8; 15];
let mut hand = vec![];
for card in cards.chars(){
if card == ' ' { continue; }
let values = get_card_value(card);
if values.0 < 14 && hand.contains(&values) {
return "invalid";
}
hand.push(values);
faces[values.0 as usize]+=1;
if values.1 >= 0 {
suits[values.1 as usize]+=1;
}
}
if hand.len()!=5 {
return "invalid";
}
faces[13] = faces[0]; //add ace-high count
let jokers = faces[14];
//count suits
let mut colors = suits.into_iter()
.filter(|&x| x > 0).collect::<Vec<_>>();
colors.sort_unstable();
colors[0] += jokers; // add joker suits to the highest one;
let is_flush = colors[0] == 5;
//straight
let mut is_straight = false;
//pointer to optimise some work
//avoids looking again at cards that were the start of a sequence
//as they cannot be part of another sequence
let mut ptr = 14;
while ptr>3{
let mut jokers_left = jokers;
let mut straight_cards = 0;
for i in (0..ptr).rev(){
if faces[i]==0 {
if jokers_left == 0 {break;}
jokers_left -= 1;
}
else if i==ptr-1 { ptr-=1; }
straight_cards+=1;
}
ptr-=1;
if straight_cards == 5 {
is_straight = true;
break;
}
}
//count values
let mut values = faces.into_iter().enumerate().take(14).filter(|&x| x.1>0).collect::<Vec<_>>();
//sort by quantity, then by value, high to low
values.sort_unstable_by(|a, b| if b.1 == a.1 { (b.0).cmp(&a.0) } else { (b.1).cmp(&a.1)} );
let first_group = values[0].1 + jokers;
let second_group = if values.len()>1 {values[1].1} else {0};
match (is_flush, is_straight, first_group, second_group){
(_,_,5,_) => "five-of-a-kind",
(true, true, _, _) => if ptr == 8 {"royal-flush"} else {"straight-flush"},
(_,_,4,_) => "four-of-a-kind",
(_,_,3,2) => "full-house",
(true,_,_,_) => "flush",
(_,true,_,_) => "straight",
(_,_,3,_) => "three-of-a-kind",
(_,_,2,2) => "two-pair",
(_,_,2,_) => "one-pair",
_ => "high-card"
}
}
fn get_card_value(card: char) -> (i8,i8) {
// transform glyph to face + suit, zero-indexed
let base = card as u32 - 0x1F0A1;
let mut suit = (base / 16) as i8;
let mut face = (base % 16) as i8;
if face > 11 && face < 14 { face-=1; } // Unicode has a Knight that we do not want
if face == 14 { suit = -1; } //jokers do not have a suit
(face, suit)
}
|
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.
| #FreeBASIC | FreeBASIC |
#define NTERMS 30
function popcount( n as ulongint ) as uinteger
if n = 0 then return 0
if n = 1 then return 1
if n mod 2 = 0 then return popcount(n/2)
return 1 + popcount( (n - 1)/2 )
end function
dim as ulongint i=0, tp(0 to NTERMS-1), evil(0 to NTERMS-1),_
odious(0 to NTERMS-1), k, ne=0, no=0
while ne < NTERMS or no < NTERMS
if i<NTERMS then tp(i) = popcount(3^i)
k = popcount(i)
if k mod 2 = 0 and ne < NTERMS then
evil(ne) = i
ne += 1
endif
if k mod 2 = 1 and no < NTERMS then
odious(no) = i
no += 1
end if
i += 1
wend
dim as string s_tp = "", s_evil = "", s_odious = ""
for i = 0 to NTERMS-1
s_tp += str(tp(i))+" "
s_evil += str(evil(i))+" "
s_odious += str(odious(i))+" "
next i
print s_tp
print s_evil
print s_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
| #REXX | REXX | /* REXX needed by some... */
z='1 -12 0 -42' /* Numerator */
n='1 -3' /* Denominator */
zx=z
nx=n copies('0 ',words(z)-words(n))
qx='' /* Quotient */
Do Until words(zx)<words(n)
Parse Value div(zx,nx) With q zx
qx=qx q
nx=subword(nx,1,words(nx)-1)
End
Say '('show(z)')/('show(n)')=('show(qx)')'
Say 'Remainder:' show(zx)
Exit
div: Procedure
Parse Arg z,n
q=word(z,1)/word(n,1)
zz=''
Do i=1 To words(z)
zz=zz word(z,i)-q*word(n,i)
End
Return q subword(zz,2)
show: Procedure
Parse Arg poly
d=words(poly)-1
res=''
Do i=1 To words(poly)
Select
When d>1 Then fact='*x**'d
When d=1 Then fact='*x'
Otherwise fact=''
End
Select
When word(poly,i)=0 Then p=''
When word(poly,i)=1 Then p='+'substr(fact,2)
When word(poly,i)=-1 Then p='-'substr(fact,2)
When word(poly,i)<0 Then p=word(poly,i)||fact
Otherwise p='+'word(poly,i)||fact
End
res=res p
d=d-1
End
Return strip(space(res,0),'L','+') |
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.
| #PowerShell | PowerShell |
function qr([double[][]]$A) {
$m,$n = $A.count, $A[0].count
$pm,$pn = ($m-1), ($n-1)
[double[][]]$Q = 0..($m-1) | foreach{$row = @(0) * $m; $row[$_] = 1; ,$row}
[double[][]]$R = $A | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}
foreach ($h in 0..$pn) {
[double[]]$u = $R[$h..$pm] | foreach{$_[$h]}
[double]$nu = $u | foreach {[double]$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)}
$u[0] -= if ($u[0] -lt 1) {$nu} else {-$nu}
[double]$nu = $u | foreach {$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)}
[double[]]$u = $u | foreach { $_/$nu}
[double[][]]$v = 0..($u.Count - 1) | foreach{$i = $_; ,($u | foreach{2*$u[$i]*$_})}
[double[][]]$CR = $R | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}
[double[][]]$CQ = $Q | foreach{$row = $_; ,@(0..$pm | foreach{$row[$_]})}
foreach ($i in $h..$pm) {
foreach ($j in $h..$pn) {
$R[$i][$j] -= $h..$pm | foreach {[double]$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CR[$_][$j]} {$sum}
}
}
if (0 -eq $h) {
foreach ($i in $h..$pm) {
foreach ($j in $h..$pm) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i][$_]*$CQ[$_][$j]} {$sum}
}
}
} else {
$p = $h-1
foreach ($i in $h..$pm) {
foreach ($j in 0..$p) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}
}
foreach ($j in $h..$pm) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}
}
}
}
}
foreach ($i in 0..$pm) {
foreach ($j in $i..$pm) {$Q[$i][$j],$Q[$j][$i] = $Q[$j][$i],$Q[$i][$j]}
}
[PSCustomObject]@{"Q" = $Q; "R" = $R}
}
function leastsquares([Double[][]]$A,[Double[]]$y) {
$QR = qr $A
[Double[][]]$Q = $QR.Q
[Double[][]]$R = $QR.R
$m,$n = $A.count, $A[0].count
[Double[]]$z = foreach ($j in 0..($m-1)) {
0..($m-1) | foreach {$sum = 0} {$sum += $Q[$_][$j]*$y[$_]} {$sum}
}
[Double[]]$x = @(0)*$n
for ($i = $n-1; $i -ge 0; $i--) {
for ($j = $i+1; $j -lt $n; $j++) {
$z[$i] -= $x[$j]*$R[$i][$j]
}
$x[$i] = $z[$i]/$R[$i][$i]
}
$x
}
function polyfit([Double[]]$x,[Double[]]$y,$n) {
$m = $x.Count
[Double[][]]$A = 0..($m-1) | foreach{$row = @(1) * ($n+1); ,$row}
for ($i = 0; $i -lt $m; $i++) {
for ($j = $n-1; 0 -le $j; $j--) {
$A[$i][$j] = $A[$i][$j+1]*$x[$i]
}
}
leastsquares $A $y
}
function show($m) {$m | foreach {write-host "$_"}}
$A = @(@(12,-51,4), @(6,167,-68), @(-4,24,-41))
$x = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
$y = @(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
"polyfit "
"X^2 X constant"
"$(polyfit $x $y 2)"
|
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.
| #Java | Java | public static ArrayList<String> getpowerset(int a[],int n,ArrayList<String> ps)
{
if(n<0)
{
return null;
}
if(n==0)
{
if(ps==null)
ps=new ArrayList<String>();
ps.add(" ");
return ps;
}
ps=getpowerset(a, n-1, ps);
ArrayList<String> tmp=new ArrayList<String>();
for(String s:ps)
{
if(s.equals(" "))
tmp.add(""+a[n-1]);
else
tmp.add(s+a[n-1]);
}
ps.addAll(tmp);
return ps;
} |
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
| #Eiffel | Eiffel | class
APPLICATION
create
make
feature
make
-- Tests the feature is_prime.
do
io.put_boolean (is_prime (1))
io.new_line
io.put_boolean (is_prime (2))
io.new_line
io.put_boolean (is_prime (3))
io.new_line
io.put_boolean (is_prime (4))
io.new_line
io.put_boolean (is_prime (97))
io.new_line
io.put_boolean (is_prime (15589))
io.new_line
end
is_prime (n: INTEGER): BOOLEAN
-- Is 'n' a prime number?
require
positiv_input: n > 0
local
i: INTEGER
max: REAL_64
math: DOUBLE_MATH
do
create math
if n = 2 then
Result := True
elseif n <= 1 or n \\ 2 = 0 then
Result := False
else
Result := True
max := math.sqrt (n)
from
i := 3
until
i > max
loop
if n \\ i = 0 then
Result := False
end
i := i + 2
end
end
end
end |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #MATLAB_.2F_Octave | MATLAB / Octave | function y = rescale(x)
L = [0,.06:.05:1.02];
V = [.1,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.9,.94,.98,1];
y = x;
for k=1:numel(x);
y(k) = V(sum(L<=x(k)));
end;
end;
t=0:0.001:1;
plot(t,rescale(t)); |
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
| #Mercury | Mercury | :- module price.
:- interface.
:- import_module int.
:- type price == int.
:- func standard(price) = price.
:- implementation.
:- import_module require, list.
standard(P) = SP :-
require(P >= 0, "P must be positive"),
Cents = P `mod` 100,
P + adjust(Cents) = SP.
:- func adjust(int) = int.
adjust(Cents) = adjust(Cents, rules).
:- func adjust(int, list(price_rule)) = int.
adjust(_, []) = unexpected("price", "adjust/2", "exhausted rules").
adjust(N, [rule(Low, High, To)|T]) = R :-
( N >= Low, N < High -> To - N = R ; adjust(N, T) = R ).
:- type price_rule ---> rule(int, int, int).
:- func rules = list(price_rule).
rules = [rule(00, 06, 10),
rule(06, 11, 18),
rule(11, 16, 26),
rule(16, 21, 32),
rule(21, 26, 38),
rule(26, 31, 44),
rule(31, 36, 50),
rule(36, 41, 54),
rule(41, 46, 58),
rule(46, 51, 62),
rule(51, 56, 66),
rule(56, 61, 70),
rule(61, 66, 74),
rule(66, 71, 78),
rule(71, 76, 82),
rule(76, 81, 86),
rule(81, 86, 90),
rule(86, 91, 94),
rule(91, 96, 98),
rule(96, 101, 100)]. |
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
| #PicoLisp | PicoLisp | # Generate all proper divisors.
(de propdiv (N)
(head -1 (filter
'((X) (=0 (% N X)))
(range 1 N) )) )
# Obtaining the values from 1 to 10 inclusive.
(mapcar propdiv (range 1 10))
# Output:
# (NIL (1) (1) (1 2) (1) (1 2 3) (1) (1 2 4) (1 3) (1 2 5)) |
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.
| #R | R | PriorityQueue <- function() {
keys <- values <- NULL
insert <- function(key, value) {
ord <- findInterval(key, keys)
keys <<- append(keys, key, ord)
values <<- append(values, value, ord)
}
pop <- function() {
head <- list(key=keys[1],value=values[[1]])
values <<- values[-1]
keys <<- keys[-1]
return(head)
}
empty <- function() length(keys) == 0
environment()
}
pq <- PriorityQueue()
pq$insert(3, "Clear drains")
pq$insert(4, "Feed cat")
pq$insert(5, "Make tea")
pq$insert(1, "Solve RC tasks")
pq$insert(2, "Tax return")
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
} |
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
| #JavaScript | JavaScript | function run_factorize(input, output) {
var n = new BigInteger(input.value, 10);
var TWO = new BigInteger("2", 10);
var divisor = new BigInteger("3", 10);
var prod = false;
if (n.compareTo(TWO) < 0)
return;
output.value = "";
while (true) {
var qr = n.divideAndRemainder(TWO);
if (qr[1].equals(BigInteger.ZERO)) {
if (prod)
output.value += "*";
else
prod = true;
output.value += "2";
n = qr[0];
}
else
break;
}
while (!n.equals(BigInteger.ONE)) {
var qr = n.divideAndRemainder(divisor);
if (qr[1].equals(BigInteger.ZERO)) {
if (prod)
output.value += "*";
else
prod = true;
output.value += divisor;
n = qr[0];
}
else
divisor = divisor.add(TWO);
}
} |
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.
| #Ol | Ol |
; define input arrays
(define x '(0 1 2 3 4 5 6 7 8 9))
(define y '(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0))
; render
(import (lib gl2))
(glOrtho 0 10 0 200 0 1)
(gl:set-renderer (lambda (mouse)
(glClear GL_COLOR_BUFFER_BIT)
(glColor3f 0 1 0)
(glBegin GL_LINE_STRIP)
(map glVertex2f x y)
(glEnd)))
|
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
| #Nim | Nim | type
Point = object
x, y: float
Circle = object
center: Point
radius: float
# Constructors
proc createPoint(x, y = 0.0): Point =
result.x = x
result.y = y
proc createCircle(x, y = 0.0, radius = 1.0): Circle =
result.center.x = x
result.center.y = y
result.radius = radius
var p1 = createPoint()
echo "p1: ", p1 # We use the default $ operator for printing
var p2 = createPoint(3, 4.2)
var p3 = createPoint(x = 2)
var p4 = createPoint(y = 2.5)
p2 = p4
p3 = createPoint()
var c1 = createCircle()
echo "c1: ", c1
var c2 = createCircle(2, 0.5, 4.2)
var c3 = createCircle(x = 2.1, y = 2)
var c4 = createCircle(radius = 10)
c1.center.x = 12
c1.radius = 5.2 |
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
| #Objeck | Objeck |
bundle Default {
class Point {
@x : Int;
@y : Int;
New() {
@x := 0;
@y := 0;
}
New(x : Int, y : Int) {
@x := x;
@y := y;
}
New(p : Point) {
@x := p->GetX();
@y := p->GetY();
}
method : public : GetX() ~ Int {
return @x;
}
method : public : GetY() ~ Int {
return @y;
}
method : public : SetX(x : Int) ~ Nil {
@x := x;
}
method : public : SetY(y : Int) ~ Nil {
@y := y;
}
method : public : Print() ~ Nil {
"Point"->PrintLine();
}
}
class Circle from Point {
@r : Int;
New() {
Parent();
@r := 0;
}
New(p : Point) {
Parent(p);
@r := 0;
}
New(c : Circle) {
Parent(c->GetX(), c->GetY());
@r := c->GetR();
}
method : public : GetR() ~ Int {
return @r;
}
method : public : SetR(r : Int) ~ Nil {
@r := r;
}
method : public : Print() ~ Nil {
"Circle"->PrintLine();
}
}
class Poly {
function : Main(args : String[]) ~ Nil {
p := Point->New();
c := Circle->New();
p->Print();
c->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
| #Scala | Scala | val faces = "23456789TJQKA"
val suits = "CHSD"
sealed trait Card
object Joker extends Card
case class RealCard(face: Int, suit: Char) extends Card
val allRealCards = for {
face <- 0 until faces.size
suit <- suits
} yield RealCard(face, suit)
def parseCard(str: String): Card = {
if (str == "joker") {
Joker
} else {
RealCard(faces.indexOf(str(0)), str(1))
}
}
def parseHand(str: String): List[Card] = {
str.split(" ").map(parseCard).toList
}
trait HandType {
def name: String
def check(hand: List[RealCard]): Boolean
}
case class And(x: HandType, y: HandType, name: String) extends HandType {
def check(hand: List[RealCard]) = x.check(hand) && y.check(hand)
}
object Straight extends HandType {
val name = "straight"
def check(hand: List[RealCard]): Boolean = {
val faces = hand.map(_.face).toSet
faces.size == 5 && (faces.min == faces.max - 4 || faces == Set(0, 1, 2, 3, 12))
}
}
object Flush extends HandType {
val name = "flush"
def check(hand: List[RealCard]): Boolean = {
hand.map(_.suit).toSet.size == 1
}
}
case class NOfAKind(n: Int, name: String = "", nOccur: Int = 1) extends HandType {
def check(hand: List[RealCard]): Boolean = {
hand.groupBy(_.face).values.count(_.size == n) >= nOccur
}
}
val allHandTypes = List(
NOfAKind(5, "five-of-a-kind"),
And(Straight, Flush, "straight-flush"),
NOfAKind(4, "four-of-a-kind"),
And(NOfAKind(3), NOfAKind(2), "full-house"),
Flush,
Straight,
NOfAKind(3, "three-of-a-kind"),
NOfAKind(2, "two-pair", 2),
NOfAKind(2, "one-pair")
)
def possibleRealHands(hand: List[Card]): List[List[RealCard]] = {
val realCards = hand.collect { case r: RealCard => r }
val nJokers = hand.count(_ == Joker)
allRealCards.toList.combinations(nJokers).map(_ ++ realCards).toList
}
def analyzeHand(hand: List[Card]): String = {
val possibleHands = possibleRealHands(hand)
allHandTypes.find(t => possibleHands.exists(t.check)).map(_.name).getOrElse("high-card")
} |
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.
| #Gambas | Gambas | Public Sub Main()
Dim sEvil, sOdious As String 'To store the output for printing Evil and Odious
Dim iCount, iEvil, iOdious As Integer 'Counters
Print "First 30 numbers ^3\t"; 'Print title
For iCount = 0 To 29 'Count 30 times
Print Len(Replace(Bin(3 ^ iCount), "0", ""));; 'Get the Bin of the number, take out the '0's and the remaining
Next 'length is the Population count e.g. 3^2=9, Bin=1001, remove '0's='11', length=2
iCount = 0 'Reset iCount
Repeat 'Repeat/Until loop
If Even(Len(Replace(Bin(iCount), "0", ""))) Then 'If (as above) the result is Even then
sEvil &= Str(icount) & " " 'Add it to sEvil
Inc iEvil 'Increase iEvil
End If
If Odd(Len(Replace(Bin(iCount), "0", ""))) Then 'If (as above) the result is Odd then
sOdious &= Str(icount) & " " 'Add it to sOdious
Inc iOdious 'Increase iOdious
End If
Inc iCount 'Increase iCount
Until iEvil = 30 And iOdious = 30 'Until both iEvil and iOdious = 30 then exit the loop
Print "\n1st 30 Evil numbers =\t" & sEvil 'Print Evil
Print "1st 30 Odious numbers =\t" & sOdious 'Print Odious
End |
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
| #Ruby | Ruby | def polynomial_long_division(numerator, denominator)
dd = degree(denominator)
raise ArgumentError, "denominator is zero" if dd < 0
if dd == 0
return [multiply(numerator, 1.0/denominator[0]), [0]*numerator.length]
end
q = [0] * numerator.length
while (dn = degree(numerator)) >= dd
d = shift_right(denominator, dn - dd)
q[dn-dd] = numerator[dn] / d[degree(d)]
d = multiply(d, q[dn-dd])
numerator = subtract(numerator, d)
end
[q, numerator]
end
def degree(ary)
idx = ary.rindex(&:nonzero?)
idx ? idx : -1
end
def shift_right(ary, n)
[0]*n + ary[0, ary.length - n]
end
def subtract(a1, a2)
a1.zip(a2).collect {|v1,v2| v1 - v2}
end
def multiply(ary, num)
ary.collect {|x| x * num}
end
f = [-42, 0, -12, 1]
g = [-3, 1, 0, 0]
q, r = polynomial_long_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
# => [-42, 0, -12, 1] / [-3, 1, 0, 0] => [-27, -9, 1, 0] remainder [-123, 0, 0, 0]
g = [-3, 1, 1, 0]
q, r = polynomial_long_division(f, g)
puts "#{f} / #{g} => #{q} remainder #{r}"
# => [-42, 0, -12, 1] / [-3, 1, 1, 0] => [-13, 1, 0, 0] remainder [-81, 16, 0, 0] |
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.
| #Python | Python | >>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
>>> coeffs = numpy.polyfit(x,y,deg=2)
>>> coeffs
array([ 3., 2., 1.]) |
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.
| #JavaScript | JavaScript | function powerset(ary) {
var ps = [[]];
for (var i=0; i < ary.length; i++) {
for (var j = 0, len = ps.length; j < len; j++) {
ps.push(ps[j].concat(ary[i]));
}
}
return ps;
}
var res = powerset([1,2,3,4]);
load('json2.js');
print(JSON.stringify(res)); |
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
| #Elixir | Elixir | defmodule RC do
def is_prime(2), do: true
def is_prime(n) when n<2 or rem(n,2)==0, do: false
def is_prime(n), do: is_prime(n,3)
def is_prime(n,k) when n<k*k, do: true
def is_prime(n,k) when rem(n,k)==0, do: false
def is_prime(n,k), do: is_prime(n,k+2)
end
IO.inspect for n <- 1..50, RC.is_prime(n), do: 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
| #MUMPS | MUMPS | PRICFRAC(X)
;Outputs a specified value dependent upon the input value
;The non-inclusive upper limits are encoded in the PFMAX string, and the values
;to convert to are encoded in the PFRES string.
NEW PFMAX,PFRES,I,RESULT
SET PFMAX=".06^.11^.16^.21^.26^.31^.36^.41^.46^.51^.56^.61^.66^.71^.76^.81^.86^.91^.96^1.01"
SET PFRES=".10^.18^.26^.32^.38^.44^.50^.54^.58^.62^.66^.70^.74^.78^.82^.86^.90^.94^.98^1.00"
Q:(X<0)!(X>1.01) ""
FOR I=1:1:$LENGTH(PFMAX,"^") Q:($DATA(RESULT)'=0) SET:X<$P(PFMAX,"^",I) RESULT=$P(PFRES,"^",I)
KILL PFMAX,PFRES,I
QUIT RESULT |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- -----------------------------------------------------------------------------
method runSample(arg) public static
parse arg in_val .
if in_val \= '' then test_vals = [in_val]
else test_vals = getTestData()
say 'Input Adjustment'
loop tv = 0 to test_vals.length - 1
in_val = test_vals[tv]
adjust = priceFraction(in_val)
say in_val.format(null, 2).right(5) adjust.format(null, 2).right(10)
end tv
return
-- -----------------------------------------------------------------------------
method priceFraction(in_val) public static
out_val = -1
limit_table = getLimitTable()
limit_table_K = limit_table.length
loop p1 = 0 to limit_table_K - 1
pair = limit_table[p1]
hi_limit = pair[0]
adjustmt = pair[1]
if in_val < hi_limit then do
out_val = adjustmt
leave p1
end
end p1
if out_val = -1 then signal IllegalArgumentException('Input' in_val 'is outside of acceptable range.')
return out_val
-- -----------------------------------------------------------------------------
method getLimitTable() public static returns Rexx[,]
limit_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] -
]
return limit_table
-- -----------------------------------------------------------------------------
method getTestData() private static returns Rexx[]
test_vals = Rexx[5]
rng = Random(1024)
loop tv = 0 to test_vals.length - 1
test_vals[tv] = rng.nextFloat()
end tv
return test_vals
|
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
| #PL.2FI | PL/I | *process source xref;
(subrg):
cpd: Proc Options(main);
p9a=time();
Dcl (p9a,p9b) Pic'(9)9';
Dcl cnt(3) Bin Fixed(31) Init((3)0);
Dcl x Bin Fixed(31);
Dcl pd(300) Bin Fixed(31);
Dcl sumpd Bin Fixed(31);
Dcl npd Bin Fixed(31);
Dcl hi Bin Fixed(31) Init(0);
Dcl (xl(10),xi) Bin Fixed(31);
Dcl i Bin Fixed(31);
Do x=1 To 10;
Call proper_divisors(x,pd,npd);
Put Edit(x,' -> ',(pd(i) Do i=1 To npd))(Skip,f(2),a,10(f(2)));
End;
xi=0;
Do x=1 To 20000;
Call proper_divisors(x,pd,npd);
Select;
When(npd>hi) Do;
xi=1;
xl(1)=x;
hi=npd;
End;
When(npd=hi) Do;
xi+=1;
xl(xi)=x;
End;
Otherwise;
End;
End;
Put Edit(hi,' -> ',(xl(i) Do i=1 To xi))(Skip,f(3),a,10(f(6)));
x= 166320; Call proper_divisors(x,pd,npd);
Put Edit(x,' -> ',npd)(Skip,f(8),a,f(4));
x=1441440; Call proper_divisors(x,pd,npd);
Put Edit(x,' -> ',npd)(Skip,f(8),a,f(4));
p9b=time();
Put Edit((p9b-p9a)/1000,' seconds elapsed')(Skip,f(6,3),a);
Return;
proper_divisors: Proc(n,pd,npd);
Dcl (n,pd(300),npd) Bin Fixed(31);
Dcl (d,delta) Bin Fixed(31);
npd=0;
If n>1 Then Do;
If mod(n,2)=1 Then /* odd number */
delta=2;
Else /* even number */
delta=1;
Do d=1 To n/2 By delta;
If mod(n,d)=0 Then Do;
npd+=1;
pd(npd)=d;
End;
End;
End;
End;
End; |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| #Racket | Racket |
#lang racket
(require data/heap)
(define pq (make-heap (λ(x y) (<= (second x) (second y)))))
(define (insert! x pri)
(heap-add! pq (list pri x)))
(define (remove-min!)
(begin0
(first (heap-min pq))
(heap-remove-min! pq)))
(insert! 3 "Clear drains")
(insert! 4 "Feed cat")
(insert! 5 "Make tea")
(insert! 1 "Solve RC tasks")
(insert! 2 "Tax return")
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
(remove-min!)
|
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
| #jq | jq | def factors:
. as $in
| [2, $in, false]
| recurse(
. as [$p, $q, $valid, $s]
| if $q == 1 then empty
elif $q % $p == 0 then [$p, $q/$p, true]
elif $p == 2 then [3, $q, false, $s]
else ($s // ($q | sqrt)) as $s
| if $p + 2 <= $s then [$p + 2, $q, false, $s]
else [$q, 1, true]
end
end )
| if .[2] then .[0] else empty end ; |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.