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/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Oz | Oz | declare
class T from ObjectSupport.reflect
meth init
skip
end
meth name($)
'T'
end
end
class S from T
attr a
feat f
meth name($)
'S'
end
meth getA($) @a end
meth setA(V) a := V end
end
Obj = {New S init}
Copy = {Obj clone($)}
in
%% Some assertions:
%% Copy is really an S:
{Copy name($)} = 'S'
%% Copy is not just a reference to the same object:
{System.eq Obj Copy} = false
%% Not a deep copy. Feature f has the same identity for both objects:
{System.eq Obj.f Copy.f} = true
%% However, both have their own distinct attributes:
{Obj setA(13)}
{Copy setA(14)}
{Obj getA($)} \= {Copy getA($)} = true |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Perl | Perl | package T;
sub new {
my $cls = shift;
bless [ @_ ], $cls
}
sub set_data {
my $self = shift;
@$self = @_;
}
sub copy {
my $self = shift;
bless [ @$self ], ref $self;
}
sub manifest {
my $self = shift;
print "type T, content: @$self\n\n";
}
package S;
our @ISA = 'T';
# S is inheriting from T.
# 'manifest' method is overriden, while 'new', 'copy' and
# 'set_data' are all inherited.
sub manifest {
my $self = shift;
print "type S, content: @$self\n\n";
}
package main;
print "# creating \$t as a T\n";
my $t = T->new('abc');
$t->manifest;
print "# creating \$s as an S\n";
my $s = S->new('SPQR');
$s->manifest;
print "# make var \$x as a copy of \$t\n";
my $x = $t->copy;
$x->manifest;
print "# now as a copy of \$s\n";
$x = $s->copy;
$x->manifest;
print "# show that this copy is indeed a separate entity\n";
$x->set_data('totally different');
print "\$x is: ";
$x->manifest; |
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.
| #Java | Java | import java.util.Arrays;
import java.util.function.IntToDoubleFunction;
import java.util.stream.IntStream;
public class PolynomialRegression {
private static void polyRegression(int[] x, int[] y) {
int n = x.length;
int[] r = IntStream.range(0, n).toArray();
double xm = Arrays.stream(x).average().orElse(Double.NaN);
double ym = Arrays.stream(y).average().orElse(Double.NaN);
double x2m = Arrays.stream(r).map(a -> a * a).average().orElse(Double.NaN);
double x3m = Arrays.stream(r).map(a -> a * a * a).average().orElse(Double.NaN);
double x4m = Arrays.stream(r).map(a -> a * a * a * a).average().orElse(Double.NaN);
double xym = 0.0;
for (int i = 0; i < x.length && i < y.length; ++i) {
xym += x[i] * y[i];
}
xym /= Math.min(x.length, y.length);
double x2ym = 0.0;
for (int i = 0; i < x.length && i < y.length; ++i) {
x2ym += x[i] * x[i] * y[i];
}
x2ym /= Math.min(x.length, y.length);
double sxx = x2m - xm * xm;
double sxy = xym - xm * ym;
double sxx2 = x3m - xm * x2m;
double sx2x2 = x4m - x2m * x2m;
double sx2y = x2ym - x2m * ym;
double b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
double c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
double a = ym - b * xm - c * x2m;
IntToDoubleFunction abc = (int xx) -> a + b * xx + c * xx * xx;
System.out.println("y = " + a + " + " + b + "x + " + c + "x^2");
System.out.println(" Input Approximation");
System.out.println(" x y y1");
for (int i = 0; i < n; ++i) {
System.out.printf("%2d %3d %5.1f\n", x[i], y[i], abc.applyAsDouble(x[i]));
}
}
public static void main(String[] args) {
int[] x = IntStream.range(0, 11).toArray();
int[] y = new int[]{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
polyRegression(x, y);
}
} |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #EchoLisp | EchoLisp |
(define (set-cons a A)
(make-set (cons a A)))
(define (power-set e)
(cond ((null? e)
(make-set (list ∅)))
(else (let [(ps (power-set (cdr e)))]
(make-set
(append ps (map set-cons (circular-list (car e)) ps)))))))
(define B (make-set ' ( 🍎 🍇 🎂 🎄 )))
(power-set B)
→ { ∅ { 🍇 } { 🍇 🍎 } { 🍇 🍎 🎂 } { 🍇 🍎 🎂 🎄 } { 🍇 🍎 🎄 } { 🍇 🎂 } { 🍇 🎂 🎄 }
{ 🍇 🎄 } { 🍎 } { 🍎 🎂 } { 🍎 🎂 🎄 } { 🍎 🎄 } { 🎂 } { 🎂 🎄 } { 🎄 } }
;; The Von Neumann universe
(define V0 (power-set null)) ;; null and ∅ are the same
→ { ∅ }
(define V1 (power-set V0))
→ { ∅ { ∅ } }
(define V2 (power-set V1))
→ { ∅ { ∅ } { ∅ { ∅ } } { { ∅ } } }
(define V3 (power-set V2))
→ { ∅ { ∅ } { ∅ { ∅ } } …🔃 )
(length V3) → 16
(define V4 (power-set V3))
(length V4) → 65536
;; length V5 = 2^65536 : out of bounds
|
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
| #C | C | int is_prime(unsigned int n)
{
unsigned int p;
if (!(n & 1) || n < 2 ) return n == 2;
/* comparing p*p <= n can overflow */
for (p = 3; p <= n/p; p += 2)
if (!(n % p)) return 0;
return 1;
} |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Go | Go | package main
import "fmt"
func pf(v float64) float64 {
switch {
case v < .06:
return .10
case v < .11:
return .18
case v < .16:
return .26
case v < .21:
return .32
case v < .26:
return .38
case v < .31:
return .44
case v < .36:
return .50
case v < .41:
return .54
case v < .46:
return .58
case v < .51:
return .62
case v < .56:
return .66
case v < .61:
return .70
case v < .66:
return .74
case v < .71:
return .78
case v < .76:
return .82
case v < .81:
return .86
case v < .86:
return .90
case v < .91:
return .94
case v < .96:
return .98
}
return 1
}
func main() {
tests := []float64{0.3793, 0.4425, 0.0746, 0.6918, 0.2993,
0.5486, 0.7848, 0.9383, 0.2292, 0.9760}
for _, v := range tests {
fmt.Printf("%0.4f -> %0.2f\n", v, pf(v))
}
} |
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
| #Kotlin | Kotlin | // version 1.0.5-2
fun listProperDivisors(limit: Int) {
if (limit < 1) return
for(i in 1..limit) {
print(i.toString().padStart(2) + " -> ")
if (i == 1) {
println("(None)")
continue
}
(1..i/2).filter{ i % it == 0 }.forEach { print(" $it") }
println()
}
}
fun countProperDivisors(n: Int): Int {
if (n < 2) return 0
return (1..n/2).count { (n % it) == 0 }
}
fun main(args: Array<String>) {
println("The proper divisors of the following numbers are :\n")
listProperDivisors(10)
println()
var count: Int
var maxCount = 0
val most: MutableList<Int> = mutableListOf(1)
for (n in 2..20000) {
count = countProperDivisors(n)
if (count == maxCount)
most.add(n)
else if (count > maxCount) {
maxCount = count
most.clear()
most.add(n)
}
}
println("The following number(s) have the most proper divisors, namely " + maxCount + "\n")
for (n in most) println(n)
} |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Python | Python | import random, bisect
def probchoice(items, probs):
'''\
Splits the interval 0.0-1.0 in proportion to probs
then finds where each random.random() choice lies
'''
prob_accumulator = 0
accumulator = []
for p in probs:
prob_accumulator += p
accumulator.append(prob_accumulator)
while True:
r = random.random()
yield items[bisect.bisect(accumulator, r)]
def probchoice2(items, probs, bincount=10000):
'''\
Puts items in bins in proportion to probs
then uses random.choice() to select items.
Larger bincount for more memory use but
higher accuracy (on avarage).
'''
bins = []
for item,prob in zip(items, probs):
bins += [item]*int(bincount*prob)
while True:
yield random.choice(bins)
def tester(func=probchoice, items='good bad ugly'.split(),
probs=[0.5, 0.3, 0.2],
trials = 100000
):
def problist2string(probs):
'''\
Turns a list of probabilities into a string
Also rounds FP values
'''
return ",".join('%8.6f' % (p,) for p in probs)
from collections import defaultdict
counter = defaultdict(int)
it = func(items, probs)
for dummy in xrange(trials):
counter[it.next()] += 1
print "\n##\n## %s\n##" % func.func_name.upper()
print "Trials: ", trials
print "Items: ", ' '.join(items)
print "Target probability: ", problist2string(probs)
print "Attained probability:", problist2string(
counter[x]/float(trials) for x in items)
if __name__ == '__main__':
items = 'aleph beth gimel daleth he waw zayin heth'.split()
probs = [1/(float(n)+5) for n in range(len(items))]
probs[-1] = 1-sum(probs[:-1])
tester(probchoice, items, probs, 1000000)
tester(probchoice2, items, probs, 1000000) |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| #Nim | Nim | type
PriElem[T] = tuple
data: T
pri: int
PriQueue[T] = object
buf: seq[PriElem[T]]
count: int
# first element not used to simplify indices
proc initPriQueue[T](initialSize = 4): PriQueue[T] =
result.buf.newSeq(initialSize)
result.buf.setLen(1)
result.count = 0
proc add[T](q: var PriQueue[T], data: T, pri: int) =
var n = q.buf.len
var m = n div 2
q.buf.setLen(n + 1)
# append at end, then up heap
while m > 0 and pri < q.buf[m].pri:
q.buf[n] = q.buf[m]
n = m
m = m div 2
q.buf[n] = (data, pri)
q.count = q.buf.len - 1
proc pop[T](q: var PriQueue[T]): PriElem[T] =
assert q.buf.len > 1
result = q.buf[1]
var qn = q.buf.len - 1
var n = 1
var m = 2
while m < qn:
if m + 1 < qn and q.buf[m].pri > q.buf[m+1].pri:
inc m
if q.buf[qn].pri <= q.buf[m].pri:
break
q.buf[n] = q.buf[m]
n = m
m = m * 2
q.buf[n] = q.buf[qn]
q.buf.setLen(q.buf.len - 1)
q.count = q.buf.len - 1
var p = initPriQueue[string]()
p.add("Clear drains", 3)
p.add("Feed cat", 4)
p.add("Make tea", 5)
p.add("Solve RC tasks", 1)
p.add("Tax return", 2)
while p.count > 0:
echo p.pop() |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
| #Visual_Basic | Visual Basic | Option Explicit
Dim total As Long, prim As Long, maxPeri As Long
Public Sub NewTri(ByVal s0 As Long, ByVal s1 As Long, ByVal s2 As Long)
Dim p As Long, x1 As Long, x2 As Long
p = s0 + s1 + s2
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
x1 = s0 + s2
x2 = s1 + s2
NewTri s0 + 2 * (-s1 + s2), 2 * x1 - s1, 2 * (x1 - s1) + s2
NewTri s0 + 2 * x2, 2 * x1 + s1, 2 * (x1 + s1) + s2
NewTri -s0 + 2 * x2, 2 * (-s0 + s2) + s1, 2 * (-s0 + x2) + s2
End If
End Sub
Public Sub Main()
maxPeri = 100
Do While maxPeri <= 10& ^ 8
prim = 0
total = 0
NewTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #Unlambda | Unlambda | `ei |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #Ursa | Ursa | stop |
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
| #Ezhil | Ezhil |
## இந்த நிரல் தரப்பட்ட எண்ணின் பகாஎண் கூறுகளைக் கண்டறியும்
நிரல்பாகம் பகாஎண்ணா(எண்1)
## இந்த நிரல்பாகம் தரப்பட்ட எண் பகு எண்ணா அல்லது பகா எண்ணா என்று கண்டறிந்து சொல்லும்
## பகுஎண் என்றால் 0 திரும்பத் தரப்படும்
## பகாஎண் என்றால் 1 திரும்பத் தரப்படும்
@(எண்1 < 0) ஆனால்
## எதிர்மறை எண்களை நேராக்குதல்
எண்1 = எண்1 * (-1)
முடி
@(எண்1 < 2) ஆனால்
## பூஜ்ஜியம், ஒன்று ஆகியவை பகா எண்கள் அல்ல
பின்கொடு 0
முடி
@(எண்1 == 2) ஆனால்
## இரண்டு என்ற எண் ஒரு பகா எண்
பின்கொடு 1
முடி
மீதம் = எண்1%2
@(மீதம் == 0) ஆனால்
## இரட்டைப்படை எண், ஆகவே, இது பகா எண் அல்ல
பின்கொடு 0
முடி
எண்1வர்க்கமூலம் = எண்1^0.5
@(எண்2 = 3, எண்2 <= எண்1வர்க்கமூலம், எண்2 = எண்2 + 2) ஆக
மீதம்1 = எண்1%எண்2
@(மீதம்1 == 0) ஆனால்
## ஏதேனும் ஓர் எண்ணால் முழுமையாக வகுபட்டுவிட்டது, ஆகவே அது பகா எண் அல்ல
பின்கொடு 0
முடி
முடி
பின்கொடு 1
முடி
நிரல்பாகம் பகுத்தெடு(எண்1)
## இந்த எண் தரப்பட்ட எண்ணின் பகா எண் கூறுகளைக் கண்டறிந்து பட்டியல் இடும்
கூறுகள் = பட்டியல்()
@(எண்1 < 0) ஆனால்
## எதிர்மறை எண்களை நேராக்குதல்
எண்1 = எண்1 * (-1)
முடி
@(எண்1 <= 1) ஆனால்
## ஒன்று அல்லது அதற்குக் குறைவான எண்களுக்குப் பகா எண் விகிதம் கண்டறியமுடியாது
பின்கொடு கூறுகள்
முடி
@(பகாஎண்ணா(எண்1) == 1) ஆனால்
## தரப்பட்ட எண்ணே பகா எண்ணாக அமைந்துவிட்டால், அதற்கு அதுவே பகாஎண் கூறு ஆகும்
பின்இணை(கூறுகள், எண்1)
பின்கொடு கூறுகள்
முடி
தாற்காலிகஎண் = எண்1
எண்2 = 2
@(எண்2 <= தாற்காலிகஎண்) வரை
விடை1 = பகாஎண்ணா(எண்2)
மீண்டும்தொடங்கு = 0
@(விடை1 == 1) ஆனால்
விடை2 = தாற்காலிகஎண்%எண்2
@(விடை2 == 0) ஆனால்
## பகா எண்ணால் முழுமையாக வகுபட்டுள்ளது, அதனைப் பட்டியலில் இணைக்கிறோம்
பின்இணை(கூறுகள், எண்2)
தாற்காலிகஎண் = தாற்காலிகஎண்/எண்2
## மீண்டும் இரண்டில் தொடங்கி இதே கணக்கிடுதலைத் தொடரவேண்டும்
எண்2 = 2
மீண்டும்தொடங்கு = 1
முடி
முடி
@(மீண்டும்தொடங்கு == 0) ஆனால்
## அடுத்த எண்ணைத் தேர்ந்தெடுத்துக் கணக்கிடுதலைத் தொடரவேண்டும்
எண்2 = எண்2 + 1
முடி
முடி
பின்கொடு கூறுகள்
முடி
அ = int(உள்ளீடு("உங்களுக்குப் பிடித்த ஓர் எண்ணைத் தாருங்கள்: "))
பகாஎண்கூறுகள் = பட்டியல்()
பகாஎண்கூறுகள் = பகுத்தெடு(அ)
பதிப்பி "நீங்கள் தந்த எண்ணின் பகா எண் கூறுகள் இவை: ", பகாஎண்கூறுகள்
|
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #Perl | Perl | # start with some var definitions
my $scalar = 'aa';
my @array = ('bb', 'cc');
my %hash = ( dd => 'DD', ee => 'EE' );
# make references
my $scalarref = \$scalar;
my $arrayref = \@array;
my $hashref = \%hash; |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #Phix | Phix | atom addr = allocate(8) -- (assumes 32 bit)
poke4(addr,{NULL,SOME_CONSTANT})
c_proc(xSome_External_Routine,{addr,addr+4})
?peek4s({addr,2}) -- prints {x,y}
free(addr)
|
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.
| #gnuplot | gnuplot | unset key # Only one data set, so the key is uninformative
plot '-' # '-' can be replaced with a filename, to read data from that file.
0 2.7
1 2.8
2 31.4
3 38.1
4 68.0
5 76.2
6 100.5
7 130.0
8 149.3
9 180.0
e |
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.
| #Go | Go | package main
import (
"fmt"
"log"
"os/exec"
)
var (
x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0}
)
func main() {
g := exec.Command("gnuplot", "-persist")
w, err := g.StdinPipe()
if err != nil {
log.Fatal(err)
}
if err = g.Start(); err != nil {
log.Fatal(err)
}
fmt.Fprintln(w, "unset key; plot '-'")
for i, xi := range x {
fmt.Fprintf(w, "%d %f\n", xi, y[i])
}
fmt.Fprintln(w, "e")
w.Close()
g.Wait()
} |
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
| #Ela | Ela | type Point = Point x y
instance Show Point where
show (Point x y) = "Point " ++ (show x) ++ " " ++ (show y)
instance Name Point where
getField nm (Point x y)
| nm == "x" = x
| nm == "y" = y
| else = fail "Undefined name."
isField nm _ = nm == "x" || nm == "y"
pointX = flip Point 0
pointY = Point 0
pointEmpty = Point 0 0
type Circle = Circle x y z
instance Show Circle where
show (Circle x y z) =
"Circle " ++ (show x) ++ " " ++ (show y) ++ " " ++ (show z)
instance Name Circle where
getField nm (Circle x y z)
| nm == "x" = x
| nm == "y" = y
| nm == "z" = z
| else = fail "Undefined name."
isField nm _ = nm == "x" || nm == "y" || nm == "z"
circleXZ = flip Circle 0
circleX x = Circle x 0 0
circleYZ = Circle 0
circleY y = Circle 0 y 0
circleZ = Circle 0 0
circleEmpty = Circle 0 0 0 |
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
| #Elena | Elena | import extensions;
class Point
{
prop int X;
prop int Y;
constructor new(int x, int y)
{
X := x;
Y := y
}
constructor new()
<= new(0,0);
print() { console.printLine("Point") }
}
class Circle : Point
{
prop int R;
constructor new()
<= new(0);
constructor new(int r)
<= new(0, 0, r);
constructor new(int x, int y, int r)
<= new(x, y)
{
R := r
}
print() { console.printLine("Circle") }
}
public program()
{
Point p := Point.new();
Point c := Circle.new();
p.print();
c.print()
} |
http://rosettacode.org/wiki/Poker_hand_analyser | Poker hand analyser | Task
Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
Example
2d (two of diamonds).
Faces are: a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, k
Suits are: h (hearts), d (diamonds), c (clubs), and s (spades), or
alternatively, the unicode card-suit characters: ♥ ♦ ♣ ♠
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
Examples
2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind
2♥ 5♥ 7♦ 8♣ 9♠: high-card
a♥ 2♦ 3♣ 4♣ 5♦: straight
2♥ 3♥ 2♦ 3♣ 3♦: full-house
2♥ 7♥ 2♦ 3♣ 3♦: two-pair
2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind
10♥ j♥ q♥ k♥ a♥: straight-flush
4♥ 4♠ k♠ 5♦ 10♠: one-pair
q♣ 10♣ 7♣ 6♣ q♣: invalid
The programs output for the above examples should be displayed here on this page.
Extra credit
use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
allow two jokers
use the symbol joker
duplicates would be allowed (for jokers only)
five-of-a-kind would then be the highest hand
More extra credit examples
joker 2♦ 2♠ k♠ q♦: three-of-a-kind
joker 5♥ 7♦ 8♠ 9♦: straight
joker 2♦ 3♠ 4♠ 5♠: straight
joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind
joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind
joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind
joker j♥ q♥ k♥ A♥: straight-flush
joker 4♣ k♣ 5♦ 10♠: one-pair
joker k♣ 7♣ 6♣ 4♣: flush
joker 2♦ joker 4♠ 5♠: straight
joker Q♦ joker A♠ 10♠: straight
joker Q♦ joker A♦ 10♦: straight-flush
joker 2♦ 2♠ joker q♦: four-of-a-kind
Related tasks
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Go Fish
| #Julia | Julia | sorteddeck = [string(r) * s for s in "♣♦♥♠", r in "23456789TJQKA"]
cardlessthan(card1, card2) = indexin(x, sorteddeck)[1] < indexin(y, sorteddeck)[1]
decksort(d) = sort(d, lt=cardlessthan)
highestrank(d) = string(highestcard(d)[1])
function hasduplicate(d)
s = sort(d)
for i in 1:length(s)-1
if s[i] == s[i+1]
return true
end
end
false
end
invalid(d) = !all(x -> x in sorteddeck, d) || hasduplicate(d)
function countranks(d)
ranks = Dict()
for c in d
r = string(c[1])
if !haskey(ranks, r)
ranks[r] = 1
else
ranks[r] += 1
end
end
ranks
end
function countsuits(d)
suits = Dict()
for c in d
s = string(c[2])
if !haskey(suits, s)
suits[s] = 1
else
suits[s] += 1
end
end
suits
end
const rankmodifiers = Dict("A" => 130, "K" => 120, "Q" => 110, "J" => 100, "T" => 90,
"9" => 80, "8" => 70, "7" => 60, "6" => 50, "5" => 40,
"4" => 30, "3" => 20, "2" => 10)
rank(card) = rankmodifiers[string(card[1])]
const suitmodifiers = Dict("♠" => 4, "♥" => 3, "♦" => 2, "♣" => 1)
suitrank(card) = suitmodifiers[string(card[2])]
function isstraight(ranksdict)
v = collect(values(ranksdict))
if maximum(v) != 1
return false
else
s = sort(map(x->rankmodifiers[x], collect(keys(ranksdict))))
if s == [10, 20, 30, 40, 130] # aces low straight
return true
else
for i in 1:length(s)-1
if abs(s[i] - s[i+1]) > 10
return false
end
end
end
end
true
end
highestsuit(suitsdict) = sort(collect(keys(suitsdict)), lt=(x,y)->suitsdict[x] < suitsdict[y])[end]
isflush(suitsdict) = length(collect(values(suitsdict))) == 1
isstraightflush(ranks, suits) = isstraight(ranks) && isflush(suits)
isfourofakind(ranksdict) = maximum(values(ranksdict)) == 4 ? true : false
isfullhouse(ranksdict) = sort(collect(values(ranksdict))) == [2, 3]
isthreeofakind(ranksdict) = maximum(values(ranksdict)) == 3 && !isfullhouse(ranksdict) ? true : false
istwopair(ranksdict) = sort(collect(values(ranksdict)))[end-1: end] == [2,2]
isonepair(ranksdict) = sort(collect(values(ranksdict)))[end-1: end] == [1,2]
ishighcard(ranks, suits) = maximum(values(ranks)) == 1 && !isflush(suits) && !isstraight(ranks)
function scorehand(d)
suits = countsuits(d)
ranks = countranks(d)
if invalid(d)
return "invalid"
end
if isstraightflush(ranks, suits) return "straight-flush"
elseif isfourofakind(ranks) return "four-of-a-kind"
elseif isfullhouse(ranks) return "full-house"
elseif isflush(suits) return "flush"
elseif isstraight(ranks) return "straight"
elseif isthreeofakind(ranks) return "three-of-a-kind"
elseif istwopair(ranks) return "two-pair"
elseif isonepair(ranks) return "one-pair"
elseif ishighcard(ranks, suits) return "high-card"
end
end
const hands = [["2♥", "2♦", "2♣", "K♣", "Q♦"], ["2♥", "5♥", "7♦", "8♣", "9♠"],
["A♥", "2♦", "3♣", "4♣", "5♦"], ["2♥", "3♥", "2♦", "3♣", "3♦"],
["2♥", "7♥", "2♦", "3♣", "3♦"], ["2♥", "7♥", "7♦", "7♣", "7♠"],
["T♥", "J♥", "Q♥", "K♥", "A♥"], ["4♥", "4♠", "K♠", "5♦", "T♠"],
["Q♣", "T♣", "7♣", "6♣", "4♣"]]
for hand in hands
println("Hand $hand is a ", scorehand(hand), " hand.")
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. HAMMING.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 POPCOUNT-VARIABLES.
03 POPCOUNT-IN PIC 9(15)V9.
03 FILLER REDEFINES POPCOUNT-IN.
05 POPCOUNT-REST PIC 9(15).
05 FILLER PIC 9.
88 BIT-IS-SET VALUE 5.
03 POPCOUNT-OUT PIC 99.
03 FILLER REDEFINES POPCOUNT-OUT.
05 FILLER PIC 9.
05 FILLER PIC 9.
88 EVIL VALUES 0, 2, 4, 6, 8.
88 ODIOUS VALUES 1, 3, 5, 7, 9.
01 STATE-VARIABLES.
03 CUR-POWER-3 PIC 9(15) VALUE 1.
03 CUR-EVIL-NUM PIC 99 VALUE 0.
03 CUR-ODIOUS-NUM PIC 99 VALUE 0.
03 LINE-INDEX PIC 99 VALUE 1.
01 OUTPUT-FORMAT.
03 LINENO PIC Z9.
03 FILLER PIC X VALUE '.'.
03 FILLER PIC XX VALUE SPACES.
03 OUT-POW3 PIC Z9.
03 FILLER PIC X(4) VALUE SPACES.
03 OUT-EVIL PIC Z9.
03 FILLER PIC X(4) VALUE SPACES.
03 OUT-ODIOUS PIC Z9.
PROCEDURE DIVISION.
BEGIN.
DISPLAY " 3^ EVIL ODD"
PERFORM MAKE-LINE 30 TIMES.
STOP RUN.
MAKE-LINE.
MOVE LINE-INDEX TO LINENO.
MOVE CUR-POWER-3 TO POPCOUNT-IN.
PERFORM FIND-POPCOUNT.
MOVE POPCOUNT-OUT TO OUT-POW3.
PERFORM FIND-EVIL.
MOVE CUR-EVIL-NUM TO OUT-EVIL.
PERFORM FIND-ODIOUS.
MOVE CUR-ODIOUS-NUM TO OUT-ODIOUS.
DISPLAY OUTPUT-FORMAT.
MULTIPLY 3 BY CUR-POWER-3.
ADD 1 TO CUR-EVIL-NUM.
ADD 1 TO CUR-ODIOUS-NUM.
ADD 1 TO LINE-INDEX.
FIND-EVIL.
MOVE CUR-EVIL-NUM TO POPCOUNT-IN.
PERFORM FIND-POPCOUNT.
IF NOT EVIL, ADD 1 TO CUR-EVIL-NUM, GO TO FIND-EVIL.
FIND-ODIOUS.
MOVE CUR-ODIOUS-NUM TO POPCOUNT-IN.
PERFORM FIND-POPCOUNT.
IF NOT ODIOUS, ADD 1 TO CUR-ODIOUS-NUM, GO TO FIND-ODIOUS.
FIND-POPCOUNT.
MOVE 0 TO POPCOUNT-OUT.
PERFORM PROCESS-BIT UNTIL POPCOUNT-IN IS EQUAL TO ZERO.
PROCESS-BIT.
DIVIDE 2 INTO POPCOUNT-IN.
IF BIT-IS-SET, ADD 1 TO POPCOUNT-OUT.
MOVE POPCOUNT-REST TO POPCOUNT-IN. |
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
| #J | J | divmod=:[: (}: ; {:) ([ (] -/@,:&}. (* {:)) ] , %&{.~)^:(>:@-~&#)&.|.~ |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Phix | Phix | with javascript_semantics
enum NAME, METHOD
procedure me_t()
puts(1,"I is a T\n")
end procedure
procedure me_s()
puts(1,"I is an S\n")
end procedure
type T(object o)
-- as o[METHOD] can be overidden, don't verify it (as in test for me_t)!
return sequence(o) and length(o)=2 and string(o[NAME]) and integer(o[METHOD])
end type
type S(T t)
return t[METHOD] = me_s
end type
S s = {"S",me_s}
T t = {"T",me_t}
call_proc(t[METHOD],{})
t = s
call_proc(t[METHOD],{})
|
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #PHP | PHP | <?php
class T {
function name() { return "T"; }
}
class S {
function name() { return "S"; }
}
$obj1 = new T();
$obj2 = new S();
$obj3 = clone $obj1;
$obj4 = clone $obj2;
echo $obj3->name(), "\n"; // prints "T"
echo $obj4->name(), "\n"; // prints "S"
?> |
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.
| #Julia | Julia | polyfit(x::Vector, y::Vector, deg::Int) = collect(v ^ p for v in x, p in 0:deg) \ y
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
@show polyfit(x, y, 2) |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Elixir | Elixir | defmodule RC do
use Bitwise
def powerset1(list) do
n = length(list)
max = round(:math.pow(2,n))
for i <- 0..max-1, do: (for pos <- 0..n-1, band(i, bsl(1, pos)) != 0, do: Enum.at(list, pos) )
end
def powerset2([]), do: [[]]
def powerset2([h|t]) do
pt = powerset2(t)
(for x <- pt, do: [h|x]) ++ pt
end
def powerset3([]), do: [[]]
def powerset3([h|t]) do
pt = powerset3(t)
powerset3(h, pt, pt)
end
defp powerset3(_, [], acc), do: acc
defp powerset3(x, [h|t], acc), do: powerset3(x, t, [[x|h] | acc])
end
IO.inspect RC.powerset1([1,2,3])
IO.inspect RC.powerset2([1,2,3])
IO.inspect RC.powerset3([1,2,3])
IO.inspect RC.powerset1([])
IO.inspect RC.powerset1(["one"]) |
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
| #C.23 | C# | static bool isPrime(int n)
{
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
} |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Groovy | Groovy | def priceFraction(value) {
assert value >= 0.0 && value <= 1.0
def priceMappings = [(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]
for (price in priceMappings.keySet()) {
if (value < price) return priceMappings[price]
}
1.00
}
for (def v = 0.00; v <= 1.00; v += 0.01) {
println "$v --> ${priceFraction(v)}"
} |
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
| #Lua | Lua | -- Return a table of the proper divisors of n
function propDivs (n)
if n < 2 then return {} end
local divs, sqr = {1}, math.sqrt(n)
for d = 2, sqr do
if n % d == 0 then
table.insert(divs, d)
if d ~= sqr then table.insert(divs, n/d) end
end
end
table.sort(divs)
return divs
end
-- Show n followed by all values in t
function show (n, t)
io.write(n .. ":\t")
for _, v in pairs(t) do io.write(v .. " ") end
print()
end
-- Main procedure
local mostDivs, numDivs, answer = 0
for i = 1, 10 do show(i, propDivs(i)) end
for i = 1, 20000 do
numDivs = #propDivs(i)
if numDivs > mostDivs then
mostDivs = numDivs
answer = i
end
end
print(answer .. " has " .. mostDivs .. " proper divisors.") |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
( --------------- zen object orientation -------------- )
[ immovable
]this[ swap do ]done[ ] is object ( [ --> )
[ ]'[ ] is method ( --> [ )
[ method
[ dup share
swap put ] ] is localise ( --> )
[ method [ release ] ] is delocalise ( --> )
( ------------------ rand-gen methods ----------------- )
[ method
[ dup take
2 split drop
' [ 0 0 ] join
swap put ] ] is reset-gen ( --> [ )
[ method
[ dup take
dup 2 peek 1+
swap 2 poke
dup 1 peek random
over 0 peek <
if
[ dup 3 peek 1+
swap 3 poke ]
swap put ] ] is rand-gen ( --> [ )
[ method
[ dup echo say ": "
share
dup 2 peek dup echo
say " trials" cr
say " Actual: "
over 3 peek
swap 10 point$ echo$ cr
say " Expected: "
dup 0 peek
swap 1 peek
10 point$ echo$ cr
cr ] ] is report ( --> [ )
( ------------------ rand-gen objects ----------------- )
[ object [ 1 5 0 0 ] ] is aleph ( [ --> )
[ object [ 1 6 0 0 ] ] is beth ( [ --> )
[ object [ 1 7 0 0 ] ] is gimel ( [ --> )
[ object [ 1 8 0 0 ] ] is daleth ( [ --> )
[ object [ 1 9 0 0 ] ] is he ( [ --> )
[ object [ 1 10 0 0 ] ] is waw ( [ --> )
[ object [ 1 11 0 0 ] ] is zayin ( [ --> )
[ object [ 1759 27720 0 0 ] ] is heth ( [ --> )
' [ aleph beth gimel daleth he waw zayin heth ]
dup witheach [ reset-gen swap do ]
dup witheach
[ 1000000 times
[ rand-gen over do ]
drop ]
witheach [ report swap do ] |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #R | R | prob = c(aleph=1/5, beth=1/6, gimel=1/7, daleth=1/8, he=1/9, waw=1/10, zayin=1/11, heth=1759/27720)
# Note that R doesn't actually require the weights
# vector for rmultinom to sum to 1.
hebrew = c(rmultinom(1, 1e6, prob))
d = data.frame(
Requested = prob,
Obtained = hebrew/sum(hebrew))
print(d) |
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.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
const void *PQRetain(CFAllocatorRef allocator, const void *ptr) {
return (__bridge_retained const void *)(__bridge id)ptr;
}
void PQRelease(CFAllocatorRef allocator, const void *ptr) {
(void)(__bridge_transfer id)ptr;
}
CFComparisonResult PQCompare(const void *ptr1, const void *ptr2, void *unused) {
return [(__bridge id)ptr1 compare:(__bridge id)ptr2];
}
@interface Task : NSObject {
int priority;
NSString *name;
}
- (instancetype)initWithPriority:(int)p andName:(NSString *)n;
- (NSComparisonResult)compare:(Task *)other;
@end
@implementation Task
- (instancetype)initWithPriority:(int)p andName:(NSString *)n {
if ((self = [super init])) {
priority = p;
name = [n copy];
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat:@"%d, %@", priority, name];
}
- (NSComparisonResult)compare:(Task *)other {
if (priority == other->priority)
return NSOrderedSame;
else if (priority < other->priority)
return NSOrderedAscending;
else
return NSOrderedDescending;
}
@end
int main (int argc, const char *argv[]) {
@autoreleasepool {
CFBinaryHeapCallBacks callBacks = {0, PQRetain, PQRelease, NULL, PQCompare};
CFBinaryHeapRef pq = CFBinaryHeapCreate(NULL, 0, &callBacks, NULL);
CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:3 andName:@"Clear drains"]);
CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:4 andName:@"Feed cat"]);
CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:5 andName:@"Make tea"]);
CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:1 andName:@"Solve RC tasks"]);
CFBinaryHeapAddValue(pq, [[Task alloc] initWithPriority:2 andName:@"Tax return"]);
while (CFBinaryHeapGetCount(pq) != 0) {
Task *task = (id)CFBinaryHeapGetMinimum(pq);
NSLog(@"%@", task);
CFBinaryHeapRemoveMinimumValue(pq);
}
CFRelease(pq);
}
return 0;
} |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
| #Wren | Wren | var sc = System.clock
var total = 0
var prim = 0
var maxPeri = 0
var newTri // recursive function so needs to be declared before it can be called
newTri = Fn.new { |s0, s1, s2|
var p = s0 + s1 + s2
if (p <= maxPeri) {
prim = prim + 1
total = total + (maxPeri/p).floor
newTri.call( 1*s0-2*s1+2*s2, 2*s0-1*s1+2*s2, 2*s0-2*s1+3*s2)
newTri.call( 1*s0+2*s1+2*s2, 2*s0+1*s1+2*s2, 2*s0+2*s1+3*s2)
newTri.call(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)
}
}
maxPeri = 100
while (maxPeri <= 1e10) {
prim = 0
total = 0
newTri.call(3, 4, 5)
var secs = (System.clock - sc).round
System.print("Up to %(maxPeri): %(total) triples, %(prim) primitives, %(secs) seconds")
maxPeri = 10 * maxPeri
} |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #VBA | VBA | 'In case of problem this will terminate the program (without cleanup):
If problem then End
'As VBA is run within an application, such as Excel, a more rigorous way would be:
If problem then Application.Quit
'This will stop the application, but will prompt you to save work. |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #VBScript | VBScript | dim i, j
j = 0
do
for i = 1 to 100
while j < i
if i = 3 then
wscript.quit
end if
wend
next
loop |
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
| #F.23 | F# | let decompose_prime n =
let rec loop c p =
if c < (p * p) then [c]
elif c % p = 0I then p :: (loop (c/p) p)
else loop c (p + 1I)
loop n 2I
printfn "%A" (decompose_prime 600851475143I) |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #PHP | PHP | <?php
/* Assignment of scalar variables */
$a = 1;
$b =& $a; // $b and $a are now linked together
$b = 2; //both $b and $a now equal 2
$c = $b;
$c = 7; //$c is not a reference; no change to $a or $b
unset($a); //won't unset $b, just $a.
/* Passing by Reference in and out of functions */
function &pass_out() {
global $filestr; //$exactly equivalent to: $filestr =& $_GLOBALS['filestr'];
$filestr = get_file_contents("./bigfile.txt");
return $_GLOBALS['filestr'];
}
function pass_in(&$in_filestr) {
echo "File Content Length: ". strlen($in_filestr);
/* Changing $in_filestr also changes the global $filestr and $tmp */
$in_filestr .= "EDIT";
echo "File Content Length is now longer: ". strlen($in_filestr);
}
$tmp = &pass_out(); // now $tmp and the global variable $filestr are linked
pass_in($tmp); // changes $tmp and prints the length
?> |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #PicoLisp | PicoLisp | : (setq L (1 a 2 b 3 c)) # Create a list of 6 items in 'L'
-> (1 a 2 b 3 c)
: (nth L 4) # Get a pointer to the 4th item
-> (b 3 c)
: (set (nth L 4) "Hello") # Store "Hello" in that location
-> "Hello"
: L # Look at the modified list in 'L'
-> (1 a 2 "Hello" 3 c) |
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.
| #Groovy | Groovy | import groovy.swing.SwingBuilder
import javax.swing.JFrame
import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartPanel
import org.jfree.data.xy.XYSeries
import org.jfree.data.xy.XYSeriesCollection
import org.jfree.chart.plot.PlotOrientation
def chart = {
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]
def series = new XYSeries('plots')
[x, y].transpose().each { x, y -> series.add x, y }
def labels = ["Plot Demo", "X", "Y"]
def data = new XYSeriesCollection(series)
def options = [false, true, false]
def chart = ChartFactory.createXYLineChart(*labels, data, PlotOrientation.VERTICAL, *options)
new ChartPanel(chart)
}
new SwingBuilder().edt {
frame(title:'Plot coordinate pairs', defaultCloseOperation:JFrame.EXIT_ON_CLOSE, pack:true, show:true) {
widget(chart())
}
} |
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
| #F.23 | F# | type Printable =
abstract member Print : unit -> unit
type Point(?x, ?y) =
member t.x = defaultArg x 0.0
member t.y = defaultArg y 0.0
interface Printable with
member t.Print() = printfn "Point(x:%f, y:%f)" t.x t.y
type Circle(?center, ?radius) =
member t.center = defaultArg center (new Point())
member t.radius = defaultArg radius 1.0
interface Printable with
member t.Print() =
printfn "Circle(x:%f, y:%f, r:%f)" t.center.x t.center.y t.radius |
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
| #Kotlin | Kotlin | // version 1.1.2
class Card(val face: Int, val suit: Char)
const val FACES = "23456789tjqka"
const val SUITS = "shdc"
fun isStraight(cards: List<Card>): Boolean {
val sorted = cards.sortedBy { it.face }
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
}
fun isFlush(cards: List<Card>): Boolean {
val suit = cards[0].suit
if (cards.drop(1).all { it.suit == suit }) return true
return false
}
fun analyzeHand(hand: String): String {
val h = hand.toLowerCase()
val split = h.split(' ').filterNot { it == "" }.distinct()
if (split.size != 5) return "invalid"
val cards = mutableListOf<Card>()
for (s in split) {
if (s.length != 2) return "invalid"
val fIndex = FACES.indexOf(s[0])
if (fIndex == -1) return "invalid"
val sIndex = SUITS.indexOf(s[1])
if (sIndex == -1) return "invalid"
cards.add(Card(fIndex + 2, s[1]))
}
val groups = cards.groupBy { it.face }
when (groups.size) {
2 -> {
if (groups.any { it.value.size == 4 }) return "four-of-a-kind"
return "full-house"
}
3 -> {
if (groups.any { it.value.size == 3 }) return "three-of-a-kind"
return "two-pair"
}
4 -> return "one-pair"
else -> {
val flush = isFlush(cards)
val straight = isStraight(cards)
when {
flush && straight -> return "straight-flush"
flush -> return "flush"
straight -> return "straight"
else -> return "high-card"
}
}
}
}
fun main(args: Array<String>) {
val hands = arrayOf(
"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) {
println("$hand: ${analyzeHand(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.
| #Common_Lisp | Common Lisp | (format T "3^x: ~{~a ~}~%"
(loop for i below 30
collect (logcount (expt 3 i))))
(multiple-value-bind
(evil odious)
(loop for i below 60
if (evenp (logcount i)) collect i into evil
else collect i into odious
finally (return (values evil odious)))
(format T "evil: ~{~a ~}~%" evil)
(format T "odious: ~{~a ~}~%" odious)) |
http://rosettacode.org/wiki/Polynomial_long_division | Polynomial long division |
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
| #Java | Java |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class PolynomialLongDivision {
public static void main(String[] args) {
RunDivideTest(new Polynomial(1, 3, -12, 2, -42, 0), new Polynomial(1, 1, -3, 0));
RunDivideTest(new Polynomial(5, 2, 4, 1, 1, 0), new Polynomial(2, 1, 3, 0));
RunDivideTest(new Polynomial(5, 10, 4, 7, 1, 0), new Polynomial(2, 4, 2, 2, 3, 0));
RunDivideTest(new Polynomial(2,7,-24,6,2,5,-108,4,3,3,-120,2,-126,0), new Polynomial(2, 4, 2, 2, 3, 0));
}
private static void RunDivideTest(Polynomial p1, Polynomial p2) {
Polynomial[] result = p1.divide(p2);
System.out.printf("Compute: (%s) / (%s) = %s reminder %s%n", p1, p2, result[0], result[1]);
System.out.printf("Test: (%s) * (%s) + (%s) = %s%n%n", result[0], p2, result[1], result[0].multiply(p2).add(result[1]));
}
private static final class Polynomial {
private List<Term> polynomialTerms;
// Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
public Polynomial(long ... values) {
if ( values.length % 2 != 0 ) {
throw new IllegalArgumentException("ERROR 102: Polynomial constructor. Length must be even. Length = " + values.length);
}
polynomialTerms = new ArrayList<>();
for ( int i = 0 ; i < values.length ; i += 2 ) {
polynomialTerms.add(new Term(BigInteger.valueOf(values[i]), values[i+1]));
}
Collections.sort(polynomialTerms, new TermSorter());
}
public Polynomial() {
// zero
polynomialTerms = new ArrayList<>();
polynomialTerms.add(new Term(BigInteger.ZERO, 0));
}
private Polynomial(List<Term> termList) {
if ( termList.size() != 0 ) {
// Remove zero terms if needed
for ( int i = 0 ; i < termList.size() ; i++ ) {
if ( termList.get(i).coefficient.compareTo(Integer.ZERO_INT) == 0 ) {
termList.remove(i);
}
}
}
if ( termList.size() == 0 ) {
// zero
termList.add(new Term(BigInteger.ZERO,0));
}
polynomialTerms = termList;
Collections.sort(polynomialTerms, new TermSorter());
}
public Polynomial[] divide(Polynomial v) {
Polynomial q = new Polynomial();
Polynomial r = this;
Number lcv = v.leadingCoefficient();
long dv = v.degree();
while ( r.degree() >= dv ) {
Number lcr = r.leadingCoefficient();
Number s = lcr.divide(lcv);
Term term = new Term(s, r.degree() - dv);
q = q.add(term);
r = r.add(v.multiply(term.negate()));
}
return new Polynomial[] {q, r};
}
public Polynomial add(Polynomial polynomial) {
List<Term> termList = new ArrayList<>();
int thisCount = polynomialTerms.size();
int polyCount = polynomial.polynomialTerms.size();
while ( thisCount > 0 || polyCount > 0 ) {
Term thisTerm = thisCount == 0 ? null : polynomialTerms.get(thisCount-1);
Term polyTerm = polyCount == 0 ? null : polynomial.polynomialTerms.get(polyCount-1);
if ( thisTerm == null ) {
termList.add(polyTerm);
polyCount--;
}
else if (polyTerm == null ) {
termList.add(thisTerm);
thisCount--;
}
else if ( thisTerm.degree() == polyTerm.degree() ) {
Term t = thisTerm.add(polyTerm);
if ( t.coefficient.compareTo(Integer.ZERO_INT) != 0 ) {
termList.add(t);
}
thisCount--;
polyCount--;
}
else if ( thisTerm.degree() < polyTerm.degree() ) {
termList.add(thisTerm);
thisCount--;
}
else {
termList.add(polyTerm);
polyCount--;
}
}
return new Polynomial(termList);
}
public Polynomial add(Term term) {
List<Term> termList = new ArrayList<>();
boolean added = false;
for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
Term currentTerm = polynomialTerms.get(index);
if ( currentTerm.exponent == term.exponent ) {
added = true;
if ( currentTerm.coefficient.add(term.coefficient).compareTo(Integer.ZERO_INT) != 0 ) {
termList.add(currentTerm.add(term));
}
}
else {
termList.add(currentTerm);
}
}
if ( ! added ) {
termList.add(term);
}
return new Polynomial(termList);
}
public Polynomial multiply(Polynomial polynomial) {
List<Term> termList = new ArrayList<>();
for ( int i = 0 ; i < polynomialTerms.size() ; i++ ) {
Term ci = polynomialTerms.get(i);
for ( int j = 0 ; j < polynomial.polynomialTerms.size() ; j++ ) {
Term cj = polynomial.polynomialTerms.get(j);
Term currentTerm = ci.multiply(cj);
boolean added = false;
for ( int k = 0 ; k < termList.size() ; k++ ) {
if ( currentTerm.exponent == termList.get(k).exponent ) {
added = true;
Term t = termList.remove(k).add(currentTerm);
if ( t.coefficient.compareTo(Integer.ZERO_INT) != 0 ) {
termList.add(t);
}
break;
}
}
if ( ! added ) {
termList.add(currentTerm);
}
}
}
return new Polynomial(termList);
}
public Polynomial multiply(Term term) {
List<Term> termList = new ArrayList<>();
for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
Term currentTerm = polynomialTerms.get(index);
termList.add(currentTerm.multiply(term));
}
return new Polynomial(termList);
}
public Number leadingCoefficient() {
return polynomialTerms.get(0).coefficient;
}
public long degree() {
return polynomialTerms.get(0).exponent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for ( Term term : polynomialTerms ) {
if ( first ) {
sb.append(term);
first = false;
}
else {
sb.append(" ");
if ( term.coefficient.compareTo(Integer.ZERO_INT) > 0 ) {
sb.append("+ ");
sb.append(term);
}
else {
sb.append("- ");
sb.append(term.negate());
}
}
}
return sb.toString();
}
}
private static final class TermSorter implements Comparator<Term> {
@Override
public int compare(Term o1, Term o2) {
return (int) (o2.exponent - o1.exponent);
}
}
private static final class Term {
Number coefficient;
long exponent;
public Term(BigInteger c, long e) {
coefficient = new Integer(c);
exponent = e;
}
public Term(Number c, long e) {
coefficient = c;
exponent = e;
}
public Term multiply(Term term) {
return new Term(coefficient.multiply(term.coefficient), exponent + term.exponent);
}
public Term add(Term term) {
if ( exponent != term.exponent ) {
throw new RuntimeException("ERROR 102: Exponents not equal.");
}
return new Term(coefficient.add(term.coefficient), exponent);
}
public Term negate() {
return new Term(coefficient.negate(), exponent);
}
public long degree() {
return exponent;
}
@Override
public String toString() {
if ( coefficient.compareTo(Integer.ZERO_INT) == 0 ) {
return "0";
}
if ( exponent == 0 ) {
return "" + coefficient;
}
if ( coefficient.compareTo(Integer.ONE_INT) == 0 ) {
if ( exponent == 1 ) {
return "x";
}
else {
return "x^" + exponent;
}
}
if ( exponent == 1 ) {
return coefficient + "x";
}
return coefficient + "x^" + exponent;
}
}
private static abstract class Number {
public abstract int compareTo(Number in);
public abstract Number negate();
public abstract Number add(Number in);
public abstract Number multiply(Number in);
public abstract Number inverse();
public abstract boolean isInteger();
public abstract boolean isFraction();
public Number subtract(Number in) {
return add(in.negate());
}
public Number divide(Number in) {
return multiply(in.inverse());
}
}
public static class Fraction extends Number {
private final Integer numerator;
private final Integer denominator;
public Fraction(Integer n, Integer d) {
numerator = n;
denominator = d;
}
@Override
public int compareTo(Number in) {
if ( in.isInteger() ) {
Integer result = ((Integer) in).multiply(denominator);
return numerator.compareTo(result);
}
else if ( in.isFraction() ) {
Fraction inFrac = (Fraction) in;
Integer left = numerator.multiply(inFrac.denominator);
Integer right = denominator.multiply(inFrac.numerator);
return left.compareTo(right);
}
throw new RuntimeException("ERROR: Unknown number type in Fraction.compareTo");
}
@Override
public Number negate() {
if ( denominator.integer.signum() < 0 ) {
return new Fraction(numerator, (Integer) denominator.negate());
}
return new Fraction((Integer) numerator.negate(), denominator);
}
@Override
public Number add(Number in) {
if ( in.isInteger() ) {
//x/y+z = (x+yz)/y
return new Fraction((Integer) ((Integer) in).multiply(denominator).add(numerator), denominator);
}
else if ( in.isFraction() ) {
Fraction inFrac = (Fraction) in;
// compute a/b + x/y
// Let q = gcd(b,y)
// Result = ( (a*y + x*b)/q ) / ( b*y/q )
Integer x = inFrac.numerator;
Integer y = inFrac.denominator;
Integer q = y.gcd(denominator);
Integer temp1 = numerator.multiply(y);
Integer temp2 = denominator.multiply(x);
Integer newDenom = denominator.multiply(y).divide(q);
if ( newDenom.compareTo(Integer.ONE_INT) == 0 ) {
return temp1.add(temp2);
}
Integer newNum = (Integer) temp1.add(temp2).divide(q);
Integer gcd2 = newDenom.gcd(newNum);
if ( gcd2.compareTo(Integer.ONE_INT) == 0 ) {
return new Fraction(newNum, newDenom);
}
newNum = newNum.divide(gcd2);
newDenom = newDenom.divide(gcd2);
if ( newDenom.compareTo(Integer.ONE_INT) == 0 ) {
return newNum;
}
else if ( newDenom.compareTo(Integer.MINUS_ONE_INT) == 0 ) {
return newNum.negate();
}
return new Fraction(newNum, newDenom);
}
throw new RuntimeException("ERROR: Unknown number type in Fraction.compareTo");
}
@Override
public Number multiply(Number in) {
if ( in.isInteger() ) {
//x/y*z = x*z/y
Integer temp = numerator.multiply((Integer) in);
Integer gcd = temp.gcd(denominator);
if ( gcd.compareTo(Integer.ONE_INT) == 0 || gcd.compareTo(Integer.MINUS_ONE_INT) == 0 ) {
return new Fraction(temp, denominator);
}
Integer newTop = temp.divide(gcd);
Integer newBot = denominator.divide(gcd);
if ( newBot.compareTo(Integer.ONE_INT) == 0 ) {
return newTop;
}
if ( newBot.compareTo(Integer.MINUS_ONE_INT) == 0 ) {
return newTop.negate();
}
return new Fraction(newTop, newBot);
}
else if ( in.isFraction() ) {
Fraction inFrac = (Fraction) in;
// compute a/b * x/y
Integer tempTop = numerator.multiply(inFrac.numerator);
Integer tempBot = denominator.multiply(inFrac.denominator);
Integer gcd = tempTop.gcd(tempBot);
if ( gcd.compareTo(Integer.ONE_INT) == 0 || gcd.compareTo(Integer.MINUS_ONE_INT) == 0 ) {
return new Fraction(tempTop, tempBot);
}
Integer newTop = tempTop.divide(gcd);
Integer newBot = tempBot.divide(gcd);
if ( newBot.compareTo(Integer.ONE_INT) == 0 ) {
return newTop;
}
if ( newBot.compareTo(Integer.MINUS_ONE_INT) == 0 ) {
return newTop.negate();
}
return new Fraction(newTop, newBot);
}
throw new RuntimeException("ERROR: Unknown number type in Fraction.compareTo");
}
@Override
public boolean isInteger() {
return false;
}
@Override
public boolean isFraction() {
return true;
}
@Override
public String toString() {
return numerator.toString() + "/" + denominator.toString();
}
@Override
public Number inverse() {
if ( numerator.equals(Integer.ONE_INT) ) {
return denominator;
}
else if ( numerator.equals(Integer.MINUS_ONE_INT) ) {
return denominator.negate();
}
else if ( numerator.integer.signum() < 0 ) {
return new Fraction((Integer) denominator.negate(), (Integer) numerator.negate());
}
return new Fraction(denominator, numerator);
}
}
public static class Integer extends Number {
private BigInteger integer;
public static final Integer MINUS_ONE_INT = new Integer(new BigInteger("-1"));
public static final Integer ONE_INT = new Integer(new BigInteger("1"));
public static final Integer ZERO_INT = new Integer(new BigInteger("0"));
public Integer(BigInteger number) {
this.integer = number;
}
public int compareTo(Integer val) {
return integer.compareTo(val.integer);
}
@Override
public int compareTo(Number in) {
if ( in.isInteger() ) {
return compareTo((Integer) in);
}
else if ( in.isFraction() ) {
Fraction frac = (Fraction) in;
BigInteger result = integer.multiply(frac.denominator.integer);
return result.compareTo(frac.numerator.integer);
}
throw new RuntimeException("ERROR: Unknown number type in Integer.compareTo");
}
@Override
public Number negate() {
return new Integer(integer.negate());
}
public Integer add(Integer in) {
return new Integer(integer.add(in.integer));
}
@Override
public Number add(Number in) {
if ( in.isInteger() ) {
return add((Integer) in);
}
else if ( in.isFraction() ) {
Fraction f = (Fraction) in;
Integer top = f.numerator;
Integer bot = f.denominator;
return new Fraction((Integer) multiply(bot).add(top), bot);
}
throw new RuntimeException("ERROR: Unknown number type in Integer.add");
}
@Override
public Number multiply(Number in) {
if ( in.isInteger() ) {
return multiply((Integer) in);
}
else if ( in.isFraction() ) {
// a * x/y = ax/y
Integer x = ((Fraction) in).numerator;
Integer y = ((Fraction) in).denominator;
Integer temp = (Integer) multiply(x);
Integer gcd = temp.gcd(y);
if ( gcd.compareTo(Integer.ONE_INT) == 0 || gcd.compareTo(Integer.MINUS_ONE_INT) == 0 ) {
return new Fraction(temp, y);
}
Integer newTop = temp.divide(gcd);
Integer newBot = y.divide(gcd);
if ( newBot.compareTo(Integer.ONE_INT) == 0 ) {
return newTop;
}
if ( newBot.compareTo(Integer.MINUS_ONE_INT) == 0 ) {
return newTop.negate();
}
return new Fraction(newTop, newBot);
}
throw new RuntimeException("ERROR: Unknown number type in Integer.add");
}
public Integer gcd(Integer in) {
return new Integer(integer.gcd(in.integer));
}
public Integer divide(Integer in) {
return new Integer(integer.divide(in.integer));
}
public Integer multiply(Integer in) {
return new Integer(integer.multiply(in.integer));
}
@Override
public boolean isInteger() {
return true;
}
@Override
public boolean isFraction() {
return false;
}
@Override
public String toString() {
return integer.toString();
}
@Override
public Number inverse() {
if ( equals(ZERO_INT) ) {
throw new RuntimeException("Attempting to take the inverse of zero in IntegerExpression");
}
else if ( this.compareTo(ONE_INT) == 0 ) {
return ONE_INT;
}
else if ( this.compareTo(MINUS_ONE_INT) == 0 ) {
return MINUS_ONE_INT;
}
return new Fraction(ONE_INT, this);
}
}
}
|
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #PicoLisp | PicoLisp | : (setq A (new '(+Cls1 +Cls2) 'attr1 123 'attr2 "def" 'attr3 (4 2 0) 'attr4 T))
-> $385603635
: (show A)
$385603635 (+Cls1 +Cls2)
attr4
attr3 (4 2 0)
attr2 "def"
attr1 123
-> $385603635 |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Python | Python | import copy
class T:
def classname(self):
return self.__class__.__name__
def __init__(self):
self.myValue = "I'm a T."
def speak(self):
print self.classname(), 'Hello', self.myValue
def clone(self):
return copy.copy(self)
class S1(T):
def speak(self):
print self.classname(),"Meow", self.myValue
class S2(T):
def speak(self):
print self.classname(),"Woof", self.myValue
print "creating initial objects of types S1, S2, and T"
a = S1()
a.myValue = 'Green'
a.speak()
b = S2()
b.myValue = 'Blue'
b.speak()
u = T()
u.myValue = 'Purple'
u.speak()
print "Making copy of a as u, colors and types should match"
u = a.clone()
u.speak()
a.speak()
print "Assigning new color to u, A's color should be unchanged."
u.myValue = "Orange"
u.speak()
a.speak()
print "Assigning u to reference same object as b, colors and types should match"
u = b
u.speak()
b.speak()
print "Assigning new color to u. Since u,b references same object b's color changes as well"
u.myValue = "Yellow"
u.speak()
b.speak() |
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.
| #Kotlin | Kotlin | // version 1.1.51
fun polyRegression(x: IntArray, y: IntArray) {
val xm = x.average()
val ym = y.average()
val x2m = x.map { it * it }.average()
val x3m = x.map { it * it * it }.average()
val x4m = x.map { it * it * it * it }.average()
val xym = x.zip(y).map { it.first * it.second }.average()
val x2ym = x.zip(y).map { it.first * it.first * it.second }.average()
val sxx = x2m - xm * xm
val sxy = xym - xm * ym
val sxx2 = x3m - xm * x2m
val sx2x2 = x4m - x2m * x2m
val sx2y = x2ym - x2m * ym
val b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
val c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
val a = ym - b * xm - c * x2m
fun abc(xx: Int) = a + b * xx + c * xx * xx
println("y = $a + ${b}x + ${c}x^2\n")
println(" Input Approximation")
println(" x y y1")
for ((xi, yi) in x zip y) {
System.out.printf("%2d %3d %5.1f\n", xi, yi, abc(xi))
}
}
fun main() {
val x = IntArray(11) { it }
val y = intArrayOf(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
polyRegression(x, y)
} |
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Erlang | Erlang | For [1 2 3]:
[ ] | 0 0 0 | 0
[ 3] | 0 0 1 | 1
[ 2 ] | 0 1 0 | 2
[ 2 3] | 0 1 1 | 3
[1 ] | 1 0 0 | 4
[1 3] | 1 0 1 | 5
[1 2 ] | 1 1 0 | 6
[1 2 3] | 1 1 1 | 7
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
|
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.
| #F.23 | F# |
let subsets xs = List.foldBack (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]
|
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
| #C.2B.2B | C++ | #include <cmath>
bool is_prime(unsigned int n)
{
if (n <= 1)
return false;
if (n == 2)
return true;
for (unsigned int i = 2; i <= sqrt(n); ++i)
if (n % i == 0)
return false;
return true;
} |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Haskell | Haskell | price_fraction n
| n < 0 || n > 1 = error "Values must be between 0 and 1."
| n < 0.06 = 0.10
| n < 0.11 = 0.18
| n < 0.16 = 0.26
| n < 0.21 = 0.32
| n < 0.26 = 0.38
| n < 0.31 = 0.44
| n < 0.36 = 0.50
| n < 0.41 = 0.54
| n < 0.46 = 0.58
| n < 0.51 = 0.62
| n < 0.56 = 0.66
| n < 0.61 = 0.70
| n < 0.66 = 0.74
| n < 0.71 = 0.78
| n < 0.76 = 0.82
| n < 0.81 = 0.86
| n < 0.86 = 0.90
| n < 0.91 = 0.94
| n < 0.96 = 0.98
| otherwise = 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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ProperDivisors[n_Integer /; n > 0] := Most@Divisors@n; |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Racket | Racket | #lang racket
;;; returns a probabalistic choice from the sequence choices
;;; choices generates two values -- the chosen value and a
;;; probability (weight) of the choice.
;;;
;;; Note that a hash where keys are choices and values are probabilities
;;; is such a sequence.
;;;
;;; if the total probability < 1 then choice could return #f
;;; if the total probability > 1 then some choices may be impossible
(define (probabalistic-choice choices)
(let-values
(((_ choice) ;; the fold provides two values, we only need the second
;; the first will always be a negative number showing that
;; I've run out of random steam
(for/fold
((rnd (random))
(choice #f))
(((v p) choices)
#:break (<= rnd 0))
(values (- rnd p) v))))
choice))
;;; ditto, but all probabilities must be exact rationals
;;; the optional lcd
;;;
;;; not the most efficient, since it provides a wrapper (and demo)
;;; for p-c/i-w below
(define (probabalistic-choice/exact
choices
#:gcd (GCD (/ (apply gcd (hash-values choices)))))
(probabalistic-choice/integer-weights
(for/hash (((k v) choices))
(values k (* v GCD)))
#:sum-of-weights GCD))
;;; this proves useful in Rock-Paper-Scissors
(define (probabalistic-choice/integer-weights
choices
#:sum-of-weights (sum-of-weights (apply + (hash-values choices))))
(let-values
(((_ choice)
(for/fold
((rnd (random sum-of-weights))
(choice #f))
(((v p) choices)
#:break (< rnd 0))
(values (- rnd p) v))))
choice))
(module+ test
(define test-samples (make-parameter 1000000))
(define (test-p-c-function f w)
(define test-selection (make-hash))
(for* ((i (in-range 0 (test-samples)))
(c (in-value (f w))))
(when (zero? (modulo i 100000)) (eprintf "~a," (quotient i 100000)))
(hash-update! test-selection c add1 0))
(printf "~a~%choice\tcount\texpected\tratio\terror~%" f)
(for* (((k v) (in-hash test-selection))
(e (in-value (* (test-samples) (hash-ref w k)))))
(printf "~a\t~a\t~a\t~a\t~a%~%"
k v e
(/ v (test-samples))
(real->decimal-string
(exact->inexact (* 100 (/ (- v e) e)))))))
(define test-weightings/rosetta
(hash
'aleph 1/5
'beth 1/6
'gimel 1/7
'daleth 1/8
'he 1/9
'waw 1/10
'zayin 1/11
'heth 1759/27720; adjusted so that probabilities add to 1
))
(define test-weightings/50:50 (hash 'woo 1/2 'yay 1/2))
(define test-weightings/1:2:3 (hash 'woo 1 'yay 2 'foo 3))
(test-p-c-function probabalistic-choice test-weightings/50:50)
(test-p-c-function probabalistic-choice/exact test-weightings/50:50)
(test-p-c-function probabalistic-choice test-weightings/rosetta)
(test-p-c-function probabalistic-choice/exact test-weightings/rosetta)) |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Raku | Raku | constant TRIALS = 1e6;
constant @event = <aleph beth gimel daleth he waw zayin heth>;
constant @P = flat (1 X/ 5 .. 11), 1759/27720;
constant @cP = [\+] @P;
my atomicint @results[+@event];
(^TRIALS).race.map: { @results[ @cP.first: { $_ > once rand }, :k ]⚛++; }
say 'Event Occurred Expected Difference';
for ^@results {
my ($occurred, $expected) = @results[$_], @P[$_] * TRIALS;
printf "%-9s%8.0f%9.1f%12.1f\n",
@event[$_],
$occurred,
$expected,
abs $occurred - $expected;
} |
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.
| #OCaml | OCaml | module PQ = Base.PriorityQueue
let () =
let tasks = [
3, "Clear drains";
4, "Feed cat";
5, "Make tea";
1, "Solve RC tasks";
2, "Tax return";
] in
let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in
List.iter (PQ.add pq) tasks;
while not (PQ.is_empty pq) do
let _, task = PQ.first pq in
PQ.remove_first pq;
print_endline task
done |
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
| #XPL0 | XPL0 | func GCD(N, D); \Return the greatest common divisor of N and D
int N, D, R; \numerator and denominator
[if D > N then
[R:=D; D:=N; N:=R];
while D > 0 do
[R:= rem(N/D);
N:= D;
D:= R;
];
return N;
];
int Max, PrimCnt, TripCnt, M, N, A, B, C, K, Prim;
[Max:= 10;
repeat PrimCnt:= 0; TripCnt:= 0;
for M:= 2 to Max do
for N:= 1 to M do
[if GCD(M,N) = 1 \coprime\ and
((M&1) = 0 xor (N&1) = 0) \one even\ then
[A:= M*M - N*N;
B:= 2*M*N;
C:= M*M + N*N;
Prim:= A+B+C;
if Prim <= Max then PrimCnt:= PrimCnt+1;
for K:= Max/Prim downto 1 do
if K*Prim <= Max then TripCnt:= TripCnt+1;
];
];
Format(6, 0);
Text(0, "Up to"); RlOut(0, float(Max));
RlOut(0, float(TripCnt)); Text(0, " triples,");
RlOut(0, float(PrimCnt)); Text(0, " primitives.^m^j");
Max:= Max*10;
until Max > 10_000;
] |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #Vedit_macro_language | Vedit macro language | if (#99 == 1) { Return } // Exit current macro. Return to calling macro.
if (#99 == 2) { Break_Out() } // Stop all macro execution and return to command mode.
if (#99 == 3) { Exit } // Exit Vedit. Prompt for saving any changed files.
if (#99 == 4) { Exit(4) } // As above, but return specified value (instead of 0) to OS
if (#99 == 5) { Xall } // Exit Vedit. Save changed files without prompting.
if (#99 == 6) { Qall } // Exit Vedit. Do not save any files. |
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
| #Factor | Factor | USING: io kernel math math.parser math.primes.factors sequences ;
27720 factors
[ number>string ] map
" " join print ; |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #PL.2FI | PL/I |
dcl i fixed bin(31);
dcl p pointer;
dcl j fixed bin(31) based;
i=5;
p=addr(i);
p->j=p->j+1; /an other way to say i=i+1 */
put skip edit(i)(F(5)); /* -> 6 */
/* second form */
dcl i fixed bin(31);
dcl j fixed bin(31) based(p);
i=5;
p=addr(i);
j=j+1; /* an other way to say i=i+1 */
put skip edit(i)(F(5)); /* -> 6 */
/* cascading pointers */
dcl (p,q,s,t) pointer;
dcl (j,k) fixed bin(31) based;
dcl (i1,i2) fixed bin(31);
p=addr(i1); t=addr(i2), q=addr(p); s=addr(t);
q->p->j = s->t->k + 3; /* to say i1=i2+3 */
|
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #Pop11 | Pop11 | vars vec1, vec2;
;;; Create a vector and assign (reference to) it to vec1
consvector("a", "b", "c", 3) -> vec1;
;;; Copy (reference to) vector
vec1 -> vec2;
;;; Print value of vec1
vec1 =>
;;; Change first element of vec2
"d" -> vec2(1);
;;; Print value of vec1 -- the value changes because vec1 and
;;; vec2 reference the same vector
vec1 =>
|
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.
| #Haskell | Haskell | import Graphics.Gnuplot.Simple
pnts = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
doPlot = plotPathStyle [ ( Title "plotting dots" )]
(PlotStyle Points (CustomStyle [])) (zip [0..] pnts) |
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.
| #HicEst | HicEst | REAL :: n=10, x(n), y(n)
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)
WINDOW(WINdowhandle=wh, Width=-300, Height=-300, X=1, TItle='Rosetta')
AXIS(WINdowhandle=wh, Title='x values', Yaxis, Title='y values')
LINE(X=x, Y=y, SymbolDiameter=2) |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Factor | Factor | QUALIFIED: io ! there already is print in io
GENERIC: print ( shape -- )
TUPLE: point x y ;
C: <point> point ! shorthand constructor definition
M: point print drop "Point" io:print ;
TUPLE: circle radius x y ;
C: <circle> circle
M: circle print drop "Circle" io:print ; |
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
| #Forth | Forth | include lib/memcell.4th
include 4pp/lib/foos.4pp
:: Point ( xn n a--)
class
field: x \ x coordinate
field: y \ y coordinate
method: print \ print routine
method: setx \ set x coordinate
method: sety \ set y coordinate
method: getx \ get x coordinate
method: gety \ get y coordinate
end-class {
\ bind the methods immediately
:method { this -> x ! } ; defines setx
:method { this -> y ! } ; defines sety
:method { this -> x @ } ; defines getx
:method { this -> y @ } ; defines gety
\ because we'll use them immediately
:method { \ e.g. in this print routine
." Point(" this => getx 0 .r ." ," this => gety 0 .r ." )" cr
} ; defines print \ and this initialization
\ object or argument count
dup type@ this type@ = \ if it is an object, a point
if \ get the coordinates and set them
dup => getx this => setx
=> gety this => sety
else \ otherwise initialize it
0 dup this => setx this => sety
case \ and check the argument count
1 of this => setx endof \ one argument : x only
2 of this => setx \ two arguments: x and y
this => sety endof
endcase
then
private{ x y } \ make x and y private
}
;
:: Circle ( xn n a --)
over >r ( arg-count object-addr)
extends Point \ save the argument count!!
field: r \ radius
method: getr \ get radius
method: setr \ set radius
end-extends r> swap { \ retrieve count
\ bind the methods immediately
:method { this -> r ! } ; defines setr
:method { this -> r @ } ; defines getr
\ because we'll use them immediately
:method { \ e.g. in this print routine
." Circle(" this => getx 0 .r ." ,"
this => gety 0 .r ." ,"
this => getr 0 .r ." )" cr
} ; defines print \ and this initialization
\ object or argument count
dup type@ this type@ = \ if it is an object, a circle
if \ get the coordinates and set them
dup => getx this => setx
dup => gety this => sety
=> getr this => setr
else \ otherwise initialize it
0 this => setr
case \ and check the argument count
3 of this => setr \ three arguments: x, y and r
this => sety \ note the rest is already set
this => setx endof \ by "Point" and r was left on
endcase \ the stack!
then
private{ r }
}
;
0 new Point Point1
Point1 => print
45 23 2 new Point Point2
Point2 => print
Point2 new Point Point3
Point3 => print
78 1 new Point Point4
Point4 => print
10 45 23 3 new Circle Circle1
Circle1 => print
Point2 new Circle Circle2
Circle2 => print
Circle1 new Circle Circle3
Circle3 => print |
http://rosettacode.org/wiki/Poker_hand_analyser | Poker hand analyser | Task
Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
Example
2d (two of diamonds).
Faces are: a, 2, 3, 4, 5, 6, 7, 8, 9, 10, j, q, k
Suits are: h (hearts), d (diamonds), c (clubs), and s (spades), or
alternatively, the unicode card-suit characters: ♥ ♦ ♣ ♠
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
Examples
2♥ 2♦ 2♣ k♣ q♦: three-of-a-kind
2♥ 5♥ 7♦ 8♣ 9♠: high-card
a♥ 2♦ 3♣ 4♣ 5♦: straight
2♥ 3♥ 2♦ 3♣ 3♦: full-house
2♥ 7♥ 2♦ 3♣ 3♦: two-pair
2♥ 7♥ 7♦ 7♣ 7♠: four-of-a-kind
10♥ j♥ q♥ k♥ a♥: straight-flush
4♥ 4♠ k♠ 5♦ 10♠: one-pair
q♣ 10♣ 7♣ 6♣ q♣: invalid
The programs output for the above examples should be displayed here on this page.
Extra credit
use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
allow two jokers
use the symbol joker
duplicates would be allowed (for jokers only)
five-of-a-kind would then be the highest hand
More extra credit examples
joker 2♦ 2♠ k♠ q♦: three-of-a-kind
joker 5♥ 7♦ 8♠ 9♦: straight
joker 2♦ 3♠ 4♠ 5♠: straight
joker 3♥ 2♦ 3♠ 3♦: four-of-a-kind
joker 7♥ 2♦ 3♠ 3♦: three-of-a-kind
joker 7♥ 7♦ 7♠ 7♣: five-of-a-kind
joker j♥ q♥ k♥ A♥: straight-flush
joker 4♣ k♣ 5♦ 10♠: one-pair
joker k♣ 7♣ 6♣ 4♣: flush
joker 2♦ joker 4♠ 5♠: straight
joker Q♦ joker A♠ 10♠: straight
joker Q♦ joker A♦ 10♦: straight-flush
joker 2♦ 2♠ joker q♦: four-of-a-kind
Related tasks
Playing cards
Card shuffles
Deal cards_for_FreeCell
War Card_Game
Go Fish
| #Lua | Lua | -- Check whether t is a valid poker hand
function valid (t)
if #t ~= 5 then return false end
for k, v in pairs(t) do
for key, card in pairs(t) do
if v.value == card.value and
v.suit == card.suit and
k ~= key
then
return false
end
end
end
return true
end
-- Return numerical value of a single card
function cardValue (card)
local val = card:sub(1, -2)
local n = tonumber(val)
if n then return n end
if val == "j" then return 11 end
if val == "q" then return 12 end
if val == "k" then return 13 end
if val == "a" then return 1 end
error("Invalid card value: " .. val)
end
-- Detect whether hand t is a straight
function straight (t)
table.sort(t, function (a, b) return a.value < b.value end)
local ace, thisValue, lastValue = false
for i = 2, #t do
thisValue, lastValue = t[i].value, t[i-1].value
if lastValue == 1 then ace = i - 1 end
if thisValue ~= lastValue + 1 then
if ace then
t[ace].value = 14
return straight(t)
else
return false
end
end
end
return true
end
-- Detect whether hand t is a flush
function isFlush (t)
local suit = t[1].suit
for card = 2, #t do
if t[card].suit ~= suit then return false end
end
return true
end
-- Return a table of the count of each card value in hand t
function countValues (t)
local countTab, maxCount = {}, 0
for k, v in pairs(t) do
if countTab[v.value] then
countTab[v.value] = countTab[v.value] + 1
else
countTab[v.value] = 1
end
end
return countTab
end
-- Find the highest value in t
function highestCount (t)
local maxCount = 0
for k, v in pairs(t) do
if v > maxCount then maxCount = v end
end
return maxCount
end
-- Detect full-house and two-pair using the value counts in t
function twoTypes (t)
local threes, twos = 0, 0
for k, v in pairs(t) do
if v == 3 then threes = threes + 1 end
if v == 2 then twos = twos + 1 end
end
return threes, twos
end
-- Return the rank of a poker hand represented as a string
function rank (cards)
local hand = {}
for card in cards:gmatch("%S+") do
table.insert(hand, {value = cardValue(card), suit = card:sub(-1, -1)})
end
if not valid(hand) then return "invalid" end
local st, fl = straight(hand), isFlush(hand)
if st and fl then return "straight-flush" end
local valCount = countValues(hand)
local highCount = highestCount(valCount)
if highCount == 4 then return "four-of-a-kind" end
local n3, n2 = twoTypes(valCount)
if n3 == 1 and n2 == 1 then return "full-house" end
if fl then return "flush" end
if st then return "straight" end
if highCount == 3 then return "three-of-a-kind" end
if n3 == 0 and n2 == 2 then return "two-pair" end
if highCount == 2 then return "one-pair" end
return "high-card"
end
-- Main procedure
local testCases = {
"2h 2d 2c kc qd", -- three-of-a-kind
"2h 5h 7d 8c 9s", -- high-card
"ah 2d 3c 4c 5d", -- straight
"2h 3h 2d 3c 3d", -- full-house
"2h 7h 2d 3c 3d", -- two-pair
"2h 7h 7d 7c 7s", -- four-of-a-kind
"10h jh qh kh ah",-- straight-flush
"4h 4s ks 5d 10s",-- one-pair
"qc 10c 7c 6c 4c" -- flush
}
for _, case in pairs(testCases) do print(case, ": " .. rank(case)) 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.
| #Crystal | Crystal | struct Int
def evil?
self >= 0 && popcount.even?
end
end
puts "Powers of 3:", (0...30).map{|n| (3u64 ** n).popcount}.join(' ') # can also use &** (to prevent arithmetic overflow)
puts "Evil:" , 0.step.select(&.evil?).first(30).join(' ')
puts "Odious:", 0.step.reject(&.evil?).first(30).join(' ') |
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
| #Julia | Julia |
using Polynomials
p = Poly([-42,0,-12,1])
q = Poly([-3,1])
d, r = divrem(p,q)
println(p, " divided by ", q, " is ", d, " with remainder ", r, ".")
|
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Racket | Racket | #lang racket/base
(define (copy-prefab-struct str)
(apply make-prefab-struct (vector->list (struct->vector str))))
(struct point (x y) #:prefab)
(struct point/color point (color) #:prefab)
(let* ([original (point 0 0)]
[copied (copy-prefab-struct original)])
(displayln copied)
(displayln (eq? original copied)))
(let* ([original (point/color 0 0 'black)]
[copied (copy-prefab-struct original)])
(displayln copied)
(displayln (eq? original copied))) |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Raku | Raku | my Cool $x = 22/7 but role Fink { method brag { say "I'm a cool {self.WHAT.raku}!" }}
my Cool $y = $x.clone;
$y.brag; |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #REXX | REXX | /*REXX program to copy (polymorphically) one variable's value into another variable. */
b= 'old value.'
a= 123.45
b= a /*copy a variable's value into another.*/
if a==b then say "copy did work."
else say "copy didn't work." /*didn't work, maybe ran out of storage*/
/*stick a fork in it, we're all done. */ |
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.
| #Lua | Lua | function eval(a,b,c,x)
return a + (b + c * x) * x
end
function regression(xa,ya)
local n = #xa
local xm = 0.0
local ym = 0.0
local x2m = 0.0
local x3m = 0.0
local x4m = 0.0
local xym = 0.0
local x2ym = 0.0
for i=1,n do
xm = xm + xa[i]
ym = ym + ya[i]
x2m = x2m + xa[i] * xa[i]
x3m = x3m + xa[i] * xa[i] * xa[i]
x4m = x4m + xa[i] * xa[i] * xa[i] * xa[i]
xym = xym + xa[i] * ya[i]
x2ym = x2ym + xa[i] * xa[i] * ya[i]
end
xm = xm / n
ym = ym / n
x2m = x2m / n
x3m = x3m / n
x4m = x4m / n
xym = xym / n
x2ym = x2ym / n
local sxx = x2m - xm * xm
local sxy = xym - xm * ym
local sxx2 = x3m - xm * x2m
local sx2x2 = x4m - x2m * x2m
local sx2y = x2ym - x2m * ym
local b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
local c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
local a = ym - b * xm - c * x2m
print("y = "..a.." + "..b.."x + "..c.."x^2")
for i=1,n do
print(string.format("%2d %3d %3d", xa[i], ya[i], eval(a, b, c, xa[i])))
end
end
local xa = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
local ya = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
regression(xa, ya) |
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.
| #Factor | Factor | USING: kernel prettyprint sequences arrays sets hash-sets ;
IN: powerset
: add ( set elt -- newset ) 1array <hash-set> union ;
: powerset ( set -- newset ) members { HS{ } } [ dupd [ add ] curry map append ] reduce <hash-set> ; |
http://rosettacode.org/wiki/Primality_by_trial_division | Primality by trial division | Task
Write a boolean function that tells whether a given integer is prime.
Remember that 1 and all non-positive numbers are not prime.
Use trial division.
Even numbers greater than 2 may be eliminated right away.
A loop from 3 to √ n will suffice, but other loops are allowed.
Related tasks
count in factors
prime decomposition
AKS test for primes
factors of an integer
Sieve of Eratosthenes
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
| #Chapel | Chapel | proc is_prime(n)
{
if n == 2 then
return true;
if n <= 1 || n % 2 == 0 then
return false;
for i in 3..floor(sqrt(n)):int by 2 do
if n % i == 0 then
return false;
return true;
} |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #HicEst | HicEst | DIMENSION upperbound(20), rescaleTo(20), temp(20)
upperbound = (.06,.11,.16,.21,.26,.31,.36,.41,.46,.51,.56,.61,.66,.71,.76,.81,.86,.91,.96,1.01)
rescaleTo = (.10,.18,.26,.32,.38,.44,.50,.54,.58,.62,.66,.70,.74,.78,.82,.86,.90,.94,.98,1.00)
DO test = 1, 10
value = RAN(0.5, 0.5)
temp = value > upperbound
PriceFraction = rescaleTo( INDEX(temp, 0) )
WRITE(Format="F8.6, F6.2") value, PriceFraction
ENDDO |
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
| #MATLAB | MATLAB | function D=pd(N)
K=1:ceil(N/2);
D=K(~(rem(N, K))); |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #ReScript | ReScript | let p = [
("Aleph", 1.0 /. 5.0),
("Beth", 1.0 /. 6.0),
("Gimel", 1.0 /. 7.0),
("Daleth", 1.0 /. 8.0),
("He", 1.0 /. 9.0),
("Waw", 1.0 /. 10.0),
("Zayin", 1.0 /. 11.0),
("Heth", 1759.0 /. 27720.0),
]
let prob_take = (arr, k) => {
let rec aux = (i, k) => {
let (v, p) = arr[i]
if k < p { v } else { aux(i+1, (k -. p)) }
}
aux(0, k)
}
{
let n = 1_000_000
let h = Belt.HashMap.String.make(~hintSize=10)
Js.Array2.forEach(p, ((v, _)) =>
Belt.HashMap.String.set(h, v, 0)
)
let tot = Js.Array2.reduce(p, (acc, (_, prob)) => acc +. prob, 0.0)
for _ in 1 to n {
let sel = prob_take(p, tot *. Js.Math.random())
let _n = Belt.HashMap.String.get(h, sel)
let n = Belt.Option.getExn(_n)
Belt.HashMap.String.set(h, sel, (n+1)) /* count the number of each item */
}
Printf.printf("Event expected occurred\n")
Js.Array2.forEach(p, ((v, p)) => {
let _d = Belt.HashMap.String.get(h, v)
let d = Belt.Option.getExn(_d)
Printf.printf("%s \t %8.5g %8.5g\n", v, p, float(d) /. float(n))
}
)
} |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #REXX | REXX | /*REXX program displays results of probabilistic choices, gen random #s per probability.*/
parse arg trials digs seed . /*obtain the optional arguments from CL*/
if trials=='' | trials=="," then trials= +1e6 /*Not specified? Then use the default.*/
if digs=='' | digs=="," then digs= 15 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /*allows repeatability for RANDOM nums.*/
numeric digits digs /*use a specific number of decimal digs*/
names= 'aleph beth gimel daleth he waw zayin heth ───totals───►' /*names of the cells.*/
hi= 100000 /*max REXX RANDOM num*/
z= words(names); #= z - 1 /*#: the number of actual/usable names.*/
$= 0 /*initialize sum of the probabilities. */
do n=1 for #; prob.n= 1 / (n+4); if n==# then prob.n= 1759 / 27720
$= $ + prob.n; Hprob.n= prob.n * hi /*spread the range of probabilities. */
end /*n*/
prob.z= $ /*define the value of the ───totals───.*/
@.= 0 /*initialize all counters in the range.*/
@.z= trials /*define the last counter of " " */
do j=1 for trials; r= random(hi) /*gen TRIAL number of random numbers.*/
do k=1 for # /*for each cell, compute percentages. */
if r<=Hprob.k then @.k= @.k + 1 /* " " " range, bump the counter*/
end /*k*/
end /*j*/
_= '═' /*_: padding used by the CENTER BIF.*/
w= digs + 6 /*W: display width for the percentages*/
d= 4 + max( length(trials), length('count') ) /* [↓] display a formatted top header.*/
say center('name',15,_) center('count',d,_) center('target %',w,_) center('actual %',w,_)
do cell=1 for z /*display each of the cells and totals.*/
say ' ' left( word(names, cell), 13) right(@.cell, d-2) " " ,
left( format( prob.cell * 100, d), w-2) ,
left( format( @.cell/trials * 100, d), w-2) /* [↓] foot title. [↓] */
if cell==# then say center(_,15,_) center(_,d,_) center(_,w,_) center(_,w,_)
end /*c*/ /*stick a fork in it, we are all done.*/ |
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.
| #OxygenBasic | OxygenBasic |
'PRIORITY QUEUE WITH 16 LEVELS
uses console
% pl 16 'priority levels
===================
Class PriorityQueue
===================
indexbase 1
bstring buf[pl] 'buffers to hold priority queues content
int bg[pl] 'buffers base offset
int i[pl] 'indexers
int le[pl] 'length of buffer
method constructor()
====================
int p
for p=1 to pl
buf[p]=""
le[p]=0
bg[p]=0
i=[p]=0
next
end method
method destructor()
===================
int p
for p=1 to pl
del (buf[p])
le[p]=0
bg[p]=0
i=[p]=0
next
end method
method Encodelength(int ls,p)
=============================
int ll at i[p]+strptr(buf[p])
ll=ls
i[p]+=sizeof int
end method
method limit(int*p)
===================
if p>pl
p=pl
endif
if p<1
p=1
endif
end method
method push(string s,int p)
=============================
limit p
int ls
ls=len s
if i[p]+ls+8 > le[p] then
int e=8000+(ls*2) 'extra buffer bytes
buf[p]=buf[p]+nuls e 'extend buf
le[p]=len buf[p]
end if
EncodeLength ls,p 'length of input s
mid buf[p],i[p]+1,s 'patch in s
i[p]+=ls
end method
method popLength(int p) as int
==============================
if bg[p]>=i[p]
return -1 'buffer empty
endif
int ll at (bg[p]+strptr buf[p])
bg[p]+=sizeof int
return ll
end method
method pop(string *s, int *p=1, lpl=0) as int
=============================================
limit p
int ls
do
ls=popLength p
if ls=-1
if not lpl 'lpl: lock priority level
p++ 'try next priority level
if p<=pl
continue do
endif
endif
s=""
return ls 'empty buffers
endif
exit do
loop
s=mid buf[p],bg[p]+1,ls
bg[p]+=ls
'cleanup buffer
if bg[p]>1e6 then
buf[p]=mid buf[p],bg[p]+1 'remove old popped data
le[p]=len buf[p]
i[p]-=bg[p] 'shrink buf
bg[p]=0
end if
end method
method clear()
==============
constructor
end method
end class 'PriorityQueue
'====
'DEMO
'====
new PriorityQueue medo()
string s
def inp
medo.push %2,%1
end def
' Priority Task
' ══════════ ════════════════
inp 3 "Clear drains"
inp 4 "Feed cat"
inp 5 "Make tea"
inp 1 "Solve RC tasks"
inp 2 "Tax return"
inp 4 "Plant beans"
'
int er
int p
print "Priority Task" cr
print "=================" cr
do
er=medo.pop s,p
if er=-1
print "(buffer empty)"
exit do
endif
print p tab s cr
loop
pause
del medo
/*
RESULTS:
Priority Task
=================
1 Solve RC tasks
2 Tax return
3 Clear drains
4 Feed cat
4 Plant beans
5 Make tea
(buffer empty)
*/
|
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
| #zkl | zkl | fcn tri(lim,a=3,b=4,c=5){
p:=a + b + c;
if(p>lim) return(0,0);
T(1,lim/p).zipWith('+,
tri(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c),
tri(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c),
tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c)
);
} |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #Visual_Basic | Visual Basic | Sub Main()
'...
If problem Then
For n& = Forms.Count To 0 Step -1
Unload Forms(n&)
Next
Exit Sub
End If
'...
End Sub |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #Wren | Wren | import "io" for Stdin, Stdout
System.write("Do you want to terminate the program y/n ? ")
Stdout.flush()
var yn = Stdin.readLine()
if (yn == "y" || yn == "Y") {
System.print("OK, shutting down")
Fiber.suspend() // return to OS
}
System.print("OK, carrying on") |
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
| #FALSE | FALSE | [2[\$@$$*@>~][\$@$@$@$@\/*=$[%$." "$@\/\0~]?~[1+1|]?]#%.]d:
27720d;! {2 2 2 3 3 5 7 11} |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #PureBasic | PureBasic | Define varA.i = 5, varB.i = 0, *myInteger.Integer
*myInteger = @varA ;set pointer to address of an integer variable
varB = *myInteger\i + 3 ;set variable to the 3 + value of dereferenced pointer, i.e varB = 8 |
http://rosettacode.org/wiki/Pointers_and_references | Pointers and references |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In this task, the goal is to demonstrate common operations on pointers and references. These examples show pointer operations on the stack, which can be dangerous and is rarely done. Pointers and references are commonly used along with Memory allocation on the heap.
| #Python | Python | # Bind a literal string object to a name:
a = "foo"
# Bind an empty list to another name:
b = []
# Classes are "factories" for creating new objects: invoke class name as a function:
class Foo(object):
pass
c = Foo()
# Again, but with optional initialization:
class Bar(object):
def __init__(self, initializer = None)
# "initializer is an arbitrary identifier, and "None" is an arbitrary default value
if initializer is not None:
self.value = initializer
d = Bar(10)
print d.value
# Test if two names are references to the same object:
if a is b: pass
# Alternatively:
if id(a) == id(b): pass
# Re-bind a previous used name to a function:
def a(fmt, *args):
if fmt is None:
fmt = "%s"
print fmt % (args)
# Append reference to a list:
b.append(a)
# Unbind a reference:
del(a)
# Call (anymous function object) from inside a list
b[0]("foo") # Note that the function object we original bound to the name "a" continues to exist
# even if its name is unbound or rebound to some other object. |
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.
| #Icon_and_Unicon | Icon and Unicon | link printf,numbers
procedure main()
x := [0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]
y := [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
Plot(x,y,600,400)
end
$define POINTR 2 # Point Radius
$define POINTC "red" # Point Colour
$define GRIDC "grey" # grid colour
$define AXISC "black" # axis/label colour
$define BORDER 60 # per side border
$define TICKS 5. # grid ticks per axis
$define AXISFH 20 # font height for axis labels
procedure Plot(x,y,cw,ch)
/cw := 700 # default dimensions
/ch := 400
uw := cw-BORDER*2 # usable dimensions
uh := ch-BORDER*2
wparms := ["Plot","g",
sprintf("size=%d,%d",cw,ch),
"bg=white"] # base window parms
dx := sprintf("dx=%d",BORDER) # grid origin
dy := sprintf("dy=%d",BORDER)
&window := open!wparms | stop("Unable to open window")
X := scale(x,uw) # scale data to usable space
Y := scale(y,uh,"invert")
WAttrib(dx,dy) # set origin=grid & draw grid
every x := (X.tickfrom to X.tickto by X.tick) * X.tickscale do {
if x = 0 then Fg(AXISC) else Fg(GRIDC)
DrawLine(x,Y.tickfrom*Y.tickscale,x,Y.tickto*Y.tickscale)
}
every y := (Y.tickfrom to Y.tickto by Y.tick) * Y.tickscale do {
if y = uh then Fg(AXISC) else Fg(GRIDC)
DrawLine(X.tickfrom*X.tickscale,y,X.tickto*X.tickscale,y)
}
Fg(POINTC) # draw data points ....
every i := 1 to *X.scaled do
FillCircle(X.scaled[i],Y.scaled[i],POINTR)
Fg(AXISC) # label grid
WAttrib(dx,"dy=0") # label X axis
Font(sprintf("Helvetica,%d",AXISFH))
ytxt := ch-BORDER+1+(WAttrib("ascent") - WAttrib("descent"))/2
every x := X.tickscale * (xv := X.tickfrom to X.tickto by X.tick) do
DrawString(x - TextWidth(xv)/2, ytxt + integer(AXISFH*1.5),xv)
WAttrib("dx=0",dy) # label Y axis
every y := Y.tickscale * (yv := Y.tickfrom to Y.tickto by Y.tick) do
DrawString(BORDER/2 - TextWidth(yv)/2, ytxt - BORDER - y,yv)
WriteImage(sprintf("PlotPoints-%d.gif",&now)) # save image
WAttrib("dx=0","dy=0") # close off nicely
Font("Helvetica,10")
DrawString(10,ch-5,"Right click to exit")
until Event() == &rpress # wait for left mouse button
close(&window)
end
record scaledata(low,high,range,pix,raw,scaled,tick,tickfrom,tickto,tickscale)
procedure scale(data,pix,opts[])
P :=scaledata( pmin := min!data, pmax := max!data,
prange := real(pmax-pmin), pix,
data,q :=[])
/ticks := TICKS
P.tick := ceil(prange/(10^(k:=floor(log(prange,10))))*(10^k)/ticks)
P.tickfrom := P.tick*floor(pmin/P.tick)
P.tickto := P.tick*ceil(pmax/P.tick)
P.tickscale := real(pix)/(P.tickto-P.tickfrom)
every put(q,integer((!data-P.tickfrom)*P.tickscale))
if !opts == "invert" then # invert is for y
every q[i := 1 to *q] := pix - q[i]
return P
end |
http://rosettacode.org/wiki/Polymorphism | Polymorphism | Task
Create two classes Point(x,y) and Circle(x,y,r) with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
| #Fortran | Fortran |
module geom
type point
real(8), private :: x = 0
real(8), private :: y = 0
contains
procedure, public :: get_x
procedure, public :: get_y
procedure, public :: set_x
procedure, public :: set_y
procedure, public :: print => print_point
procedure, pass :: copy_point
!overloaded assignment operator
generic, public :: assignment(=) => copy_point
end type point
type, extends(point) :: circle
real(8), private :: r = 0
contains
procedure, public :: get_r
procedure, public :: set_r
procedure, public :: print => print_circle
procedure, pass :: copy_circle
!overloaded assignment operator
generic, public :: assignment(=) => copy_circle
end type circle
! constructor interface
interface circle
module procedure circle_constructor
end interface circle
! constructor interface
interface point
module procedure point_constructor
end interface point
contains
real(8) function get_x(this)
class(point), intent(in) :: this
get_x = this%x
end function get_x
real(8) function get_y(this)
class(point), intent(in) :: this
get_y = this%y
end function get_y
subroutine set_x(this, val)
class(point), intent(inout) :: this
real(8), intent(in) :: val
this%x = val
end subroutine set_x
subroutine set_y(this, val)
class(point), intent(inout) :: this
real(8), intent(in) :: val
this%y = val
end subroutine set_y
subroutine print_point(this)
class(point), intent(in) :: this
write(*,'(2(a,f0.4),a)') 'Point(',this%x,', ',this%y,')'
end subroutine print_point
real(8) function get_r(this)
class(circle), intent(in) :: this
get_r = this%r
end function get_r
subroutine set_r(this, val)
class(circle), intent(inout) :: this
real(8), intent(in) :: val
this%r = val
end subroutine set_r
subroutine print_circle(this)
class(circle), intent(in) :: this
write(*,'(3(a,f0.4),a)') 'Circle(',this%x,', ',this%y,'; ',this%r,')'
end subroutine print_circle
subroutine copy_point(this, rhs)
class(point), intent(inout) :: this
type(point), intent(in) :: rhs
this%x = rhs%x
this%y = rhs%y
end subroutine copy_point
subroutine copy_circle(this, rhs)
class(circle), intent(inout) :: this
type(circle), intent(in) :: rhs
this%x = rhs%x
this%y = rhs%y
this%r = rhs%r
end subroutine copy_circle
! non-default constructor to init private components
type(point) function point_constructor(x,y)
real(8), intent(in) :: x,y
point_constructor%x = x
point_constructor%y = y
end function point_constructor
! non-default constructor to init private components
type(circle) function circle_constructor(x,y,r)
real(8), intent(in) :: x,y,r
circle_constructor%x = x
circle_constructor%y = y
circle_constructor%r = r
end function circle_constructor
end module geom
program inh
use geom
type(point) :: p, p_copy
type(circle) :: c, c_copy
p = point(2.0d0, 3.0d0)
call p%print
p_copy = p
call p_copy%print
c = circle(3.0d0, 4.0d0, 5.0d0)
call c%print
c_copy = c
call c_copy%print
end program inh
|
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
| #Nim | Nim | import algorithm, sequtils, strutils, tables, unicode
type
Suit* = enum ♠, ♥, ♦, ♣
Face* {.pure.} = enum
Ace = (1, "a")
Two = (2, "2")
Three = (3, "3")
Four = (4, "4")
Five = (5, "5")
Six = (6, "6")
Seven = (7, "7")
Eight = (8, "8")
Nine = (9, "9")
Ten = (10, "10")
Jack = (11, "j")
Queen = (12, "q")
King = (13, "k")
Card* = tuple[face: Face; suit: Suit]
Hand* = array[5, Card]
HandValue {.pure.} = enum
Invalid = "invalid"
StraightFlush = "straight-flush"
FourOfAKind = "four-of-a-kind"
FullHouse = "full-house"
Flush = "flush"
Straight = "straight"
ThreeOfAKind = "three-of-a-kind"
TwoPair = "two-pair"
OnePair = "one-pair"
HighCard = "high-card"
CardError = object of ValueError
proc toCard(cardStr: string): Card =
## Convert a card string to a Card.
var runes = cardStr.toRunes
let suitStr = $(runes.pop()) # Extract the suit.
let faceStr = $runes # Take what’s left as the face.
try:
result.face = parseEnum[Face](faceStr)
except ValueError:
raise newException(CardError, "wrong face: " & faceStr)
try:
result.suit = parseEnum[Suit](suitStr)
except ValueError:
raise newException(CardError, "wrong suit: " & suitStr)
proc value(hand: openArray[Card]): HandValue =
## Return the value of a hand.
doAssert hand.len == 5, "Hand must have five cards."
var
cards: seq[Card] # The cards.
faces: CountTable[Face] # Count faces.
suits: CountTable[Suit] # Count suits.
for card in hand:
if card in cards: return Invalid # Duplicate card.
cards.add card
faces.inc card.face
suits.inc card.suit
faces.sort() # Greatest counts first.
suits.sort() # Greatest counts first.
cards.sort() # Smallest faces first.
# Check faces.
for face, count in faces:
case count
of 4:
return FourOfAKind
of 3:
result = ThreeOfAKind
of 2:
if result == ThreeOfAKind: return FullHouse
if result == OnePair: return TwoPair
result = OnePair
else:
if result != Invalid: return
# Search straight.
result = Straight
let start = if cards[0].face == Ace and cards[4].face == King: 2 else: 1
for n in start..4:
if cards[n].face != succ(cards[n - 1].face):
result = HighCard # No straight.
break
# Check suits.
if suits.len == 1: # A single suit.
result = if result == Straight: StraightFlush else: Flush
proc `$`(card: Card): string =
## Return the representation of a card.
var val = 0x1F0A0 + ord(card.suit) * 0x10 + ord(card.face)
if card.face >= Queen: inc val # Skip Knight.
result = $Rune(val)
when isMainModule:
const HandStrings = ["2♥ 2♦ 2♣ k♣ q♦",
"2♥ 5♥ 7♦ 8♣ 9♠",
"a♥ 2♦ 3♣ 4♣ 5♦",
"2♥ 3♥ 2♦ 3♣ 3♦",
"2♥ 7♥ 2♦ 3♣ 3♦",
"2♥ 7♥ 7♦ 7♣ 7♠",
"10♥ j♥ q♥ k♥ a♥",
"4♥ 4♠ k♠ 5♦ 10♠",
"q♣ 10♣ 7♣ 6♣ 4♣",
"4♥ 4♣ 4♥ 4♠ 4♦"]
for handString in HandStrings:
let hand = handString.split(' ').map(toCard)
echo hand.map(`$`).join(" "), " → ", hand.value |
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.
| #D | D | void main() {
import std.stdio, std.algorithm, std.range, core.bitop;
enum pCount = (ulong n) => popcnt(n & uint.max) + popcnt(n >> 32);
writefln("%s\nEvil: %s\nOdious: %s",
uint.max.iota.map!(i => pCount(3L ^^ i)).take(30),
uint.max.iota.filter!(i => pCount(i) % 2 == 0).take(30),
uint.max.iota.filter!(i => pCount(i) % 2).take(30));
} |
http://rosettacode.org/wiki/Polynomial_long_division | Polynomial long division |
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
In algebra, polynomial long division is an algorithm for dividing a polynomial by another polynomial of the same or lower degree.
Let us suppose a polynomial is represented by a vector,
x
{\displaystyle x}
(i.e., an ordered collection of coefficients) so that the
i
{\displaystyle i}
th element keeps the coefficient of
x
i
{\displaystyle x^{i}}
, and the multiplication by a monomial is a shift of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial.
Then a pseudocode for the polynomial long division using the conventions described above could be:
degree(P):
return the index of the last non-zero element of P;
if all elements are 0, return -∞
polynomial_long_division(N, D) returns (q, r):
// N, D, q, r are vectors
if degree(D) < 0 then error
q ← 0
while degree(N) ≥ degree(D)
d ← D shifted right by (degree(N) - degree(D))
q(degree(N) - degree(D)) ← N(degree(N)) / d(degree(d))
// by construction, degree(d) = degree(N) of course
d ← d * q(degree(N) - degree(D))
N ← N - d
endwhile
r ← N
return (q, r)
Note: vector * scalar multiplies each element of the vector by the scalar; vectorA - vectorB subtracts each element of the vectorB from the element of the vectorA with "the same index". The vectors in the pseudocode are zero-based.
Error handling (for allocations or for wrong inputs) is not mandatory.
Conventions can be different; in particular, note that if the first coefficient in the vector is the highest power of x for the polynomial represented by the vector, then the algorithm becomes simpler.
Example for clarification
This example is from Wikipedia, but changed to show how the given pseudocode works.
0 1 2 3
----------------------
N: -42 0 -12 1 degree = 3
D: -3 1 0 0 degree = 1
d(N) - d(D) = 2, so let's shift D towards right by 2:
N: -42 0 -12 1
d: 0 0 -3 1
N(3)/d(3) = 1, so d is unchanged. Now remember that "shifting by 2"
is like multiplying by x2, and the final multiplication
(here by 1) is the coefficient of this monomial. Let's store this
into q:
0 1 2
---------------
q: 0 0 1
now compute N - d, and let it be the "new" N, and let's loop
N: -42 0 -9 0 degree = 2
D: -3 1 0 0 degree = 1
d(N) - d(D) = 1, right shift D by 1 and let it be d
N: -42 0 -9 0
d: 0 -3 1 0 * -9/1 = -9
q: 0 -9 1
d: 0 27 -9 0
N ← N - d
N: -42 -27 0 0 degree = 1
D: -3 1 0 0 degree = 1
looping again... d(N)-d(D)=0, so no shift is needed; we
multiply D by -27 (= -27/1) storing the result in d, then
q: -27 -9 1
and
N: -42 -27 0 0 -
d: 81 -27 0 0 =
N: -123 0 0 0 (last N)
d(N) < d(D), so now r ← N, and the result is:
0 1 2
-------------
q: -27 -9 1 → x2 - 9x - 27
r: -123 0 0 → -123
Related task
Polynomial derivative
| #Kotlin | Kotlin | // version 1.1.51
typealias IAE = IllegalArgumentException
data class Solution(val quotient: DoubleArray, val remainder: DoubleArray)
fun polyDegree(p: DoubleArray): Int {
for (i in p.size - 1 downTo 0) {
if (p[i] != 0.0) return i
}
return Int.MIN_VALUE
}
fun polyShiftRight(p: DoubleArray, places: Int): DoubleArray {
if (places <= 0) return p
val pd = polyDegree(p)
if (pd + places >= p.size) {
throw IAE("The number of places to be shifted is too large")
}
val d = p.copyOf()
for (i in pd downTo 0) {
d[i + places] = d[i]
d[i] = 0.0
}
return d
}
fun polyMultiply(p: DoubleArray, m: Double) {
for (i in 0 until p.size) p[i] *= m
}
fun polySubtract(p: DoubleArray, s: DoubleArray) {
for (i in 0 until p.size) p[i] -= s[i]
}
fun polyLongDiv(n: DoubleArray, d: DoubleArray): Solution {
if (n.size != d.size) {
throw IAE("Numerator and denominator vectors must have the same size")
}
var nd = polyDegree(n)
val dd = polyDegree(d)
if (dd < 0) {
throw IAE("Divisor must have at least one one-zero coefficient")
}
if (nd < dd) {
throw IAE("The degree of the divisor cannot exceed that of the numerator")
}
val n2 = n.copyOf()
val q = DoubleArray(n.size) // all elements zero by default
while (nd >= dd) {
val d2 = polyShiftRight(d, nd - dd)
q[nd - dd] = n2[nd] / d2[nd]
polyMultiply(d2, q[nd - dd])
polySubtract(n2, d2)
nd = polyDegree(n2)
}
return Solution(q, n2)
}
fun polyShow(p: DoubleArray) {
val pd = polyDegree(p)
for (i in pd downTo 0) {
val coeff = p[i]
if (coeff == 0.0) continue
print (when {
coeff == 1.0 -> if (i < pd) " + " else ""
coeff == -1.0 -> if (i < pd) " - " else "-"
coeff < 0.0 -> if (i < pd) " - ${-coeff}" else "$coeff"
else -> if (i < pd) " + $coeff" else "$coeff"
})
if (i > 1) print("x^$i")
else if (i == 1) print("x")
}
println()
}
fun main(args: Array<String>) {
val n = doubleArrayOf(-42.0, 0.0, -12.0, 1.0)
val d = doubleArrayOf( -3.0, 1.0, 0.0, 0.0)
print("Numerator : ")
polyShow(n)
print("Denominator : ")
polyShow(d)
println("-------------------------------------")
val (q, r) = polyLongDiv(n, d)
print("Quotient : ")
polyShow(q)
print("Remainder : ")
polyShow(r)
} |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Ruby | Ruby | class T
def name
"T"
end
end
class S
def name
"S"
end
end
obj1 = T.new
obj2 = S.new
puts obj1.dup.name # prints "T"
puts obj2.dup.name # prints "S" |
http://rosettacode.org/wiki/Polymorphic_copy | Polymorphic copy | An object is polymorphic when its specific type may vary.
The types a specific value may take, is called class.
It is trivial to copy an object if its type is known:
int x;
int y = x;
Here x is not polymorphic, so y is declared of same type (int) as x.
But if the specific type of x were unknown, then y could not be declared of any specific type.
The task: let a polymorphic object contain an instance of some specific type S derived from a type T.
The type T is known.
The type S is possibly unknown until run time.
The objective is to create an exact copy of such polymorphic object (not to create a reference, nor a pointer to).
Let further the type T have a method overridden by S.
This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S.
| #Scala | Scala | object PolymorphicCopy {
def main(args: Array[String]) {
val a: Animal = Dog("Rover", 3, "Terrier")
val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog
println(s"Dog 'a' = $a") // implicitly calls Dog.toString()
println(s"Dog 'b' = $b") // ditto
println(s"Dog 'a' is ${if (a == b) "" else "not"} the same object as Dog 'b'")
}
case class Animal(name: String, age: Int) {
override def toString = s"Name: $name, Age: $age"
}
case class Dog(override val name: String, override val age: Int, breed: String) extends Animal(name, age) {
override def toString = super.toString() + s", Breed: $breed"
}
} |
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.
| #Maple | Maple | with(CurveFitting);
PolynomialInterpolation([[0, 1], [1, 6], [2, 17], [3, 34], [4, 57], [5, 86], [6, 121], [7, 162], [8, 209], [9, 262], [10, 321]], 'x');
|
http://rosettacode.org/wiki/Power_set | Power set | A set is a collection (container) of certain values,
without any particular order, and no repeated values.
It corresponds with a finite set in mathematics.
A set can be implemented as an associative array (partial mapping)
in which the value of each key-value pair is ignored.
Given a set S, the power set (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
Task
By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S.
For example, the power set of {1,2,3,4} is
{{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}.
For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of empty set.
The power set of the empty set is the set which contains itself (20 = 1):
P
{\displaystyle {\mathcal {P}}}
(
∅
{\displaystyle \varnothing }
) = {
∅
{\displaystyle \varnothing }
}
And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
P
{\displaystyle {\mathcal {P}}}
({
∅
{\displaystyle \varnothing }
}) = {
∅
{\displaystyle \varnothing }
, {
∅
{\displaystyle \varnothing }
} }
Extra credit: Demonstrate that your language supports these last two powersets.
| #Forth | Forth | : ?print dup 1 and if over args type space then ;
: .set begin dup while ?print >r 1+ r> 1 rshift repeat drop drop ;
: .powerset 0 do ." ( " 1 i .set ." )" cr loop ;
: check-none dup 2 < abort" Usage: powerset [val] .. [val]" ;
: check-size dup /cell 8 [*] >= abort" Set too large" ;
: powerset 1 argn check-none check-size 1- lshift .powerset ;
powerset |
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
| #Clojure | Clojure | (defn divides? [k n] (zero? (mod k n))) |
http://rosettacode.org/wiki/Price_fraction | Price fraction | A friend of mine runs a pharmacy. He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value. This value is regulated by a government department.
Task
Given a floating point value between 0.00 and 1.00, rescale according to the following table:
>= 0.00 < 0.06 := 0.10
>= 0.06 < 0.11 := 0.18
>= 0.11 < 0.16 := 0.26
>= 0.16 < 0.21 := 0.32
>= 0.21 < 0.26 := 0.38
>= 0.26 < 0.31 := 0.44
>= 0.31 < 0.36 := 0.50
>= 0.36 < 0.41 := 0.54
>= 0.41 < 0.46 := 0.58
>= 0.46 < 0.51 := 0.62
>= 0.51 < 0.56 := 0.66
>= 0.56 < 0.61 := 0.70
>= 0.61 < 0.66 := 0.74
>= 0.66 < 0.71 := 0.78
>= 0.71 < 0.76 := 0.82
>= 0.76 < 0.81 := 0.86
>= 0.81 < 0.86 := 0.90
>= 0.86 < 0.91 := 0.94
>= 0.91 < 0.96 := 0.98
>= 0.96 < 1.01 := 1.00
| #Icon_and_Unicon | Icon and Unicon |
record Bounds(low,high,new)
# rescale given value according to a list of bounds
procedure rescale (i, bounds)
every bound := !bounds do
if bound.low <= i < bound.high
then return bound.new
return fail # could not find i in bounds
end
procedure main ()
bounds := [
Bounds(0.00, 0.06, 0.10),
Bounds(0.06, 0.11, 0.18),
Bounds(0.11, 0.16, 0.26),
Bounds(0.16, 0.21, 0.32),
Bounds(0.21, 0.26, 0.38),
Bounds(0.26, 0.31, 0.44),
Bounds(0.31, 0.36, 0.50),
Bounds(0.36, 0.41, 0.54),
Bounds(0.41, 0.46, 0.58),
Bounds(0.46, 0.51, 0.62),
Bounds(0.51, 0.56, 0.66),
Bounds(0.56, 0.61, 0.70),
Bounds(0.61, 0.66, 0.74),
Bounds(0.66, 0.71, 0.78),
Bounds(0.71, 0.76, 0.82),
Bounds(0.76, 0.81, 0.86),
Bounds(0.81, 0.86, 0.90),
Bounds(0.86, 0.91, 0.94),
Bounds(0.91, 0.96, 0.98),
Bounds(0.96, 1.01, 1.00)
]
# test the procedure
every i := 0.00 to 1.00 by 0.1 do {
write (i || " rescaled is " || rescale(i, bounds))
}
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
| #Modula-2 | Modula-2 | MODULE ProperDivisors;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
FormatString("%i", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE proper_divisors(n : INTEGER; print_flag : BOOLEAN) : INTEGER;
VAR count,i : INTEGER;
BEGIN
count := 0;
FOR i:=1 TO n-1 DO
IF n MOD i = 0 THEN
INC(count);
IF print_flag THEN
WriteInt(i);
WriteString(" ")
END
END
END;
IF print_flag THEN WriteLn END;
RETURN count;
END proper_divisors;
VAR
buf : ARRAY[0..63] OF CHAR;
i,max,max_i,v : INTEGER;
BEGIN
FOR i:=1 TO 10 DO
WriteInt(i);
WriteString(": ");
proper_divisors(i, TRUE)
END;
max := 0;
max_i := 1;
FOR i:=1 TO 20000 DO
v := proper_divisors(i, FALSE);
IF v>= max THEN
max := v;
max_i := i
END
END;
FormatString("%i with %i divisors\n", buf, max_i, max);
WriteString(buf);
ReadChar
END ProperDivisors. |
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Ring | Ring |
# Project : Probabilistic choice
cnt = list(8)
item = ["aleph","beth","gimel","daleth","he","waw","zayin","heth"]
prob = [1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720]
for trial = 1 to 1000000
r = random(10)/10
p = 0
for i = 1 to len(prob)
p = p + prob[i]
if r < p
cnt[i] = cnt[i] + 1
loop
ok
next
next
see "item actual theoretical" + nl
for i = 1 to len(item)
see "" + item[i] + " " + cnt[i]/1000000 + " " + prob[i] + nl
next
|
http://rosettacode.org/wiki/Probabilistic_choice | Probabilistic choice | Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values.
The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
aleph 1/5.0
beth 1/6.0
gimel 1/7.0
daleth 1/8.0
he 1/9.0
waw 1/10.0
zayin 1/11.0
heth 1759/27720 # adjusted so that probabilities add to 1
Related task
Random number generator (device)
| #Ruby | Ruby | probabilities = {
"aleph" => 1/5.0,
"beth" => 1/6.0,
"gimel" => 1/7.0,
"daleth" => 1/8.0,
"he" => 1/9.0,
"waw" => 1/10.0,
"zayin" => 1/11.0,
}
probabilities["heth"] = 1.0 - probabilities.each_value.inject(:+)
ordered_keys = probabilities.keys
sum, sums = 0.0, {}
ordered_keys.each do |key|
sum += probabilities[key]
sums[key] = sum
end
actual = Hash.new(0)
samples = 1_000_000
samples.times do
r = rand
for k in ordered_keys
if r < sums[k]
actual[k] += 1
break
end
end
end
puts "key expected actual diff"
for k in ordered_keys
act = Float(actual[k]) / samples
val = probabilities[k]
printf "%-8s%.8f %.8f %6.3f %%\n", k, val, act, 100*(act-val)/val
end |
http://rosettacode.org/wiki/Priority_queue | Priority queue | A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
Task
Create a priority queue. The queue must support at least two operations:
Insertion. An element is added to the queue with a priority (a numeric value).
Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
Priority Task
══════════ ════════════════
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| #Pascal | Pascal |
program PriorityQueueTest;
uses Classes;
Type
TItem = record
Priority:Integer;
Value:string;
end;
PItem = ^TItem;
TPriorityQueue = class(Tlist)
procedure Push(Priority:Integer;Value:string);
procedure SortPriority();
function Pop():String;
function Empty:Boolean;
end;
{ TPriorityQueue }
procedure TPriorityQueue.Push(Priority:Integer;Value:string);
var
Item: PItem;
begin
new(Item);
Item^.Priority := Priority;
Item^.Value := Value;
inherited Add(Item);
SortPriority();
end;
procedure TPriorityQueue.SortPriority();
var
i,j:Integer;
begin
if(Count < 2) Then Exit();
for i:= 0 to Count-2 do
for j:= i+1 to Count-1 do
if ( PItem(Items[i])^.Priority > PItem(Items[j])^.Priority)then
Exchange(i,j);
end;
function TPriorityQueue.Pop():String;
begin
if count = 0 then
Exit('');
result := PItem(First)^.value;
Dispose(PItem(First));
Delete(0);
end;
function TPriorityQueue.Empty:Boolean;
begin
Result := Count = 0;
end;
var
Queue : TPriorityQueue;
begin
Queue:= TPriorityQueue.Create();
Queue.Push(3,'Clear drains');
Queue.Push(4,'Feed cat');
Queue.Push(5,'Make tea');
Queue.Push(1,'Solve RC tasks');
Queue.Push(2,'Tax return');
while not Queue.Empty() do
writeln(Queue.Pop());
Queue.free;
end.
|
http://rosettacode.org/wiki/Pythagorean_triples | Pythagorean triples | A Pythagorean triple is defined as three positive integers
(
a
,
b
,
c
)
{\displaystyle (a,b,c)}
where
a
<
b
<
c
{\displaystyle a<b<c}
, and
a
2
+
b
2
=
c
2
.
{\displaystyle a^{2}+b^{2}=c^{2}.}
They are called primitive triples if
a
,
b
,
c
{\displaystyle a,b,c}
are co-prime, that is, if their pairwise greatest common divisors
g
c
d
(
a
,
b
)
=
g
c
d
(
a
,
c
)
=
g
c
d
(
b
,
c
)
=
1
{\displaystyle {\rm {gcd}}(a,b)={\rm {gcd}}(a,c)={\rm {gcd}}(b,c)=1}
.
Because of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime (
g
c
d
(
a
,
b
)
=
1
{\displaystyle {\rm {gcd}}(a,b)=1}
).
Each triple forms the length of the sides of a right triangle, whose perimeter is
P
=
a
+
b
+
c
{\displaystyle P=a+b+c}
.
Task
The task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.
Extra credit
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.
Related tasks
Euler's sum of powers conjecture
List comprehensions
Pythagorean quadruples
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 1 LET Y=0: LET X=0: LET Z=0: LET V=0: LET U=0: LET L=10: LET T=0: LET P=0: LET N=4: LET M=0: PRINT "limit trip. prim."
2 FOR U=2 TO INT (SQR (L/2)): LET Y=U-INT (U/2)*2: LET N=N+4: LET M=U*U*2: IF Y=0 THEN LET M=M-U-U
3 FOR V=1+Y TO U-1 STEP 2: LET M=M+N: LET X=U: LET Y=V
4 LET Z=Y: LET Y=X-INT (X/Y)*Y: LET X=Z: IF Y<>0 THEN GO TO 4
5 IF X>1 THEN GO TO 8
6 IF M>L THEN GO TO 9
7 LET P=P+1: LET T=T+INT (L/M)
8 NEXT V
9 NEXT U
10 PRINT L;TAB 8;T;TAB 16;P
11 LET N=4: LET T=0: LET P=0: LET L=L*10: IF L<=100000 THEN GO TO 2 |
http://rosettacode.org/wiki/Program_termination | Program termination |
Task
Show the syntax for a complete stoppage of a program inside a conditional.
This includes all threads/processes which are part of your program.
Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.).
Unless otherwise described, no special cleanup outside that provided by the operating system is provided.
| #XPL0 | XPL0 | if Problem then exit 1;
|
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.