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/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.
| #PARI.2FGP | PARI/GP | plothraw(vx, vy) |
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.
| #Perl | Perl | use GD::Graph::points;
@data = (
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0],
);
$graph = GD::Graph::points->new(400, 300);
open my $fh, '>', "qsort-range-10-9.png";
binmode $fh;
print $fh $graph->plot(\@data)->png;
close $fh; |
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
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface RCPoint : NSObject {
int x, y;
}
-(instancetype)initWithX:(int)x0;
-(instancetype)initWithX:(int)x0 andY:(int)y0;
-(instancetype)initWithPoint:(RCPoint *)p;
@property (nonatomic) int x;
@property (nonatomic) int y;
@end
@implementation RCPoint
@synthesize x, y;
-(instancetype)initWithX:(int)x0 { return [self initWithX:x0 andY:0]; }
-(instancetype)initWithX:(int)x0 andY:(int)y0 {
if ((self = [super init])) {
x = x0;
y = y0;
}
return self;
}
-(instancetype)initWithPoint:(RCPoint *)p { return [self initWithX:p.x andY:p.y]; }
-(NSString *)description { return [NSString stringWithFormat:@"<RCPoint %p x: %d y: %d>", self, x, y]; }
@end
@interface RCCircle : RCPoint {
int r;
}
-(instancetype)initWithCenter:(RCPoint *)p andRadius:(int)r0;
-(instancetype)initWithX:(int)x0 andY:(int)y0 andRadius:(int)r0;
-(instancetype)initWithCircle:(RCCircle *)c;
@property (nonatomic) int r;
@end
@implementation RCCircle
@synthesize r;
-(instancetype)initWithCenter:(RCPoint *)p andRadius:(int)r0 {
if ((self = [super initWithPoint:p])) {
r = r0;
}
return self;
}
-(instancetype)initWithX:(int)x0 andY:(int)y0 andRadius:(int)r0 {
if ((self = [super initWithX:x0 andY:y0])) {
r = r0;
}
return self;
}
-(instancetype)initWithCircle:(RCCircle *)c { return [self initWithX:c.x andY:c.y andRadius:c.r]; }
-(NSString *)description { return [NSString stringWithFormat:@"<RCCircle %p x: %d y: %d r: %d>", self, x, y, r]; }
@end
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSLog(@"%@", [[RCPoint alloc] init]);
NSLog(@"%@", [[RCPoint alloc] initWithX:3]);
NSLog(@"%@", [[RCPoint alloc] initWithX:3 andY:4]);
NSLog(@"%@", [[RCCircle alloc] init]);
NSLog(@"%@", [[RCCircle alloc] initWithX:3]);
NSLog(@"%@", [[RCCircle alloc] initWithX:3 andY:4]);
NSLog(@"%@", [[RCCircle alloc] initWithX:3 andY:4 andRadius:7]);
RCPoint *p = [[RCPoint alloc] initWithX:1 andY:2];
NSLog(@"%@", [[RCCircle alloc] initWithPoint:p]);
NSLog(@"%@", [[RCCircle alloc] initWithCenter:p andRadius:7]);
NSLog(@"%d", p.x); // 1
p.x = 8;
NSLog(@"%d", p.x); // 8
}
return 0;
} |
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
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "console.s7i";
const string: face is "A23456789TJQK";
const string: suit is "♥♦♣♠";
const func string: analyzeHand (in array integer: faceCnt, in array integer: suitCnt) is func
result
var string: handValue is "";
local
var boolean: pair1 is FALSE;
var boolean: pair2 is FALSE;
var boolean: three is FALSE;
var boolean: four is FALSE;
var boolean: flush is FALSE;
var boolean: straight is FALSE;
var integer: sequence is 0;
var integer: x is 0;
begin
for x range 1 to 13 do
case faceCnt[x] of
when {2}: if pair1 then pair2 := TRUE; else pair1 := TRUE; end if;
when {3}: three := TRUE;
when {4}: four := TRUE;
end case;
end for;
for x range 1 to 4 until flush do
if suitCnt[x] = 5 then
flush := TRUE;
end if;
end for;
if not pair1 and not three and not four then
for x range 1 to 13 until sequence = 5 do
if faceCnt[x] <> 0 then incr(sequence); else sequence := 0; end if;
end for;
straight := sequence = 5 or (sequence = 4 and faceCnt[1] <> 0);
end if;
if straight and flush then handValue := "straight-flush";
elsif four then handValue := "four-of-a-kind";
elsif pair1 and three then handValue := "full-house";
elsif flush then handValue := "flush";
elsif straight then handValue := "straight";
elsif three then handValue := "three-of-a-kind";
elsif pair1 and pair2 then handValue := "two-pair";
elsif pair1 then handValue := "one-pair";
else handValue := "high-card";
end if;
end func;
const proc: analyze (in string: cards) is func
local
var array integer: faceCnt is 13 times 0;
var array integer: suitCnt is 4 times 0;
var string: card is "";
begin
for card range split(upper(cards), ' ') do
incr(faceCnt[pos(face, card[1])]);
incr(suitCnt[pos(suit, card[2])]);
end for;
writeln(cards <& ": " <& analyzeHand(faceCnt, suitCnt));
end func;
const proc: main is func
begin
OUT := STD_CONSOLE;
analyze("2♥ 2♦ 2♠ k♠ q♦");
analyze("2♥ 5♥ 7♦ 8♠ 9♦");
analyze("a♥ 2♦ 3♠ 4♠ 5♠");
analyze("2♥ 3♥ 2♦ 3♠ 3♦");
analyze("2♥ 7♥ 2♦ 3♠ 3♦");
analyze("2♥ 7♥ 7♦ 7♠ 7♣");
analyze("t♥ j♥ q♥ k♥ a♥");
analyze("4♥ 4♣ k♣ 5♦ t♣");
analyze("q♣ t♣ 7♣ 6♣ 4♣");
end func; |
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.
| #Go | Go | package main
import (
"fmt"
"math/bits"
)
func main() {
fmt.Println("Pop counts, powers of 3:")
n := uint64(1) // 3^0
for i := 0; i < 30; i++ {
fmt.Printf("%d ", bits.OnesCount64(n))
n *= 3
}
fmt.Println()
fmt.Println("Evil numbers:")
var od [30]uint64
var ne, no int
for n = 0; ne+no < 60; n++ {
if bits.OnesCount64(n)&1 == 0 {
if ne < 30 {
fmt.Printf("%d ", n)
ne++
}
} else {
if no < 30 {
od[no] = n
no++
}
}
}
fmt.Println()
fmt.Println("Odious numbers:")
for _, n := range od {
fmt.Printf("%d ", n)
}
fmt.Println()
} |
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
| #Sidef | Sidef | func poly_long_div(rn, rd) {
var n = rn.map{_}
var gd = rd.len
if (n.len >= gd) {
return(gather {
while (n.len >= gd) {
var piv = n[0]/rd[0]
take(piv)
{ |i|
n[i] -= (rd[i] * piv)
} << ^(n.len `min` gd)
n.shift
}
}, n)
}
return([0], rn)
} |
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.
| #R | R |
x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y <- c(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
coef(lm(y ~ x + I(x^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.
| #jq | jq | def powerset:
reduce .[] as $i ([[]];
reduce .[] as $r (.; . + [$r + [$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
| #Emacs_Lisp | Emacs Lisp | (defun prime (a)
(not (or (< a 2)
(cl-loop for x from 2 to (sqrt a)
when (zerop (% a x))
return 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
| #Nim | Nim | import random, strformat
# Representation of a standard value as an int (actual value * 100).
type StandardValue = distinct int
proc `<`(a, b: StandardValue): bool {.borrow.}
const Pricemap = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100]
proc toStandardValue(f: float): StandardValue =
## Convert a float to a standard value (decimal value multiplied by 100).
## Index: 0.01..0.05 -> 0, 0.06..0.10 -> 1, 0.11..0.15 -> 2...
var value = int(f * 100)
if value == 0: return StandardValue(10)
dec value
# Increment index every 5 of value, so value in 1..100 translates to index in 0..19.
let index = 2 * (value div 10) + (value mod 10) div 5
result = StandardValue(Pricemap[index])
proc `$`(price: StandardValue): string =
## Return the string representation of a standard value.
if price < StandardValue(10): "0.0" & $int(price)
elif price < StandardValue(100): "0." & $int(price)
else: "1.00"
when isMainModule:
randomize()
for _ in 0 .. 10:
let price = rand(1.01)
echo &"Price for {price:.2f} is {price.toStandardValue()}" |
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
| #Objeck | Objeck | class PriceFraction {
function : Main(args : String[]) ~ Nil {
for(i := 0; i < 5; i++;) {
f := Float->Random();
r := SpecialRound(f);
"{$f} -> {$r}"->PrintLine();
};
}
function : SpecialRound(inValue : Float) ~ Float {
if (inValue > 1) {
return 1;
};
splitters := [
0.00 , 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 ];
replacements := [
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(x := 0; x < splitters->Size() - 1; x+=1;) {
if (inValue >= splitters[x] & inValue < splitters[x + 1]) {
return replacements[x];
};
};
return inValue;
}
} |
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
| #PowerShell | PowerShell |
function proper-divisor ($n) {
if($n -ge 2) {
$lim = [Math]::Floor([Math]::Sqrt($n))
$less, $greater = @(1), @()
for($i = 2; $i -lt $lim; $i++){
if($n%$i -eq 0) {
$less += @($i)
$greater = @($n/$i) + $greater
}
}
if(($lim -ne 1) -and ($n%$lim -eq 0)) {$less += @($lim)}
$($less + $greater)
} else {@()}
}
"$(proper-divisor 100)"
"$(proper-divisor 496)"
"$(proper-divisor 2048)"
|
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.
| #Raku | Raku | class PriorityQueue {
has @!tasks;
method insert (Int $priority where * >= 0, $task) {
@!tasks[$priority].push: $task;
}
method get { @!tasks.first(?*).shift }
method is-empty { ?none @!tasks }
}
my $pq = PriorityQueue.new;
for (
3, 'Clear drains',
4, 'Feed cat',
5, 'Make tea',
9, 'Sleep',
3, 'Check email',
1, 'Solve RC tasks',
9, 'Exercise',
2, 'Do taxes'
) -> $priority, $task {
$pq.insert( $priority, $task );
}
say $pq.get until $pq.is-empty; |
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
| #Julia | Julia |
julia> Pkg.add("Primes")
julia> factor(8796093022207)
[9719=>1,431=>1,2099863=>1]
|
http://rosettacode.org/wiki/Plot_coordinate_pairs | Plot coordinate pairs | Task
Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on Time a function):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Processing | Processing |
//Aamrun, 26th June 2022
int x[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
float y[] = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
size(300,300);
surface.setTitle("Rosetta Plot");
stroke(#ff0000);
for(int i=0;i<x.length;i++){
ellipse(x[i],y[i],3,3);
}
|
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
| #OCaml | OCaml | class point ?(x=0.0) ?(y=0.0) () = (* extra () used to erase the optional parameters *)
object (self)
val mutable x = x
val mutable y = y
method x = x
method y = y
method set_x x' = x <- x'
method set_y y' = y <- y'
method print = Printf.sprintf "Point (%f, %f)" x y
method copy = {< >}
end
class circle ?(r=1.0) ?(x=0.0) ?(y=0.0) () =
object (self)
inherit point ~x:x ~y:y ()
val mutable r = r
method r = r
method set_r r' = r <- r'
method print = Printf.sprintf "Circle (%f, %f, %f)" r x y
end
let print x = print_endline x#print
let () =
let p = new point () in
let c = new circle () in
print c;
print p;
c#set_x 10.0;
print c;
print (new point ~y:2.1 ()) |
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
| #Standard_ML | Standard ML |
local
val rec ins = fn x : int*'a => fn [] => [x]
| ll as h::t => if #1 x<= (#1 h) then x::ll else h::ins x t
val rec acount = fn
(n,a::(b::t)) => if a=b then acount (n+1,b::t) else (n,a)::acount(1,b::t)
| (n,[t]) => [(n,t)]
in (* helper count and sort functions *)
val rec sortBy1st = fn [] => [] | h::t => ins h (sortBy1st t)
val addcount = fn ll => acount (1,ll)
end;
val showHand = fn input =>
let
exception Cheat of string
(* replace a j q k by their numbers *)
val translateCardstrings = fn inputstr =>
String.tokens (fn #" "=>true|_=>false) (String.translate (fn #"a"=>"1"| #"j"=>"11"| #"q"=>"12"| #"k"=>"13" | a=>str a ) inputstr )
(* parse numbers and characters into int*strings and order those *)
val parseFacesSuits = fn cardcodes =>
sortBy1st (List.map (fn el => (valOf (Int.fromString el ),String.extract (el,String.size el -1,NONE) )) cardcodes )
handle Option => raise Cheat "parse"
(* replace the list of face numbers by a list of every face with its count and order it / descending count *)
val countAndSort =fn li =>
let val hand = ListPair.unzip li in (rev (sortBy1st (addcount (#1 hand))) , #2 hand ) end;
val score = fn
( (4,_)::t , _ ) => "four-of-a-kind"
| ( (3,_)::(2,_)::t , _ ) => "full-house"
| ( (3,_)::t,_) => "three-of-a-kind"
| ( (2,_)::(2,_)::t,_) => "two-pair"
| ( (2,_)::t,_) => "one-pair"
| (x as (1,_)::t,ll) => if #2 (hd x ) - (#2 (hd (rev x))) =4 orelse ( #2 (hd (rev x)) = 1 andalso #2 (hd (tl (rev x))) =10 )
then
if List.all (fn x => hd ll=x) ll
then "straight-flush"
else "straight"
else if List.all (fn x => hd ll=x) ll then "flush" else "high-card"
| _ => "invalid"
(* return 'invalid' if any duplicates or invalid codes *)
val validate = fn lpair : (int * string) list =>
let val rec uniq = fn ([],y) =>true|(x,y) => List.filter (fn a=>a= hd x) y = [hd x] andalso uniq(tl x,y)
in
if List.all (fn x :int*string => #1 x > 0 andalso #1 x < 14 ) lpair
andalso List.all (fn (x) => Option.isSome ( List.find (fn a=> a= #2x) ["c","d","h","s"] ) ) lpair
andalso uniq (lpair ,lpair)
then lpair
else raise Cheat "value"
end
in
( score o countAndSort o validate o parseFacesSuits o translateCardstrings ) input handle Cheat ch => "invalid"
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.
| #Haskell | Haskell | import Data.Bits (popCount)
printPops :: (Show a, Integral a) => String -> [a] -> IO ()
printPops title counts = putStrLn $ title ++ show (take 30 counts)
main :: IO ()
main = do
printPops "popcount " $ map popCount $ iterate (*3) (1 :: Integer)
printPops "evil " $ filter (even . popCount) ([0..] :: [Integer])
printPops "odious " $ filter ( odd . popCount) ([0..] :: [Integer]) |
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
| #Slate | Slate | define: #Polynomial &parents: {Comparable} &slots: {#coefficients -> ExtensibleArray new}.
p@(Polynomial traits) new &capacity: n
[
p cloneSettingSlots: #(coefficients) to: {p coefficients new &capacity: n}
].
p@(Polynomial traits) newFrom: seq@(Sequence traits)
[
p clone `>> [coefficients: (seq as: p coefficients). normalize. ]
].
p@(Polynomial traits) copy
[
p cloneSettingSlots: #(coefficients) to: {p coefficients copy}
].
p1@(Polynomial traits) >= p2@(Polynomial traits)
[p1 degree >= p2 degree].
p@(Polynomial traits) degree
[p coefficients indexOfLastSatisfying: [| :n | n isZero not]].
p@(Polynomial traits) normalize
[
[p degree isPositive /\ [p coefficients last isZero]]
whileTrue: [p coefficients removeLast]
].
p@(Polynomial traits) * n@(Number traits)
[
p newFrom: (p coefficients collect: [| :x | x * n])
].
p@(Polynomial traits) / n@(Number traits)
[
p newFrom: (p coefficients collect: [| :x | x / n])
].
p1@(Polynomial traits) minusCoefficients: p2@(Polynomial traits)
[
p1 newFrom: (p1 coefficients with: p2 coefficients collect: #- `er)
].
p@(Polynomial traits) / denom@(Polynomial traits)
[
p >= denom
ifTrue:
[| n q |
n: p copy.
q: p new.
[n >= denom]
whileTrue:
[| piv |
piv: p coefficients last / denom coefficients last.
q coefficients add: piv.
n: (n minusCoefficients: denom * piv).
n normalize].
n coefficients isEmpty ifTrue: [n coefficients add: 0].
{q. n}]
ifFalse: [{p newFrom: #(0). p copy}]
]. |
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.
| #Racket | Racket |
#lang racket
(require math plot)
(define xs '(0 1 2 3 4 5 6 7 8 9 10))
(define ys '(1 6 17 34 57 86 121 162 209 262 321))
(define (fit x y n)
(define Y (->col-matrix y))
(define V (vandermonde-matrix x (+ n 1)))
(define VT (matrix-transpose V))
(matrix->vector (matrix-solve (matrix* VT V) (matrix* VT Y))))
(define ((poly v) x)
(for/sum ([c v] [i (in-naturals)])
(* c (expt x i))))
(plot (list (points (map vector xs ys))
(function (poly (fit xs ys 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.
| #Julia | Julia |
function powerset{T}(x::Vector{T})
result = Vector{T}[[]]
for elem in x, j in eachindex(result)
push!(result, [result[j] ; elem])
end
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
| #Erlang | Erlang | is_prime(N) when N == 2 -> true;
is_prime(N) when N < 2 orelse N rem 2 == 0 -> false;
is_prime(N) -> is_prime(N,3).
is_prime(N,K) when K*K > N -> true;
is_prime(N,K) when N rem K == 0 -> false;
is_prime(N,K) -> is_prime(N,K+2). |
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
| #OCaml | OCaml | let price_fraction v =
if v < 0.0 || v >= 1.01 then
invalid_arg "price_fraction";
let rec aux = function
| (x,r)::tl ->
if v < x then r
else aux tl
| [] -> assert false
in
aux [
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;
] |
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
| #Prolog | Prolog | divisor(N, Divisor) :-
UpperBound is round(sqrt(N)),
between(1, UpperBound, D),
0 is N mod D,
(
Divisor = D
;
LargerDivisor is N/D,
LargerDivisor =\= D,
Divisor = LargerDivisor
).
proper_divisor(N, D) :-
divisor(N, D),
D =\= N.
%% Task 1
%
proper_divisors(N, Ds) :-
setof(D, proper_divisor(N, D), Ds).
%% Task 2
%
show_proper_divisors_of_range(Low, High) :-
findall( N:Ds,
( between(Low, High, N),
proper_divisors(N, Ds) ),
Results ),
maplist(writeln, Results).
%% Task 3
%
proper_divisor_count(N, Count) :-
proper_divisors(N, Ds),
length(Ds, Count).
find_most_proper_divisors_in_range(Low, High, Result) :-
aggregate_all( max(Count, N),
( between(Low, High, N),
proper_divisor_count(N, Count) ),
max(MaxCount, Num) ),
Result = (num(Num)-divisor_count(MaxCount)). |
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.
| #REXX | REXX | /*REXX program implements a priority queue with insert/display/delete the top task.*/
#=0; @.= /*0 tasks; nullify the priority queue.*/
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
call .ins 4 "Feed cat"
call .ins 5 "Make tea"
call .ins 1 "Solve RC tasks"
call .ins 2 "Tax return"
call .ins 6 "Relax"
call .ins 6 "Enjoy"
say '══════ showing tasks.'; call .show
say '══════ deletes top task.'; say .del() /*delete the top task. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y
.ins: procedure expose @. #; #=#+1; @.#=arg(1); return # /*entry, P, task.*/
.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
.top: procedure expose @. #; top=; top#=
do j=1 for #; _=word(@.j, 1); if _=='' then iterate
if top=='' | _>top then do; top=_; top#=j; end
end /*j*/
return top# |
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
| #Kotlin | Kotlin | // version 1.0.6
import java.math.BigInteger
val bigTwo = BigInteger.valueOf(2L)
val bigThree = BigInteger.valueOf(3L)
fun getPrimeFactors(n: BigInteger): MutableList<BigInteger> {
val factors = mutableListOf<BigInteger>()
if (n < bigTwo) return factors
if (n.isProbablePrime(20)) {
factors.add(n)
return factors
}
var factor = bigTwo
var nn = n
while (true) {
if (nn % factor == BigInteger.ZERO) {
factors.add(factor)
nn /= factor
if (nn == BigInteger.ONE) return factors
if (nn.isProbablePrime(20)) factor = nn
}
else if (factor >= bigThree) factor += bigTwo
else factor = bigThree
}
}
fun main(args: Array<String>) {
val primes = intArrayOf(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)
for (prime in primes) {
val bigPow2 = bigTwo.pow(prime) - BigInteger.ONE
println("2^${"%2d".format(prime)} - 1 = ${bigPow2.toString().padEnd(30)} => ${getPrimeFactors(bigPow2)}")
}
} |
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.
| #Phix | Phix | --
-- demo\rosetta\Plot_coordinate_pairs.exw
-- ======================================
--
with javascript_semantics
include pGUI.e
include IupGraph.e
constant 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}
function get_data(Ihandle graph) return {{x,y,CD_BLUE}} end function
IupOpen()
Ihandle graph = IupGraph(get_data),
dlg = IupDialog(graph,`TITLE="Plot coordinate pairs"`)
IupSetAttributes(dlg,"RASTERSIZE=320x240,MINSIZE=320x200")
IupSetAttributes(graph,"XTICK=1,XMIN=0,XMAX=9")
IupSetAttributes(graph,"YTICK=20,YMIN=0,YMAX=180")
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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
| #Oforth | Oforth | Object Class new: Point(x, y)
Point method: initialize(x, y) x := x y := y ;
Point method: _x @x ;
Point method: _y @y ;
Point method: << "(" << @x << ", " << @y << ")" << ;
Object Class new: Circle(x, y, r)
Circle method: initialize(x, y, r) x := x y := y r := r ;
Circle method: _x @x ;
Circle method: _y @y ;
Circle method: _r @r ;
Circle method: << "(" << @x << ", " << @y << ", " << @r << ")" << ;
Circle classMethod: newFromPoint(aPoint, r) self new(aPoint _x, aPoint _y, r) ; |
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
| #ooRexx | ooRexx |
p = .point~new(3,2)
c = .circle~new(,2,6)
p~print
c~print
::class point
::method init
expose x y
use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates
::attribute x
::attribute y
::method print
expose x y
say "A point at location ("||x","y")"
::class circle subclass point
::method init
expose radius
use strict arg x = 0, y = 0, radius = 0
self~init:super(x, y) -- call superclass constructor
::attribute radius
::method print
expose radius
say "A circle of radius" radius "centered at location ("||self~x","self~y")"
|
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
| #Tcl | Tcl | package require Tcl 8.6
namespace eval PokerHandAnalyser {
proc analyse {hand} {
set norm [Normalise $hand]
foreach type {
invalid straight-flush four-of-a-kind full-house flush straight
three-of-a-kind two-pair one-pair
} {
if {[Detect-$type $norm]} {
return $type
}
}
# Always possible to use high-card if the hand is legal at all
return high-card
}
# This normalises to an internal representation that is a list of pairs,
# where each pair is one number for the pips (ace == 14, king == 13,
# etc.) and another for the suit. This greatly simplifies detection.
proc Normalise {hand} {
set PipMap {j 11 q 12 k 13 a 14}
set SuitMap {♥ 2 h 2 ♦ 1 d 1 ♣ 0 c 0 ♠ 3 s 3}
set hand [string tolower $hand]
set cards [regexp -all -inline {(?:[akqj98765432]|10)[hdcs♥♦♣♠]} $hand]
lsort -command CompareCards [lmap c [string map {} $cards] {
list [string map $PipMap [string range $c 0 end-1]] \
[string map $SuitMap [string index $c end]]
}]
}
proc CompareCards {a b} {
lassign $a pipA suitA
lassign $b pipB suitB
expr {$pipA==$pipB ? $suitB-$suitA : $pipB-$pipA}
}
# Detection code. Note that the detectors all assume that the preceding
# detectors have been run first; this simplifies the logic a lot, but does
# mean that the individual detectors are not robust on their own.
proc Detect-invalid {hand} {
if {[llength $hand] != 5} {return 1}
foreach c $hand {
if {[incr seen($c)] > 1} {return 1}
}
return 0
}
proc Detect-straight-flush {hand} {
foreach c $hand {
lassign $c pip suit
if {[info exist prev] && $prev-1 != $pip} {
# Special case: ace low straight flush ("steel wheel")
if {$prev != 14 && $suit != 5} {
return 0
}
}
set prev $pip
incr seen($suit)
}
return [expr {[array size seen] == 1}]
}
proc Detect-four-of-a-kind {hand} {
foreach c $hand {
lassign $c pip suit
if {[incr seen($pip)] > 3} {return 1}
}
return 0
}
proc Detect-full-house {hand} {
foreach c $hand {
lassign $c pip suit
incr seen($pip)
}
return [expr {[array size seen] == 2}]
}
proc Detect-flush {hand} {
foreach c $hand {
lassign $c pip suit
incr seen($suit)
}
return [expr {[array size seen] == 1}]
}
proc Detect-straight {hand} {
foreach c $hand {
lassign $c pip suit
if {[info exist prev] && $prev-1 != $pip} {
# Special case: ace low straight ("wheel")
if {$prev != 14 && $suit != 5} {
return 0
}
}
set prev $pip
}
return 1
}
proc Detect-three-of-a-kind {hand} {
foreach c $hand {
lassign $c pip suit
if {[incr seen($pip)] > 2} {return 1}
}
return 0
}
proc Detect-two-pair {hand} {
set pairs 0
foreach c $hand {
lassign $c pip suit
if {[incr seen($pip)] > 1} {incr pairs}
}
return [expr {$pairs > 1}]
}
proc Detect-one-pair {hand} {
foreach c $hand {
lassign $c pip suit
if {[incr seen($pip)] > 1} {return 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.
| #Idris | Idris | module Main
import Data.Vect
isOdd : (x : Int) -> Bool
isOdd x = case mod x 2 of
0 => False
1 => True
popcnt : Int -> Int
popcnt 0 = 0
popcnt x = case isOdd x of
False => popcnt (shiftR x 1)
True => 1 + popcnt (shiftR x 1)
isOdious : Int -> Bool
isOdious k = isOdd (popcnt k)
isEvil : Int -> Bool
isEvil k = not (isOdious k)
filterUnfoldN : (n : Nat) ->
(pred : Int -> Bool) -> (f : Int -> a) ->
(next : Int -> Int) -> (seed : Int) ->
Vect n a
filterUnfoldN Z pred f next seed = []
filterUnfoldN (S k) pred f next seed =
if pred seed
then (f seed) :: filterUnfoldN k pred f next (next seed)
else filterUnfoldN (S k) pred f next (next seed)
printCompact : (Show a) => Vect n a -> IO ()
printCompact v = putStrLn (unwords (map show (toList v)))
main : IO ()
main = do putStr "popcnt(3**i): "
printCompact (filterUnfoldN 30 (\_ => True) popcnt (3 *) 1)
putStr "Evil: "
printCompact (filterUnfoldN 30 isEvil id (1 +) 0)
putStr "Odious: "
printCompact (filterUnfoldN 30 isOdious id (1 +) 0) |
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
| #Smalltalk | Smalltalk | Object subclass: Polynomial [
|coeffs|
Polynomial class >> new [ ^ super basicNew init ]
init [ coeffs := OrderedCollection new. ^ self ]
Polynomial class >> newWithCoefficients: coefficients [
|r|
r := super basicNew.
^ r initWithCoefficients: coefficients
]
initWithCoefficients: coefficients [
coeffs := coefficients asOrderedCollection.
^ self
]
/ denominator [ |n q|
n := self deepCopy.
self >= denominator
ifTrue: [
q := Polynomial new.
[ n >= denominator ]
whileTrue: [ |piv|
piv := (n coeff: 0) / (denominator coeff: 0).
q addCoefficient: piv.
n := n - (denominator * piv).
n clean
].
^ { q . (n degree) > 0 ifTrue: [ n ] ifFalse: [ n addCoefficient: 0. n ] }
]
ifFalse: [
^ { Polynomial newWithCoefficients: #( 0 ) . self deepCopy }
]
]
* constant [ |r| r := self deepCopy.
1 to: (coeffs size) do: [ :i |
r at: i put: ((r at: i) * constant)
].
^ r
]
at: index [ ^ coeffs at: index ]
at: index put: obj [ ^ coeffs at: index put: obj ]
>= anotherPoly [
^ (self degree) >= (anotherPoly degree)
]
degree [ ^ coeffs size ]
- anotherPoly [ "This is not a real subtraction between Polynomial: it is an
internal method ..."
|a|
a := self deepCopy.
1 to: ( (coeffs size) min: (anotherPoly degree) ) do: [ :i |
a at: i put: ( (a at: i) - (anotherPoly at: i) )
].
^ a
]
coeff: index [ ^ coeffs at: (index + 1) ]
addCoefficient: coeff [ coeffs add: coeff ]
clean [
[ (coeffs size) > 0
ifTrue: [ (coeffs at: 1) = 0 ] ifFalse: [ false ] ]
whileTrue: [ coeffs removeFirst ].
]
display [
1 to: (coeffs size) do: [ :i |
(coeffs at: i) display.
i < (coeffs size)
ifTrue: [ ('x^%1 + ' % {(coeffs size) - i} ) display ]
]
]
displayNl [ self display. Character nl display ]
]. |
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.
| #Raku | Raku | use Clifford;
constant @x1 = <0 1 2 3 4 5 6 7 8 9 10>;
constant @y = <1 6 17 34 57 86 121 162 209 262 321>;
constant $x0 = [+] @e[^@x1];
constant $x1 = [+] @x1 Z* @e;
constant $x2 = [+] @x1 »**» 2 Z* @e;
constant $y = [+] @y Z* @e;
my $J = $x1 ∧ $x2;
my $I = $x0 ∧ $J;
my $I2 = ($I·$I.reversion).Real;
.say for
(($y ∧ $J)·$I.reversion)/$I2,
(($y ∧ ($x2 ∧ $x0))·$I.reversion)/$I2,
(($y ∧ ($x0 ∧ $x1))·$I.reversion)/$I2; |
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.
| #K | K |
ps:{x@&:'+2_vs!_2^#x}
|
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
| #ERRE | ERRE | PROGRAM PRIME_TRIAL
PROCEDURE ISPRIME(N%->OK%)
LOCAL T%
IF N%<=1 THEN OK%=FALSE EXIT PROCEDURE END IF
IF N%<=3 THEN OK%=TRUE EXIT PROCEDURE END IF
IF (N% AND 1)=0 THEN OK%=FALSE EXIT PROCEDURE END IF
FOR T%=3 TO SQR(N%) STEP 2 DO
IF N% MOD T%=0 THEN OK%=FALSE EXIT PROCEDURE END IF
END FOR
OK%=TRUE
END PROCEDURE
BEGIN
FOR I%=1 TO 100 DO
ISPRIME(I%->OK%)
IF OK% THEN PRINT(i%;"is prime") END IF
END FOR
END PROGRAM |
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
| #Oforth | Oforth | [.06, .11, .16, .21, .26, .31, .36, .41, .46, .51, .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01] const: IN
[.10, .18, .26, .32, .38, .44, .50, .54, .58, .62, .66, .70, .74, .78, .82, .86, .90, .94, .98, 1.00] const: OUT
: priceFraction(f)
| i |
IN size loop: i [ f IN at(i) < ifTrue: [ OUT at(i) return ] ]
null ; |
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
| #PureBasic | PureBasic |
EnableExplicit
Procedure ListProperDivisors(Number, List Lst())
If Number < 2 : ProcedureReturn : EndIf
Protected i
For i = 1 To Number / 2
If Number % i = 0
AddElement(Lst())
Lst() = i
EndIf
Next
EndProcedure
Procedure.i CountProperDivisors(Number)
If Number < 2 : ProcedureReturn 0 : EndIf
Protected i, count = 0
For i = 1 To Number / 2
If Number % i = 0
count + 1
EndIf
Next
ProcedureReturn count
EndProcedure
Define n, count, most = 1, maxCount = 0
If OpenConsole()
PrintN("The proper divisors of the following numbers are : ")
PrintN("")
NewList lst()
For n = 1 To 10
ListProperDivisors(n, lst())
Print(RSet(Str(n), 3) + " -> ")
If ListSize(lst()) = 0
Print("(None)")
Else
ForEach lst()
Print(Str(lst()) + " ")
Next
EndIf
ClearList(lst())
PrintN("")
Next
For n = 2 To 20000
count = CountProperDivisors(n)
If count > maxCount
maxCount = count
most = n
EndIf
Next
PrintN("")
PrintN(Str(most) + " has the most proper divisors, namely " + Str(maxCount))
PrintN("")
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
|
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.
| #Ruby | Ruby | class PriorityQueueNaive
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
data.each {|priority, item| @q[priority] << item} if data
@priorities = @q.keys.sort
end
def push(priority, item)
@q[priority] << item
@priorities = @q.keys.sort
end
def pop
p = @priorities[0]
item = @q[p].shift
if @q[p].empty?
@q.delete(p)
@priorities.shift
end
item
end
def peek
unless empty?
@q[@priorities[0]][0]
end
end
def empty?
@priorities.empty?
end
def each
@q.each do |priority, items|
items.each {|item| yield priority, item}
end
end
def dup
@q.each_with_object(self.class.new) do |(priority, items), obj|
items.each {|item| obj.push(priority, item)}
end
end
def merge(other)
raise TypeError unless self.class == other.class
pq = dup
other.each {|priority, item| pq.push(priority, item)}
pq # return a new object
end
def inspect
@q.inspect
end
end
test = [
[6, "drink tea"],
[3, "Clear drains"],
[4, "Feed cat"],
[5, "Make tea"],
[6, "eat biscuit"],
[1, "Solve RC tasks"],
[2, "Tax return"],
]
pq = PriorityQueueNaive.new
test.each {|pr, str| pq.push(pr, str) }
until pq.empty?
puts pq.pop
end
puts
test2 = test.shift(3)
p pq1 = PriorityQueueNaive.new(test)
p pq2 = PriorityQueueNaive.new(test2)
p pq3 = pq1.merge(pq2)
puts "peek : #{pq3.peek}"
until pq3.empty?
puts pq3.pop
end
puts "peek : #{pq3.peek}" |
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
| #Lambdatalk | Lambdatalk |
{def prime_fact.smallest
{def prime_fact.smallest.r
{lambda {:q :r :i}
{if {and {> :r 0} {< :i :q}}
then {prime_fact.smallest.r :q {% :q {+ :i 1}} {+ :i 1}}
else :i}}}
{lambda {:q} {prime_fact.smallest.r :q {% :q 2} 2}}}
{def prime_fact
{def prime_fact.r
{lambda {:q :d}
{if {> :q 1}
then {let { {:q :q} {:d :d}
{:i {prime_fact.smallest :q}}}
{prime_fact.r {floor {/ :q :i}} {#.push! :d :i}} }
else {if {= {#.length :d} 1} then {b :d} else :d}}}}
{lambda {:n} :n:{prime_fact.r :n {#.new}}}}
{prime_fact {* 2 3 3 3 31 47 173}}
-> 13611294:[2,3,3,3,31,47,173]
{map prime_fact {serie 2 101}}
-> 2:[2] 3:[3] 4:[2,2] 5:[5] 6:[2,3] 7:[7] 8:[2,2,2] 9:[3,3] 10:[2,5] 11:[11] 12:[2,2,3] 13:[13] 14:[2,7] 15:[3,5]
16:[2,2,2,2] 17:[17] 18:[2,3,3] 19:[19] 20:[2,2,5] 21:[3,7] 22:[2,11] 23:[23] 24:[2,2,2,3] 25:[5,5] 26:[2,13] 27:[3,3,3]
28:[2,2,7] 29:[29] 30:[2,3,5] 31:[31] 32:[2,2,2,2,2] 33:[3,11] 34:[2,17] 35:[5,7] 36:[2,2,3,3] 37:[37] 38:[2,19] 39:[3,13]
40:[2,2,2,5] 41:[41] 42:[2,3,7] 43:[43] 44:[2,2,11] 45:[3,3,5] 46:[2,23] 47:[47] 48:[2,2,2,2,3] 49:[7,7] 50:[2,5,5] 51:[3,17]
52:[2,2,13] 53:[53] 54:[2,3,3,3] 55:[5,11] 56:[2,2,2,7] 57:[3,19] 58:[2,29] 59:[59] 60:[2,2,3,5] 61:[61] 62:[2,31] 63:[3,3,7]
64:[2,2,2,2,2,2] 65:[5,13] 66:[2,3,11] 67:[67] 68:[2,2,17] 69:[3,23] 70:[2,5,7] 71:[71] 72:[2,2,2,3,3] 73:[73] 74:[2,37]
75:[3,5,5] 76:[2,2,19] 77:[7,11] 78:[2,3,13] 79:[79] 80:[2,2,2,2,5] 81:[3,3,3,3] 82:[2,41] 83:[83] 84:[2,2,3,7] 85:[5,17]
86:[2,43] 87:[3,29] 88:[2,2,2,11] 89:[89] 90:[2,3,3,5] 91:[7,13] 92:[2,2,23] 93:[3,31] 94:[2,47] 95:[5,19] 96:[2,2,2,2,2,3]
97:[97] 98:[2,7,7] 99:[3,3,11] 100:[2,2,5,5] 101:[101]
|
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.
| #PicoLisp | PicoLisp | (load "@lib/ps.l")
(scl 1)
(de plot (PsFile DX DY Lst)
(let (SX (length Lst) SY (apply max Lst) N 0 Val)
(out PsFile
(psHead (+ DX 20) (+ DY 40))
(font (9 . "Helvetica"))
(if (or (=0 SX) (=0 SY))
(window 60 12 DX DY
(font 24 ,"Not enough Data") )
(setq Lst # Build coordinates
(let X -1
(mapcar
'((Y)
(cons
(*/ (inc 'X) DX SX)
(- DY (*/ Y DY SY)) ) )
Lst ) ) )
(color 55 95 55 # Background color
(let (X (+ DX 40) Y (+ DY 40))
(poly T 0 0 X 0 X Y 0 Y 0 0) ) )
(window 20 20 DX DY # Plot coordinates
(poly NIL 0 0 0 DY (- DX 20) DY)
(color 76 24 24
(poly NIL (caar Lst) (cdar Lst) (cdr Lst)) ) )
(window 4 4 60 12 (ps (format SY *Scl)))
(for X SX
(window (+ 6 (*/ (dec X) DX SX)) (+ 24 DY) 30 12
(ps (format (dec X)) 0) ) ) )
(page) ) ) )
(plot "plot.ps" 300 200 (2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0))
(call 'display "plot.ps") |
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.
| #PostScript | PostScript |
/x [0 1 2 3 4 5 6 7 8 9] def
/y [2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0] def
/i 1 def
newpath
x 0 get y 0 get moveto
x length 1 sub{
x i get y i get lineto
/i i 1 add def
}repeat
stroke
|
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
| #OxygenBasic | OxygenBasic |
type tpoint float xx,yy
type tcircle float xx,yy,rr
'==========
class point
'==========
'
has tpoint
'
method constructor (float x=0,y=0){this<=x,y}
method destructor {}
method V() as point {return @this}
method V(tpoint*a) {this<=a.xx,a.yy}
method V(point *a) {this<=a.xx,a.yy}
method X() as float {return xx}
method Y() as float {return yy}
method X(float a) {xx=a}
method Y(float a) {yy=a}
method clear() {this<=.0,.0}
method show() as string {return "x=" xx ", y=" yy }
'
end class
'===========
class circle
'===========
'
has point
float rr
'
method constructor (float x=.0,y=.0,r=1.0){this<=x,y,r}
method V(tcircle*a) {this<=a.xx,a.yy,a.rr}
method V(circle *a) {this<=a.xx,a.yy,a.rr}
method R() as float {return rr}
method R(float a) {rr=a}
method clear() {this<=.0,.0,.0}
method show() as string {return "x=" xx ", y=" yy ", r=" rr }
'
end class
'=====
'TESTS
'=====
new circle ca (r=.5)
new circle cb (x=10,y=10)
new circle cc (10,10,0.5)
cb.r="7.5" 'will convert a string value
cb.y=20
print cb.show 'result x=10, y=20 ,r=7.5
del ca : del cb : del cc
|
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
| #Oz | Oz | class Point
feat
x
y
meth init(x:X<=0.0 y:Y<=0.0)
self.x = X
self.y = Y
end
meth print
{System.showInfo
"Point("#
"x:"#self.x#
", y:"#self.y#
")"}
end
end
class Circle
feat
center
r
meth init(center:C<={New Point init} r:R<=1.0)
self.center = C
self.r = R
end
meth print
{System.showInfo
"Circle("#
"x:"#self.center.x#
", y:"#self.center.y#
", r:"#self.r#
")"}
end
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
| #Wren | Wren | import "/dynamic" for Tuple
import "/sort" for Sort
import "/str" for Str
import "/seq" for Lst
var Card = Tuple.create("Card", ["face", "suit"])
var FACES = "23456789tjqka"
var SUITS = "shdc"
var isStraight = Fn.new { |cards|
var cmp = Fn.new { |i, j| (i.face - j.face).sign }
var sorted = Sort.merge(cards, cmp)
if (sorted[0].face + 4 == sorted[4].face) return true
if (sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].face == 5) return true
return false
}
var isFlush = Fn.new { |cards|
var suit = cards[0].suit
if (cards.skip(1).all { |card| card.suit == suit }) return true
return false
}
var analyzeHand = Fn.new { |hand|
var h = Str.lower(hand)
var split = Lst.distinct(h.split(" ").where { |c| c != "" }.toList)
if (split.count != 5) return "invalid"
var cards = []
for (s in split) {
if (s.count != 2) return "invalid"
var fIndex = FACES.indexOf(s[0])
if (fIndex == -1) return "invalid"
var sIndex = SUITS.indexOf(s[1])
if (sIndex == -1) return "invalid"
cards.add(Card.new(fIndex + 2, s[1]))
}
var groups = Lst.groups(cards) { |card| card.face }
if (groups.count == 2) {
if (groups.any { |g| g[1].count == 4 }) return "four-of-a-kind"
return "full-house"
} else if (groups.count == 3) {
if (groups.any { |g| g[1].count == 3 }) return "three-of-a-kind"
return "two-pair"
} else if (groups.count == 4) {
return "one-pair"
} else {
var flush = isFlush.call(cards)
var straight = isStraight.call(cards)
if (flush && straight) return "straight-flush"
if (flush) return "flush"
if (straight) return "straight"
return "high-card"
}
}
var hands = [
"2h 2d 2c kc qd",
"2h 5h 7d 8c 9s",
"ah 2d 3c 4c 5d",
"2h 3h 2d 3c 3d",
"2h 7h 2d 3c 3d",
"2h 7h 7d 7c 7s",
"th jh qh kh ah",
"4h 4s ks 5d ts",
"qc tc 7c 6c 4c",
"ah ah 7c 6c 4c"
]
for (hand in hands) {
System.print("%(hand): %(analyzeHand.call(hand))")
} |
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.
| #J | J | countPopln=: +/"1@#:
isOdd=: 1 = 2&|
isEven=: 0 = 2&| |
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
| #SPAD | SPAD | (1) -> monicDivide(x^3-12*x^2-42,x-3,'x)
2
(1) [quotient = x - 9x - 27,remainder = - 123]
Type: Record(quotient: Polynomial(Integer),remainder: Polynomial(Integer)) |
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
| #Swift | Swift | protocol Dividable {
static func / (lhs: Self, rhs: Self) -> Self
}
extension Int: Dividable { }
struct Solution<T> {
var quotient: [T]
var remainder: [T]
}
func polyDegree<T: SignedNumeric>(_ p: [T]) -> Int {
for i in stride(from: p.count - 1, through: 0, by: -1) where p[i] != 0 {
return i
}
return Int.min
}
func polyShiftRight<T: SignedNumeric>(p: [T], places: Int) -> [T] {
guard places > 0 else {
return p
}
let deg = polyDegree(p)
assert(deg + places < p.count, "Number of places to shift too large")
var res = p
for i in stride(from: deg, through: 0, by: -1) {
res[i + places] = res[i]
res[i] = 0
}
return res
}
func polyMul<T: SignedNumeric>(_ p: inout [T], by: T) {
for i in 0..<p.count {
p[i] *= by
}
}
func polySub<T: SignedNumeric>(_ p: inout [T], by: [T]) {
for i in 0..<p.count {
p[i] -= by[i]
}
}
func polyLongDiv<T: SignedNumeric & Dividable>(numerator n: [T], denominator d: [T]) -> Solution<T>? {
guard n.count == d.count else {
return nil
}
var nDeg = polyDegree(n)
let dDeg = polyDegree(d)
guard dDeg >= 0, nDeg >= dDeg else {
return nil
}
var n2 = n
var quo = [T](repeating: 0, count: n.count)
while nDeg >= dDeg {
let i = nDeg - dDeg
var d2 = polyShiftRight(p: d, places: i)
quo[i] = n2[nDeg] / d2[nDeg]
polyMul(&d2, by: quo[i])
polySub(&n2, by: d2)
nDeg = polyDegree(n2)
}
return Solution(quotient: quo, remainder: n2)
}
func polyPrint<T: SignedNumeric & Comparable>(_ p: [T]) {
let deg = polyDegree(p)
for i in stride(from: deg, through: 0, by: -1) where p[i] != 0 {
let coeff = p[i]
switch coeff {
case 1 where i < deg:
print(" + ", terminator: "")
case 1:
print("", terminator: "")
case -1 where i < deg:
print(" - ", terminator: "")
case -1:
print("-", terminator: "")
case _ where coeff < 0 && i < deg:
print(" - \(-coeff)", terminator: "")
case _ where i < deg:
print(" + \(coeff)", terminator: "")
case _:
print("\(coeff)", terminator: "")
}
if i > 1 {
print("x^\(i)", terminator: "")
} else if i == 1 {
print("x", terminator: "")
}
}
print()
}
let n = [-42, 0, -12, 1]
let d = [-3, 1, 0, 0]
print("Numerator: ", terminator: "")
polyPrint(n)
print("Denominator: ", terminator: "")
polyPrint(d)
guard let sol = polyLongDiv(numerator: n, denominator: d) else {
fatalError()
}
print("----------")
print("Quotient: ", terminator: "")
polyPrint(sol.quotient)
print("Remainder: ", terminator: "")
polyPrint(sol.remainder) |
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.
| #REXX | REXX | /* REXX ---------------------------------------------------------------
* Implementation of http://keisan.casio.com/exec/system/14059932254941
*--------------------------------------------------------------------*/
xl='0 1 2 3 4 5 6 7 8 9 10'
yl='1 6 17 34 57 86 121 162 209 262 321'
n=11
Do i=1 To n
Parse Var xl x.i xl
Parse Var yl y.i yl
End
xm=0
ym=0
x2m=0
x3m=0
x4m=0
xym=0
x2ym=0
Do i=1 To n
xm=xm+x.i
ym=ym+y.i
x2m=x2m+x.i**2
x3m=x3m+x.i**3
x4m=x4m+x.i**4
xym=xym+x.i*y.i
x2ym=x2ym+(x.i**2)*y.i
End
xm =xm /n
ym =ym /n
x2m=x2m/n
x3m=x3m/n
x4m=x4m/n
xym=xym/n
x2ym=x2ym/n
Sxx=x2m-xm**2
Sxy=xym-xm*ym
Sxx2=x3m-xm*x2m
Sx2x2=x4m-x2m**2
Sx2y=x2ym-x2m*ym
B=(Sxy*Sx2x2-Sx2y*Sxx2)/(Sxx*Sx2x2-Sxx2**2)
C=(Sx2y*Sxx-Sxy*Sxx2)/(Sxx*Sx2x2-Sxx2**2)
A=ym-B*xm-C*x2m
Say 'y='a'+'||b'*x+'c'*x**2'
Say ' Input "Approximation"'
Say ' x y y1'
Do i=1 To 11
Say right(x.i,2) right(y.i,3) format(fun(x.i),5,3)
End
Exit
fun:
Parse Arg x
Return a+b*x+c*x**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.
| #Kotlin | Kotlin | // purely functional & lazy version, leveraging recursion and Sequences (a.k.a. streams)
fun <T> Set<T>.subsets(): Sequence<Set<T>> =
when (size) {
0 -> sequenceOf(emptySet())
else -> {
val head = first()
val tail = this - head
tail.subsets() + tail.subsets().map { setOf(head) + it }
}
}
// if recursion is an issue, you may change it this way:
fun <T> Set<T>.subsets(): Sequence<Set<T>> = sequence {
when (size) {
0 -> yield(emptySet<T>())
else -> {
val head = first()
val tail = this@subsets - head
yieldAll(tail.subsets())
for (subset in tail.subsets()) {
yield(setOf(head) + subset)
}
}
}
}
|
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
| #Euphoria | Euphoria | function is_prime(integer n)
if n<=2 or remainder(n,2)=0 then
return 0
else
for i=3 to sqrt(n) by 2 do
if remainder(n,i)=0 then
return 0
end if
end for
return 1
end if
end function |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Oz | Oz | fun {PriceFraction X}
OutOfRange = {Value.failed outOfRange(X)}
in
for Limit#Result in
[0.00#OutOfRange
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.5
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:Return
default:OutOfRange
do
if X < Limit then {Return Result} end
end
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
| #Python | Python | >>> def proper_divs2(n):
... return {x for x in range(1, (n + 1) // 2 + 1) if n % x == 0 and n != x}
...
>>> [proper_divs2(n) for n in range(1, 11)]
[set(), {1}, {1}, {1, 2}, {1}, {1, 2, 3}, {1}, {1, 2, 4}, {1, 3}, {1, 2, 5}]
>>>
>>> n, length = max(((n, len(proper_divs2(n))) for n in range(1, 20001)), key=lambda pd: pd[1])
>>> n
15120
>>> length
79
>>> |
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.
| #Run_BASIC | Run BASIC | sqliteconnect #mem, ":memory:"
#mem execute("CREATE TABLE queue (priority float,descr text)")
' --------------------------------------------------------------
' Insert items into the que
' --------------------------------------------------------------
#mem execute("INSERT INTO queue VALUES (3,'Clear drains')")
#mem execute("INSERT INTO queue VALUES (4,'Feed cat')")
#mem execute("INSERT INTO queue VALUES (5,'Make tea')")
#mem execute("INSERT INTO queue VALUES (1,'Solve RC tasks')")
#mem execute("INSERT INTO queue VALUES (2,'Tax return')")
'--------------- insert priority between 4 and 5 -----------------
#mem execute("INSERT INTO queue VALUES (4.5,'My Special Project')")
what$ = " -------------- Find first priority ---------------------"
mem$ = "SELECT * FROM queue ORDER BY priority LIMIT 1"
gosub [getQueue]
what$ = " -------------- Find last priority ---------------------"
mem$ = "SELECT * FROM queue ORDER BY priority desc LIMIT 1"
gosub [getQueue]
what$ = " -------------- Delete Highest Priority ---------------------"
mem$ = "DELETE FROM queue WHERE priority = (select max(q.priority) FROM queue as q)"
#mem execute(mem$)
what$ = " -------------- List Priority Sequence ---------------------"
mem$ = "SELECT * FROM queue ORDER BY priority"
gosub [getQueue]
end
[getQueue]
print what$
#mem execute(mem$)
rows = #mem ROWCOUNT()
print "Priority Description"
for i = 1 to rows
#row = #mem #nextrow()
priority = #row priority()
descr$ = #row descr$()
print priority;" ";descr$
next i
RETURN |
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
| #LFE | LFE |
(defun factors (n)
(factors n 2 '()))
(defun factors
((1 _ acc)
acc)
((n k acc) (when (== 0 (rem n k)))
(factors (div n k) k (cons k acc)))
((n k acc)
(factors n (+ k 1) acc)))
|
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.
| #PureBasic | PureBasic | Structure PlotData
x.i
y.f
EndStructure
Global i, x, y.f, max_x, max_y, min_x = #MAXLONG, min_y = Infinity()
Define count = (?serie_y - ?serie_x) / SizeOf(Integer) - 1
Global Dim MyData.PlotData(count)
Restore serie_x
For i = 0 To count
Read.i x
MyData(i)\x = x
If x > max_x: max_x = x: EndIf
If x < min_x: min_x = x: EndIf
Next
Restore serie_y
For i = 0 To count
Read.f y
MyData(i)\y = y
If y > max_y: max_y = y: EndIf
If y < min_y: min_y = y: EndIf
Next
Procedure UpdatePlot(Win, w, h)
Static gblm = 20, gtrm = 5 ;graph's bottom-left and top-right margin
Protected count = ArraySize(MyData())
If w > gblm And h > gblm And count > 0
SetWindowTitle(Win, "PureBasic Plot " + Str(w) + "x" + Str(h))
Protected gw = w - gblm, gh = h - gblm ;graph's width and height
Protected i, yf.f, xf.f
yf = (gh - gtrm) / max_y
xf = (gw - gtrm) / max_x
CreateImage(0, w, h)
Protected OutputID = ImageOutput(0)
StartDrawing(OutputID)
DrawingMode(#PB_2DDrawing_Transparent)
;- Draw grid
For i = 0 To count
y = gh - max_y * i / count * yf
LineXY(gblm, y, w - gtrm, y, $467E3E)
; Y-scale
DrawText(1, y - 5, RSet(StrD(i / count * max_y, 1), 5))
x = gblm + max_x * i / count * xf
y = gh
; X-Scale
LineXY(x, y, x, gtrm, $467E3E)
If i: DrawText(x - 5, y + 2, Str(i)): EndIf
Next
;- Draw curve
Protected ox = gblm, oy = gh, x, y
For i = 0 To count
x = gblm + MyData(i)\x * xf
y = gh - MyData(i)\y * yf
LineXY(ox, oy, x, y, $0133EE)
ox = x: oy = y
Next
StopDrawing()
ImageGadget(0, 0, 0, w, h, ImageID(0))
EndIf
EndProcedure
Define Win = OpenWindow(#PB_Any, 0, 0, 600, 400,"", #PB_Window_SystemMenu | #PB_Window_SizeGadget)
If Win
SmartWindowRefresh(Win, 1)
UpdatePlot(Win, WindowWidth(Win), WindowHeight(Win))
Repeat
Define event = WaitWindowEvent()
Select event
Case #PB_Event_SizeWindow
UpdatePlot(Win, WindowWidth(Win), WindowHeight(Win))
EndSelect
Until event = #PB_Event_CloseWindow
; Save the plot if the user wants to
If MessageRequester("Question", "Save it?", #PB_MessageRequester_YesNo) = #PB_MessageRequester_Yes
Define File$=SaveFileRequester("Save as", "PB.png", "PNG (*.png)|*.png", 0)
UsePNGImageEncoder()
SaveImage(0, File$, #PB_ImagePlugin_PNG)
EndIf
EndIf
DataSection
serie_x:
Data.i 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
serie_y:
Data.f 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0
EndDataSection |
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
| #Pascal | Pascal | {
package Point;
use Class::Spiffy -base;
use Clone qw(clone);
sub _print {
my %self = %{shift()};
while (my ($k,$v) = each %self) {
print "$k: $v\n";
}
}
sub members {
no strict;
grep {
1 == length and defined *$_{CODE}
} keys %{*{__PACKAGE__."\::"}};
}
sub new {
my $class = shift;
my %param = @_;
$param{$_} = 0 for grep {!defined $param{$_}} members;
bless \%param, $class;
}
sub copy_constructor {
clone shift;
}
sub copy_assignment {
my $self = shift;
my $from = shift;
$self->$_($from->$_) for $from->members;
}
field 'x';
field 'y';
}
{
package Circle;
use base qw(Point);
field 'r';
}
{
package main;
$_->_print, print "\n" for (
Point->new,
Point->new(x => 2),
Point->new(y => 3),
Point->new(x => 8, y => -5),
);
my $p1 = Point->new(x => 8, y => -5);
my $p2 = $p1->copy_constructor;
print "we are really different objects, not just references ".
"to the same instance\n" unless \$p1 eq \$p2;
# accessors autogenerated
$p1->x(1);
$p1->y(2);
print $p1->x, "\n";
print $p1->y, "\n";
$p2->copy_assignment($p1);
print $p2->x, "\n";
print $p2->y, "\n";
print "we now have the same values, but we are still ".
"different objects\n" unless \$p1 eq \$p2;
$_->_print, print "\n" for (
Circle->new,
Circle->new(x => 1),
Circle->new(y => 2),
Circle->new(r => 3),
Circle->new(x => 4, y => 5),
Circle->new(x => 6, r => 7),
Circle->new(y => 8, r => 9),
Circle->new(x => 1, y => 2, r => 3),
);
my $c = Circle->new(r => 4);
print $c->r, "\n"; # accessor autogenerated
} |
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.
| #Java | Java | import java.math.BigInteger;
public class PopCount {
public static void main(String[] args) {
{ // with int
System.out.print("32-bit integer: ");
int n = 1;
for (int i = 0; i < 20; i++) {
System.out.printf("%d ", Integer.bitCount(n));
n *= 3;
}
System.out.println();
}
{ // with long
System.out.print("64-bit integer: ");
long n = 1;
for (int i = 0; i < 30; i++) {
System.out.printf("%d ", Long.bitCount(n));
n *= 3;
}
System.out.println();
}
{ // with BigInteger
System.out.print("big integer : ");
BigInteger n = BigInteger.ONE;
BigInteger three = BigInteger.valueOf(3);
for (int i = 0; i < 30; i++) {
System.out.printf("%d ", n.bitCount());
n = n.multiply(three);
}
System.out.println();
}
int[] od = new int[30];
int ne = 0, no = 0;
System.out.print("evil : ");
for (int n = 0; ne+no < 60; n++) {
if ((Integer.bitCount(n) & 1) == 0) {
if (ne < 30) {
System.out.printf("%d ", n);
ne++;
}
} else {
if (no < 30) {
od[no++] = n;
}
}
}
System.out.println();
System.out.print("odious : ");
for (int n : od) {
System.out.printf("%d ", n);
}
System.out.println();
}
} |
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
| #Tcl | Tcl | # poldiv - Divide two polynomials n and d.
# Result is a list of two polynomials, q and r, where n = qd + r
# and the degree of r is less than the degree of b.
# Polynomials are represented as lists, where element 0 is the
# x**0 coefficient, element 1 is the x**1 coefficient, and so on.
proc poldiv {a b} {
# Toss out leading zero coefficients efficiently
while {[lindex $a end] == 0} {set a [lrange $a[set a {}] 0 end-1]}
while {[lindex $b end] == 0} {set b [lrange $b[set b {}] 0 end-1]}
if {[llength $a] < [llength $b]} {
return [list 0 $a]
}
# Rearrange the terms to put highest powers first
set n [lreverse $a]
set d [lreverse $b]
# Carry out classical long division, accumulating quotient coefficients
# in q, and replacing n with the remainder.
set q {}
while {[llength $n] >= [llength $d]} {
set qd [expr {[lindex $n 0] / [lindex $d 0]}]
set i 0
foreach nd [lrange $n 0 [expr {[llength $d] - 1}]] dd $d {
lset n $i [expr {$nd - $qd * $dd}]
incr i
}
lappend q $qd
set n [lrange $n 1 end]
}
# Return quotient and remainder, constant term first
return [list [lreverse $q] [lreverse $n]]
}
# Demonstration
lassign [poldiv {-42. 0. -12. 1.} {-3. 1. 0. 0.}] Q R
puts [list Q = $Q]
puts [list 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.
| #Ruby | Ruby | require 'matrix'
def regress x, y, degree
x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_r } }
mx = Matrix[*x_data]
my = Matrix.column_vector(y)
((mx.t * mx).inv * mx.t * my).transpose.to_a[0].map(&:to_f)
end |
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.
| #Logo | Logo | to powerset :set
if empty? :set [output [[]]]
localmake "rest powerset butfirst :set
output sentence map [sentence first :set ?] :rest :rest
end
show powerset [1 2 3]
[[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []] |
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
| #F.23 | F# | open NUnit.Framework
open FsUnit
let inline isPrime n = not ({uint64 2..uint64 (sqrt (double n))} |> Seq.exists (fun (i:uint64) -> uint64 n % i = uint64 0))
[<Test>]
let ``Validate that 2 is prime`` () =
isPrime 2 |> should equal true
[<Test>]
let ``Validate that 4 is not prime`` () =
isPrime 4 |> should equal false
[<Test>]
let ``Validate that 3 is prime`` () =
isPrime 3 |> should equal true
[<Test>]
let ``Validate that 9 is not prime`` () =
isPrime 9 |> should equal false
[<Test>]
let ``Validate that 5 is prime`` () =
isPrime 5 |> should equal true
[<Test>]
let ``Validate that 277 is prime`` () =
isPrime 277 |> should equal 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
| #PARI.2FGP | PARI/GP | priceLookup=[6,11,16,21,26,31,41,46,51,56,61,66,71,76,81,86,91,96,101];
priceReplace=[10,18,26,32,38,44,50,54,58,62,66,70,74,78,82,86,90,94,98,100];
pf(x)={
x*=100;
for(i=1,19,
if(x<priceLookup[i], return(priceReplace[i]))
);
"nasal demons"
}; |
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
| #Quackery | Quackery | [ factors -1 split drop ] is properdivisors ( n --> [ )
10 times [ i^ 1+ properdivisors echo cr ]
0 0
20000 times
[ i^ 1+ properdivisors size
2dup < iff
[ dip [ 2drop i^ 1+ ] ]
else drop ]
swap echo say " has "
echo say " proper divisors." cr |
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.
| #Rust | Rust | use std::collections::BinaryHeap;
use std::cmp::Ordering;
use std::borrow::Cow;
#[derive(Eq, PartialEq)]
struct Item<'a> {
priority: usize,
task: Cow<'a, str>, // Takes either borrowed or owned string
}
impl<'a> Item<'a> {
fn new<T>(p: usize, t: T) -> Self
where T: Into<Cow<'a, str>>
{
Item {
priority: p,
task: t.into(),
}
}
}
// Manually implpement Ord so we have a min heap
impl<'a> Ord for Item<'a> {
fn cmp(&self, other: &Self) -> Ordering {
other.priority.cmp(&self.priority)
}
}
// PartialOrd is required by Ord
impl<'a> PartialOrd for Item<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn main() {
let mut queue = BinaryHeap::with_capacity(5);
queue.push(Item::new(3, "Clear drains"));
queue.push(Item::new(4, "Feed cat"));
queue.push(Item::new(5, "Make tea"));
queue.push(Item::new(1, "Solve RC tasks"));
queue.push(Item::new(2, "Tax return"));
for item in queue {
println!("{}", item.task);
}
} |
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
| #Lingo | Lingo | -- Returns list of prime factors for given number.
-- To overcome the limits of integers (signed 32-bit in Lingo),
-- the number can be specified as float (which works up to 2^53).
-- For the same reason, values in returned list are floats, not integers.
on getPrimeFactors (n)
f = []
f.sort()
c = sqrt(n)
i = 1.0
repeat while TRUE
i=i+1
if i>c then exit repeat
check = n/i
if bitOr(check,0)=check then
f.add(i)
n = check
c = sqrt(n)
i = 1.0
end if
end repeat
f.add(n)
return f
end |
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.
| #Python | Python | >>> 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]
>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('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
| #Perl | Perl | {
package Point;
use Class::Spiffy -base;
use Clone qw(clone);
sub _print {
my %self = %{shift()};
while (my ($k,$v) = each %self) {
print "$k: $v\n";
}
}
sub members {
no strict;
grep {
1 == length and defined *$_{CODE}
} keys %{*{__PACKAGE__."\::"}};
}
sub new {
my $class = shift;
my %param = @_;
$param{$_} = 0 for grep {!defined $param{$_}} members;
bless \%param, $class;
}
sub copy_constructor {
clone shift;
}
sub copy_assignment {
my $self = shift;
my $from = shift;
$self->$_($from->$_) for $from->members;
}
field 'x';
field 'y';
}
{
package Circle;
use base qw(Point);
field 'r';
}
{
package main;
$_->_print, print "\n" for (
Point->new,
Point->new(x => 2),
Point->new(y => 3),
Point->new(x => 8, y => -5),
);
my $p1 = Point->new(x => 8, y => -5);
my $p2 = $p1->copy_constructor;
print "we are really different objects, not just references ".
"to the same instance\n" unless \$p1 eq \$p2;
# accessors autogenerated
$p1->x(1);
$p1->y(2);
print $p1->x, "\n";
print $p1->y, "\n";
$p2->copy_assignment($p1);
print $p2->x, "\n";
print $p2->y, "\n";
print "we now have the same values, but we are still ".
"different objects\n" unless \$p1 eq \$p2;
$_->_print, print "\n" for (
Circle->new,
Circle->new(x => 1),
Circle->new(y => 2),
Circle->new(r => 3),
Circle->new(x => 4, y => 5),
Circle->new(x => 6, r => 7),
Circle->new(y => 8, r => 9),
Circle->new(x => 1, y => 2, r => 3),
);
my $c = Circle->new(r => 4);
print $c->r, "\n"; # accessor autogenerated
} |
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.
| #JavaScript | JavaScript | (() => {
'use strict';
// populationCount :: Int -> Int
const populationCount = n =>
// The number of non-zero bits in the binary
// representation of the integer n.
sum(unfoldr(
x => 0 < x ? (
Just(Tuple(x % 2)(Math.floor(x / 2)))
) : Nothing()
)(n));
// ----------------------- TEST ------------------------
// main :: IO ()
const main = () => {
const [evens, odds] = Array.from(
partition(compose(even, populationCount))(
enumFromTo(0)(59)
)
);
return [
'Population counts of the first 30 powers of three:',
` [${enumFromTo(0)(29).map(
compose(populationCount, raise(3))
).join(',')}]`,
"\nFirst thirty 'evil' numbers:",
` [${[evens.join(',')]}]`,
"\nFirst thirty 'odious' numbers:",
` [${odds.join(',')}]`
].join('\n');
};
// ----------------- GENERIC FUNCTIONS -----------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => !isNaN(m) ? (
Array.from({
length: 1 + n - m
}, (_, i) => m + i)
) : enumFromTo_(m)(n);
// even :: Int -> Bool
const even = n =>
// True if n is an even number.
0 === n % 2;
// partition :: (a -> Bool) -> [a] -> ([a], [a])
const partition = p =>
// A tuple of two lists - those elements in
// xs which match p, and those which don't.
xs => ([...xs]).reduce(
(a, x) =>
p(x) ? (
Tuple(a[0].concat(x))(a[1])
) : Tuple(a[0])(a[1].concat(x)),
Tuple([])([])
);
// raise :: Num -> Int -> Num
const raise = x =>
// X to the power of n.
n => Math.pow(x, n);
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
// unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
const unfoldr = f =>
v => {
const xs = [];
let xr = [v, v];
while (true) {
const mb = f(xr[1]);
if (mb.Nothing) {
return xs
} else {
xr = mb.Just;
xs.push(xr[0])
}
}
};
// ---
return main();
})(); |
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
| #Ursala | Ursala | #import std
#import flo
polydiv =
zeroid~-l~~; leql?rlX\~&NlX ^H\(@rNrNSPXlHDlS |\ :/0.) @NlX //=> ?(
@lrrPX ==!| zipp0.; @x not zeroid+ ==@h->hr ~&t,
(^lryPX/~&lrrl2C minus^*p/~&rrr times*lrlPD)^/div@bzPrrPlXO ~&,
@r ^|\~& ~&i&& :/0.) |
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
| #VBA | VBA | Option Base 1
Function degree(p As Variant)
For i = UBound(p) To 1 Step -1
If p(i) <> 0 Then
degree = i
Exit Function
End If
Next i
degree = -1
End Function
Function poly_div(ByVal n As Variant, ByVal d As Variant) As Variant
If UBound(d) < UBound(n) Then
ReDim Preserve d(UBound(n))
End If
Dim dn As Integer: dn = degree(n)
Dim dd As Integer: dd = degree(d)
If dd < 0 Then
poly_div = CVErr(xlErrDiv0)
Exit Function
End If
Dim quot() As Integer
ReDim quot(dn)
Do While dn >= dd
Dim k As Integer: k = dn - dd
Dim qk As Integer: qk = n(dn) / d(dd)
quot(k + 1) = qk
Dim d2() As Variant
d2 = d
ReDim Preserve d2(UBound(d) - k)
For i = 1 To UBound(d2)
n(UBound(n) + 1 - i) = n(UBound(n) + 1 - i) - d2(UBound(d2) + 1 - i) * qk
Next i
dn = degree(n)
Loop
poly_div = Array(quot, n) '-- (n is now the remainder)
End Function
Function poly(si As Variant) As String
'-- display helper
Dim r As String
For t = UBound(si) To 1 Step -1
Dim sit As Integer: sit = si(t)
If sit <> 0 Then
If sit = 1 And t > 1 Then
r = r & IIf(r = "", "", " + ")
Else
If sit = -1 And t > 1 Then
r = r & IIf(r = "", "-", " - ")
Else
If r <> "" Then
r = r & IIf(sit < 0, " - ", " + ")
sit = Abs(sit)
End If
r = r & CStr(sit)
End If
End If
r = r & IIf(t > 1, "x" & IIf(t > 2, t - 1, ""), "")
End If
Next t
If r = "" Then r = "0"
poly = r
End Function
Function polyn(s As Variant) As String
Dim t() As String
ReDim t(2 * UBound(s))
For i = 1 To 2 * UBound(s) Step 2
t(i) = poly(s((i + 1) / 2))
Next i
t(1) = String$(45 - Len(t(1)) - Len(t(3)), " ") & t(1)
t(2) = "/"
t(4) = "="
t(6) = "rem"
polyn = Join(t, " ")
End Function
Public Sub main()
Dim tests(7) As Variant
tests(1) = Array(Array(-42, 0, -12, 1), Array(-3, 1))
tests(2) = Array(Array(-3, 1), Array(-42, 0, -12, 1))
tests(3) = Array(Array(-42, 0, -12, 1), Array(-3, 1, 1))
tests(4) = Array(Array(2, 3, 1), Array(1, 1))
tests(5) = Array(Array(3, 5, 6, -4, 1), Array(1, 2, 1))
tests(6) = Array(Array(3, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 1), Array(1, 0, 0, 5, 0, 0, 0, 1))
tests(7) = Array(Array(-56, 87, -94, -55, 22, -7), Array(2, 0, 1))
Dim num As Variant, denom As Variant, quot As Variant, rmdr As Variant
For i = 1 To 7
num = tests(i)(1)
denom = tests(i)(2)
tmp = poly_div(num, denom)
quot = tmp(1)
rmdr = tmp(2)
Debug.Print polyn(Array(num, denom, quot, rmdr))
Next i
End Sub |
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.
| #Scala | Scala | object PolynomialRegression extends App {
private def xy = Seq(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321).zipWithIndex.map(_.swap)
private def polyRegression(xy: Seq[(Int, Int)]): Unit = {
val r = xy.indices
def average[U](ts: Iterable[U])(implicit num: Numeric[U]) = num.toDouble(ts.sum) / ts.size
def x3m: Double = average(r.map(a => a * a * a))
def x4m: Double = average(r.map(a => a * a * a * a))
def x2ym = xy.reduce((a, x) => (a._1 + x._1 * x._1 * x._2, 0))._1.toDouble / xy.size
def xym = xy.reduce((a, x) => (a._1 + x._1 * x._2, 0))._1.toDouble / xy.size
val x2m: Double = average(r.map(a => a * a))
val (xm, ym) = (average(xy.map(_._1)), average(xy.map(_._2)))
val (sxx, sxy) = (x2m - xm * xm, xym - xm * ym)
val sxx2: Double = x3m - xm * x2m
val sx2x2: Double = x4m - x2m * x2m
val sx2y: Double = x2ym - x2m * ym
val c: Double = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
val b: Double = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
val a: Double = ym - b * xm - c * x2m
def abc(xx: Int) = a + b * xx + c * xx * xx
println(s"y = $a + ${b}x + ${c}x^2")
println(" Input Approximation")
println(" x y y1")
xy.foreach {el => println(f"${el._1}%2d ${el._2}%3d ${abc(el._1)}%5.1f")}
}
polyRegression(xy)
} |
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.
| #Logtalk | Logtalk | :- object(set).
:- public(powerset/2).
powerset(Set, PowerSet) :-
reverse(Set, RSet),
powerset_1(RSet, [[]], PowerSet).
powerset_1([], PowerSet, PowerSet).
powerset_1([X| Xs], Yss0, Yss) :-
powerset_2(Yss0, X, Yss1),
powerset_1(Xs, Yss1, Yss).
powerset_2([], _, []).
powerset_2([Zs| Zss], X, [Zs, [X| Zs]| Yss]) :-
powerset_2(Zss, X, Yss).
reverse(List, Reversed) :-
reverse(List, [], Reversed).
reverse([], Reversed, Reversed).
reverse([Head| Tail], List, Reversed) :-
reverse(Tail, [Head| List], Reversed).
:- end_object. |
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
| #Factor | Factor | USING: combinators kernel math math.functions math.ranges sequences ;
: prime? ( n -- ? )
{
{ [ dup 2 < ] [ drop f ] }
{ [ dup even? ] [ 2 = ] }
[ 3 over sqrt 2 <range> [ mod 0 > ] with all? ]
} cond ; |
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
| #Pascal | Pascal | Program PriceFraction(output);
const
limit: array [1..20] of real =
(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);
price: array [1..20] of real =
(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.81, 0.86, 0.90, 0.94, 0.98, 1.00);
var
cost: real;
i, j: integer;
begin
randomize;
for i := 1 to 10 do
begin
cost := random;
j := high(limit);
while cost < limit[j] do
dec(j);
writeln (cost:6:4, ' -> ', price[j+1]:4:2);
end;
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
| #R | R | # Proper divisors. 12/10/16 aev
require(numbers);
V <- sapply(1:20000, Sigma, k = 0, proper = TRUE); ind <- which(V==max(V));
cat(" *** max number of divisors:", max(V), "\n"," *** for the following indices:",ind, "\n"); |
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.
| #SAS | SAS | %macro HeapInit(size=1000,nchar=20);
do;
_len = 0;
_size = &size;
array _times(&size) _temporary_ ;
array _kinds(&size) $ &nchar _temporary_;
drop _size _len;
end;
%mend;
%macro HeapSwapItem(index1, index2);
do;
_tempN = _times[&index1]; _times[&index1] = _times[&index2]; _times[&index2] = _tempN;
_tempC = _kinds[&index1]; _kinds[&index1] = _kinds[&index2]; _kinds[&index2]= _tempC;
drop _tempN _tempC;
end;
%mend;
%macro HeapEmpty;
(_len=0)
%mend;
%macro HeapCompare(index1, index2);
(_times[&index1] < _times[&index2])
%mend;
%macro HeapSiftdown(index);
do;
_parent = &index;
_done = 0;
do while (_parent*2 <= _len & ^_done);
_child = _parent*2;
if (_child+1 <= _len and %HeapCompare(_child+1,_child)) then
_child = _child + 1;
if %HeapCompare(_child,_parent) then do;
%HeapSwapItem(_child,_parent);
_parent = _child;
end;
else _done = 1;
end;
drop _done _parent _child;
end;
%mend;
%macro HeapSiftup(index);
do;
_child = &index;
_done = 0;
do while(_child>1 and ^_done);
_parent = floor(_child/2);
if %HeapCompare(_parent,_child) then
_done = 1;
else do;
%HeapSwapItem(_child,_parent);
_tempN = _child;
_child = _parent;
_parent = _tempN;
end;
end;
drop _parent _child _done _tempN;
end;
%mend;
%macro HeapPush(time, kind);
do;
if _len >= _size then do;
put "ERROR: exceeded size of heap. Consider changing size argument to %HeapInit.";
stop;
end;
_len = _len + 1;
_times[_len] = &time;
_kinds[_len] = &kind;
%HeapSiftup(_len);
end;
%mend;
%macro HeapPop;
do;
_len = _len - 1;
if (_len>0) then do;
_times[1] = _times[_len+1];
_kinds[1] = _kinds[_len+1];
%HeapSiftdown(1);
end;
end;
%mend;
%macro HeapPeek;
time = _times[1];
kind = _kinds[1];
put time kind;
%mend;
data _null_;
%HeapInit;
%HeapPush(3, "Clear drains");
%HeapPush(4, "Feed cat");
%HeapPush(5, "Make tea");
%HeapPush(1, "Solve RC tasks");
%HeapPush(2, "Tax return");
do while(^%HeapEmpty);
%HeapPeek;
%HeapPop;
end;
run; |
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
| #Logo | Logo | to decompose :n [:p 2]
if :p*:p > :n [output (list :n)]
if less? 0 modulo :n :p [output (decompose :n bitor 1 :p+1)]
output fput :p (decompose :n/:p :p)
end |
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.
| #R | R | x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
y <- c(2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0) |
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.
| #Racket | Racket | #lang racket
(require plot)
(define x (build-list 10 values))
(define y (list 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0))
(plot-new-window? #t)
(plot (points (map vector x y))) |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Phix | Phix | type point(object o)
return sequence(o) and length(o)=2 and atom(o[1]) and atom(o[2])
end type
function new_point(atom x=0, atom y=0)
return {x,y}
end function
type circle(object o)
return sequence(o) and length(o)=2 and point(o[1]) and atom(o[2])
end type
function new_circle(object x=0, atom y=0, atom r=0)
if point(x) then
r = y -- assume r got passed in y
return {x,r} -- {point,r}
end if
return {{x,y},r} -- {point,r}
-- (or {new_point(x,y),r} if you prefer)
end function
point p = new_point(4,5)
circle c1 = new_circle(p,6),
c2 = new_circle(4,5,6}
?c1
?c2
|
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.
| #jq | jq | def popcount:
def bin: recurse( if . == 0 then empty else ./2 | floor end ) % 2;
[bin] | add;
def firstN(count; condition):
if count > 0 then
if condition then ., (1+.| firstN(count-1; condition))
else (1+.) | firstN(count; condition)
end
else empty
end;
def task:
def pow(n): . as $m | reduce range(0;n) as $i (1; . * $m);
"The pop count of the first thirty powers of 3:",
[range(0;30) as $n | 3 | pow($n) | popcount],
"The first thirty evil numbers:",
[0 | firstN(30; (popcount % 2) == 0)],
"The first thirty odious numbers:",
[0 | firstN(30; (popcount % 2) == 1)]
;
task |
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
| #Wren | Wren | import "/dynamic" for Tuple
var Solution = Tuple.create("Solution", ["quotient", "remainder"])
var polyDegree = Fn.new { |p|
for (i in p.count-1..0) if (p[i] != 0) return i
return -2.pow(31)
}
var polyShiftRight = Fn.new { |p, places|
if (places <= 0) return p
var pd = polyDegree.call(p)
if (pd + places >= p.count) {
Fiber.abort("The number of places to be shifted is too large.")
}
var d = p.toList
for (i in pd..0) {
d[i + places] = d[i]
d[i] = 0
}
return d
}
var polyMultiply = Fn.new { |p, m|
for (i in 0...p.count) p[i] = p[i] * m
}
var polySubtract = Fn.new { |p, s|
for (i in 0...p.count) p[i] = p[i] - s[i]
}
var polyLongDiv = Fn.new { |n, d|
if (n.count != d.count) {
Fiber.abort("Numerator and denominator vectors must have the same size")
}
var nd = polyDegree.call(n)
var dd = polyDegree.call(d)
if (dd < 0) {
Fiber.abort("Divisor must have at least one one-zero coefficient")
}
if (nd < dd) {
Fiber.abort("The degree of the divisor cannot exceed that of the numerator")
}
var n2 = n.toList
var q = List.filled(n.count, 0)
while (nd >= dd) {
var d2 = polyShiftRight.call(d, nd - dd)
q[nd - dd] = n2[nd] / d2[nd]
polyMultiply.call(d2, q[nd - dd])
polySubtract.call(n2, d2)
nd = polyDegree.call(n2)
}
return Solution.new(q, n2)
}
var polyShow = Fn.new { |p|
var pd = polyDegree.call(p)
for (i in pd..0) {
var coeff = p[i]
if (coeff != 0) {
System.write(
(coeff == 1) ? ((i < pd) ? " + " : "") :
(coeff == -1) ? ((i < pd) ? " - " : "-") :
(coeff < 0) ? ((i < pd) ? " - %(-coeff)" : "%(coeff)") :
((i < pd) ? " + %( coeff)" : "%(coeff)")
)
if (i > 1) {
System.write("x^%(i)")
} else if (i == 1) {
System.write("x")
}
}
}
System.print()
}
var n = [-42, 0, -12, 1]
var d = [ -3, 1, 0, 0]
System.write("Numerator : ")
polyShow.call(n)
System.write("Denominator : ")
polyShow.call(d)
System.print("-------------------------------------")
var sol = polyLongDiv.call(n, d)
System.write("Quotient : ")
polyShow.call(sol.quotient)
System.write("Remainder : ")
polyShow.call(sol.remainder) |
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.
| #Sidef | Sidef | func regress(x, y, degree) {
var A = Matrix.build(x.len, degree+1, {|i,j|
x[i]**j
})
var B = Matrix.column_vector(y...)
((A.transpose * A)**(-1) * A.transpose * B).transpose[0]
}
func poly(x) {
3*x**2 + 2*x + 1
}
var coeff = regress(
10.of { _ },
10.of { poly(_) },
2
)
say coeff |
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.
| #Lua | Lua |
--returns the powerset of s, out of order.
function powerset(s, start)
start = start or 1
if(start > #s) then return {{}} end
local ret = powerset(s, start + 1)
for i = 1, #ret do
ret[#ret + 1] = {s[start], unpack(ret[i])}
end
return ret
end
--non-recurse implementation
function powerset(s)
local t = {{}}
for i = 1, #s do
for j = 1, #t do
t[#t+1] = {s[i],unpack(t[j])}
end
end
return t
end
--alternative, copied from the Python implementation
function powerset2(s)
local ret = {{}}
for i = 1, #s do
local k = #ret
for j = 1, k do
ret[k + j] = {s[i], unpack(ret[j])}
end
end
return ret
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
| #FALSE | FALSE | [0\$2=$[@~@@]?~[$$2>\1&&[\~\
3[\$@$@1+\$*>][\$@$@$@$@\/*=[%\~\$]?2+]#%
]?]?%]p: |
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
| #Perl | Perl | my @table = map [ /([\d\.]+)/g ], split "\n", <<'TBL';
>= 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
TBL
sub convert {
my $money = shift;
for (@table) {
return $_->[2] if $_->[0] <= $money and $_->[1] > $money
}
die "Can't find currency conversion for $money. Counterfeit?"
}
# try it out
for (1 .. 10) {
my $m = rand(1);
printf "%.3f -> %g\n", $m, convert($m);
}
|
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
| #Racket | Racket | #lang racket
(require math)
(define (proper-divisors n) (drop-right (divisors n) 1))
(for ([n (in-range 1 (add1 10))])
(printf "proper divisors of: ~a\t~a\n" n (proper-divisors n)))
(define most-under-20000
(for/fold ([best '(1)]) ([n (in-range 2 (add1 20000))])
(define divs (proper-divisors n))
(if (< (length (cdr best)) (length divs)) (cons n divs) best)))
(printf "~a has ~a proper divisors\n"
(car most-under-20000) (length (cdr most-under-20000))) |
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.
| #Scala | Scala | import scala.collection.mutable.PriorityQueue
case class Task(prio:Int, text:String) extends Ordered[Task] {
def compare(that: Task)=that.prio compare this.prio
}
//test
var q=PriorityQueue[Task]() ++ Seq(Task(3, "Clear drains"), Task(4, "Feed cat"),
Task(5, "Make tea"), Task(1, "Solve RC tasks"), Task(2, "Tax return"))
while(q.nonEmpty) println(q dequeue) |
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
| #Lua | Lua | function PrimeDecomposition( n )
local f = {}
if IsPrime( n ) then
f[1] = n
return f
end
local i = 2
repeat
while n % i == 0 do
f[#f+1] = i
n = n / i
end
repeat
i = i + 1
until IsPrime( i )
until n == 1
return f
end |
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.
| #Raku | Raku | use SVG;
use SVG::Plot;
my @x = 0..9;
my @y = (2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0);
say SVG.serialize: SVG::Plot.new(
width => 512,
height => 512,
x => @x,
x-tick-step => { 1 },
min-y-axis => 0,
values => [@y,],
title => 'Coordinate Pairs',
).plot(:lines); |
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
| #PHP | PHP |
class Point
{
protected $_x;
protected $_y;
public function __construct()
{
switch( func_num_args() )
{
case 1:
$point = func_get_arg( 0 );
$this->setFromPoint( $point );
break;
case 2:
$x = func_get_arg( 0 );
$y = func_get_arg( 1 );
$this->setX( $x );
$this->setY( $y );
break;
default:
throw new InvalidArgumentException( 'expecting one (Point) argument or two (numeric x and y) arguments' );
}
}
public function setFromPoint( Point $point )
{
$this->setX( $point->getX() );
$this->setY( $point->getY() );
}
public function getX()
{
return $this->_x;
}
public function setX( $x )
{
if( !is_numeric( $x ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_x = (float) $x;
}
public function getY()
{
return $this->_y;
}
public function setY( $y )
{
if( !is_numeric( $y ) )
{
throw new InvalidArgumentException( 'expecting numeric value' );
}
$this->_y = (float) $y;
}
public function output()
{
echo $this->__toString();
}
public function __toString()
{
return 'Point [x:' . $this->_x . ',y:' . $this->_y . ']';
}
}
|
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.
| #Julia | Julia | println("First 3 ^ i, up to 29 pop. counts: ", join((count_ones(3 ^ n) for n in 0:29), ", "))
println("Evil numbers: ", join(filter(x -> iseven(count_ones(x)), 0:59), ", "))
println("Odious numbers: ", join(filter(x -> isodd(count_ones(x)), 0:59), ", ")) |
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
| #zkl | zkl | fcn polyLongDivision(a,b){ // (a0 + a1x + a2x^2 + a3x^3 ...)
_assert_(degree(b)>=0,"degree(%s) < 0".fmt(b));
q:=List.createLong(a.len(),0.0);
while((ad:=degree(a)) >= (bd:=degree(b))){
z,d,m := ad-bd, List.createLong(z,0.0).extend(b), a[ad]/b[bd];;
q[z]=m;
d,a = d.apply('*(m)), a.zipWith('-,d);
}
return(q,a); // may have trailing zero elements
}
fcn degree(v){ // -1,0,..len(v)-1, -1 if v==0
v.len() - v.copy().reverse().filter1n('!=(0)) - 1;
}
fcn polyString(terms){ // (a0,a1,a2...)-->"a0 + a1x + a2x^2 ..."
str:=[0..].zipWith('wrap(n,a){ if(a) "+ %sx^%s ".fmt(a,n) else "" },terms)
.pump(String)
.replace("x^0 "," ").replace(" 1x"," x").replace("x^1 ","x ")
.replace("+ -", "- ");
if(not str) return(" "); // all zeros
if(str[0]=="+") str[1,*]; // leave leading space
else String("-",str[2,*]);
} |
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.
| #Stata | Stata | . clear
. input x y
0 1
1 6
2 17
3 34
4 57
5 86
6 121
7 162
8 209
9 262
10 321
end
. regress y c.x##c.x
Source | SS df MS Number of obs = 11
-------------+---------------------------------- F(2, 8) = .
Model | 120362 2 60181 Prob > F = .
Residual | 0 8 0 R-squared = 1.0000
-------------+---------------------------------- Adj R-squared = 1.0000
Total | 120362 10 12036.2 Root MSE = 0
------------------------------------------------------------------------------
y | Coef. Std. Err. t P>|t| [95% Conf. Interval]
-------------+----------------------------------------------------------------
x | 2 . . . . .
|
c.x#c.x | 3 . . . . .
|
_cons | 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.
| #M4 | M4 | define(`for',
`ifelse($#, 0, ``$0'',
eval($2 <= $3), 1,
`pushdef(`$1', `$2')$4`'popdef(
`$1')$0(`$1', incr($2), $3, `$4')')')dnl
define(`nth',
`ifelse($1, 1, $2,
`nth(decr($1), shift(shift($@)))')')dnl
define(`range',
`for(`x', eval($1 + 2), eval($2 + 2),
`nth(x, $@)`'ifelse(x, eval($2+2), `', `,')')')dnl
define(`powerpart',
`{range(2, incr($1), $@)}`'ifelse(incr($1), $#, `',
`for(`x', eval($1+2), $#,
`,powerpart(incr($1), ifelse(
eval(2 <= ($1 + 1)), 1,
`range(2,incr($1), $@), ')`'nth(x, $@)`'ifelse(
eval((x + 1) <= $#),1,`,range(incr(x), $#, $@)'))')')')dnl
define(`powerset',
`{powerpart(0, substr(`$1', 1, eval(len(`$1') - 2)))}')dnl
dnl
powerset(`{a,b,c}') |
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
| #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION ISPRIME(n AS INTEGER) AS INTEGER
IF n = 2 THEN
RETURN TRUE
ELSEIF n <= 1 ORELSE n MOD 2 = 0 THEN
RETURN FALSE
ELSE
FOR DIM i = 3 TO SQR(n) STEP 2
IF n MOD i = 0 THEN
RETURN FALSE
END IF
NEXT
RETURN TRUE
END IF
END FUNCTION
FUNCTION ISPRIME2(N AS INTEGER) AS INTEGER
IF N <= 1 THEN RETURN FALSE
DIM I AS INTEGER = 2
WHILE I * I <= N
IF N MOD I = 0 THEN
RETURN FALSE
END IF
I = I + 1
WEND
RETURN TRUE
END FUNCTION
' Test and display primes 1 .. 50
DIM n AS INTEGER
FOR n = 1 TO 50
IF ISPRIME(n) THEN
PRINT n, " ";
END IF
NEXT
PAUSE |
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
| #Phix | Phix | with javascript_semantics
constant TBL=split("""
>= 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""",'\n')
sequence limits = {0},
prices = {-1}
atom pl,lt,plt=0,price
for i=1 to length(TBL) do
{pl,lt,price} = scanf(TBL[i],">= %.2f < %.2f := %.2f")[1]
assert(pl==plt)
plt = lt
limits = append(limits,lt)
prices = append(prices,price)
end for
function price_fix(atom p)
for i=1 to length(limits) do
if p<limits[i] then
return prices[i]
end if
end for
return -1
end function
for i=-1 to 101 do
printf(1, "%5.2f %5.2f\n", {i/100,price_fix(i/100)})
end for
|
http://rosettacode.org/wiki/Proper_divisors | Proper divisors | The proper divisors of a positive integer N are those numbers, other than N itself, that divide N without remainder.
For N > 1 they will always include 1, but for N == 1 there are no proper divisors.
Examples
The proper divisors of 6 are 1, 2, and 3.
The proper divisors of 100 are 1, 2, 4, 5, 10, 20, 25, and 50.
Task
Create a routine to generate all the proper divisors of a number.
use it to show the proper divisors of the numbers 1 to 10 inclusive.
Find a number in the range 1 to 20,000 with the most proper divisors. Show the number and just the count of how many proper divisors it has.
Show all output here.
Related tasks
Amicable pairs
Abundant, deficient and perfect number classifications
Aliquot sequence classifications
Factors of an integer
Prime decomposition
| #Raku | Raku | sub propdiv (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d }
}
@l
}
put "$_ [{propdiv($_)}]" for 1..10;
my @candidates;
loop (my int $c = 30; $c <= 20_000; $c += 30) {
#(30, *+30 …^ * > 500_000).race.map: -> $c {
my \mx = +propdiv($c);
next if mx < @candidates - 1;
@candidates[mx].push: $c
}
say "max = {@candidates - 1}, candidates = {@candidates.tail}"; |
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.
| #SenseTalk | SenseTalk |
// PriorityQueue.script
set Tasks to a new PriorityQueue
tell Tasks to add 3,"Clear drains"
tell Tasks to add 4,"Feed cat"
tell Tasks to add 5,"Make tea"
tell Tasks to add 1,"Solve RC tasks"
tell Tasks to add 2,"Tax return"
put "Initial tasks:"
put Tasks.report & return
put Tasks.getTop into topItem
put "Top priority: " & topItem & return
put "Remaining:" & return & Tasks.report
------
properties
queue:[]
end properties
to add newPriority, newTask
repeat with each item of my queue
if newPriority comes before the priority of it then
insert {priority:newPriority, task:newTask} before item the counter of my queue
return
end if
end repeat
insert {priority:newPriority, task:newTask} into my queue -- add at end if last priority
end add
to getTop
pull my queue into firstItem
return firstItem
end getTop
to report
return (priority of each && task of each for each item of my queue) joined by return
end report
|
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
| #M2000_Interpreter | M2000 Interpreter |
Module Prime_decomposition {
Inventory Known1=2@, 3@
IsPrime=lambda Known1 (x as decimal) -> {
=0=1
if exist(Known1, x) then =1=1 : exit
if x<=5 OR frac(x) then {if x == 2 OR x == 3 OR x == 5 then Append Known1, x : =1=1
Break}
if frac(x/2) else exit
if frac(x/3) else exit
x1=sqrt(x):d = 5@
{if frac(x/d ) else exit
d += 2: if d>x1 then Append Known1, x : =1=1 : exit
if frac(x/d) else exit
d += 4: if d<= x1 else Append Known1, x : =1=1: exit
loop}
}
decompose=lambda IsPrime (n as decimal) -> {
Inventory queue Factors
{
k=2@
While frac(n/k)=0 {
n/=k
Append Factors, k
}
if n=1 then exit
k++
While frac(n/k)=0 {
n/=k
Append Factors, k
}
if n=1 then exit
{
k+=2
while not isprime(k) {k+=2}
While frac(n/k)=0 {
n/=k
Append Factors, k
}
if n=1 then exit
loop
}
}
=Factors
}
Data 10, 100, 12, 144, 496, 1212454
while not empty {
Print Decompose(Number)
}
}
Prime_decomposition
|
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.