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/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#C
|
C
|
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
const double EPS = 0.001;
const double EPS_SQUARE = 0.000001;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = min(x1, min(x2, x3)) - EPS;
double xMax = max(x1, max(x2, x3)) + EPS;
double yMin = min(y1, min(y2, y3)) - EPS;
double yMax = max(y1, max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
printf("(%f, %f)", x, y);
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
printf("Triangle is [");
printPoint(x1, y1);
printf(", ");
printPoint(x2, y2);
printf(", ");
printPoint(x3, y3);
printf("] \n");
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
printf("Point ");
printPoint(x, y);
printf(" is within triangle? ");
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
printf("true\n");
} else {
printf("false\n");
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
printf("\n");
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
printf("\n");
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
printf("\n");
return 0;
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Scala
|
Scala
|
def flatList(l: List[_]): List[Any] = l match {
case Nil => Nil
case (head: List[_]) :: tail => flatList(head) ::: flatList(tail)
case head :: tail => head :: flatList(tail)
}
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#BBC_BASIC
|
BBC BASIC
|
PROCrecurse(1)
END
DEF PROCrecurse(depth%)
IF depth% MOD 100 = 0 PRINT TAB(0,0) depth%;
PROCrecurse(depth% + 1)
ENDPROC
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Befunge
|
Befunge
|
1>1#:+#.:_@
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Arturo
|
Arturo
|
pal2?: function [n][
digs2: digits.base:2 n
return digs2 = reverse digs2
]
revNumber: function [z][
u: z
result: 0
while [u > 0][
result: result + (2*result) + u%3
u: u/3
]
return result
]
pal23: function [][
p3: 1
cnt: 1
print [
pad (to :string 0)++" :" 14
pad.right join to [:string] digits.base:2 0 37 "->"
join to [:string] digits.base:3 0
]
loop 0..31 'p [
while [(p3*(1+3*p3)) < shl 1 2*p]-> p3: p3*3
bound: (shl 1 2*p)/3*p3
limDown: max @[p3/3, bound]
limUp: min @[2*bound, p3-1]
if limUp >= limDown [
loop limDown..limUp 'k [
n: (revNumber k) + (1+3*k)*p3
if pal2? n [
print [
pad (to :string n)++" :" 14
pad.right join to [:string] digits.base:2 n 37 "->"
join to [:string] digits.base:3 n
]
cnt: cnt + 1
if cnt=6 -> return null
]
]
]
]
]
pal23
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Maple
|
Maple
|
MaxLeftTruncatablePrime := proc(b, $)
local i, j, c, p, sdprimes;
local tprimes := table();
sdprimes := select(isprime, [seq(1..b-1)]);
for p in sdprimes do
if assigned(tprimes[p]) then
next;
end if;
i := ilog[b](p)+1;
j := 1;
do
c := j*b^i + p;
if j >= b then
# we have tried all 1 digit extensions of p, add p to tprimes and move back 1 digit
tprimes[p] := p;
if i = 1 then
# if we are at the first digit, go to the next 1 digit prime
break;
end if;
i := i - 1;
j := 1;
p := p - iquo(p, b^i)*b^i;
elif assigned(tprimes[c]) then
j := j + 1;
elif isprime(c) then
p := c;
i := i + 1;
j := 1;
else
j := j+1;
end if;
end do;
end do;
return max(indices(tprimes, 'nolist'));
end proc;
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Mathematica_.2F_Wolfram_Language
|
Mathematica / Wolfram Language
|
LargestLeftTruncatablePrimeInBase[n_] :=
Max[NestWhile[{Select[
Flatten@Outer[Function[{a, b}, #[[2]] a + b],
Range[1, n - 1], #[[1]]], PrimeQ], n #[[2]]} &, {{0},
1}, #[[1]] != {} &, 1, Infinity, -1][[1]]]
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#E
|
E
|
for i in 1..100 {
println(switch ([i % 3, i % 5]) {
match [==0, ==0] { "FizzBuzz" }
match [==0, _ ] { "Fizz" }
match [_, ==0] { "Buzz" }
match _ { i }
})
}
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#C.2B.2B
|
C++
|
#include <iostream>
const double EPS = 0.001;
const double EPS_SQUARE = EPS * EPS;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = std::min(x1, std::min(x2, x3)) - EPS;
double xMax = std::max(x1, std::max(x2, x3)) + EPS;
double yMin = std::min(y1, std::min(y2, y3)) - EPS;
double yMax = std::max(y1, std::max(y2, y3)) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
std::cout << '(' << x << ", " << y << ')';
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
std::cout << "Triangle is [";
printPoint(x1, y1);
std::cout << ", ";
printPoint(x2, y2);
std::cout << ", ";
printPoint(x3, y3);
std::cout << "]\n";
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
std::cout << "Point ";
printPoint(x, y);
std::cout << " is within triangle? ";
if (accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
std::cout << "true\n";
} else {
std::cout << "false\n";
}
}
int main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
std::cout << '\n';
return 0;
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Scheme
|
Scheme
|
> (define (flatten x)
(cond ((null? x) '())
((not (pair? x)) (list x))
(else (append (flatten (car x))
(flatten (cdr x))))))
> (flatten '((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()))
(1 2 3 4 5 6 7 8)
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#BQN
|
BQN
|
{𝕊1+•Show 𝕩}0
0
1
.
.
.
4094
Error: Stack overflow
at {𝕊1+•Show 𝕩}0
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Bracmat
|
Bracmat
|
rec=.out$!arg&rec$(!arg+1)
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#C
|
C
|
#include <stdio.h>
typedef unsigned long long xint;
int is_palin2(xint n)
{
xint x = 0;
if (!(n&1)) return !n;
while (x < n) x = x<<1 | (n&1), n >>= 1;
return n == x || n == x>>1;
}
xint reverse3(xint n)
{
xint x = 0;
while (n) x = x*3 + (n%3), n /= 3;
return x;
}
void print(xint n, xint base)
{
putchar(' ');
// printing digits backwards, but hey, it's a palindrome
do { putchar('0' + (n%base)), n /= base; } while(n);
printf("(%lld)", base);
}
void show(xint n)
{
printf("%llu", n);
print(n, 2);
print(n, 3);
putchar('\n');
}
xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }
int main(void)
{
xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
int cnt;
show(0);
cnt = 1;
lo = 0;
hi = pow2 = pow3 = 1;
while (1) {
for (i = lo; i < hi; i++) {
n = (i * 3 + 1) * pow3 + reverse3(i);
if (!is_palin2(n)) continue;
show(n);
if (++cnt >= 7) return 0;
}
if (i == pow3)
pow3 *= 3;
else
pow2 *= 4;
while (1) {
while (pow2 <= pow3) pow2 *= 4;
lo2 = (pow2 / pow3 - 1) / 3;
hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
lo3 = pow3 / 3;
hi3 = pow3;
if (lo2 >= hi3)
pow3 *= 3;
else if (lo3 >= hi2)
pow2 *= 4;
else {
lo = max(lo2, lo3);
hi = min(hi2, hi3);
break;
}
}
}
return 0;
}
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Nim
|
Nim
|
import bignum, strformat
const
Primes = [2, 3, 5, 7, 11, 13, 17]
Digits = "0123456789abcdefghijklmnopqrstuvwxyz"
#---------------------------------------------------------------------------------------------------
func isProbablyPrime(n: Int): bool =
## Return true if "n" is not definitively composite.
probablyPrime(n, 25) != 0
#---------------------------------------------------------------------------------------------------
func maxLeftTruncablePrime(base: int): Int =
## Return the maximum left truncable prime for given base.
let base = base.int32
var primes: seq[Int]
# Initialize primes with one digit in given base.
for p in Primes:
if p < base:
primes.add(newInt(p))
else:
break
# Build prime list with one more digit per generation.
var next: seq[Int]
while true:
# Build the next generation (with one more digit).
for p in primes:
var pstr = ' ' & `$`(p, base) # ' ' as a placeholder for next digit.
for i in 1..<base:
pstr[0] = Digits[i]
let n = newInt(pstr, base)
if n.isProbablyPrime():
next.add(n)
if next.len == 0:
# No primes with this number of digits.
# Return the greatest prime in previous generation.
return max(primes)
# Prepare to build next generation.
primes = next
next.setLen(0)
#———————————————————————————————————————————————————————————————————————————————————————————————————
echo "Base Greatest left truncable prime"
echo "====================================="
for base in 3..17:
let m = maxLeftTruncablePrime(base)
echo &"{base:>3} {m}", if base > 10: " (" & `$`(m, base.int32) & ')' else: ""
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#PARI.2FGP
|
PARI/GP
|
a(n)=my(v=primes(primepi(n-1)),u,t,b=1,best); while(#v, best=vecmax(v); b*=n; u=List(); for(i=1,#v,for(k=1,n-1,if(isprime(t=v[i]+k*b), listput(u,t)))); v=Vec(u)); best
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#EasyLang
|
EasyLang
|
for i = 1 to 100
if i mod 15 = 0
print "FizzBuzz"
elif i mod 5 = 0
print "Buzz"
elif i mod 3 = 0
print "Fizz"
else
print i
.
.
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#Common_Lisp
|
Common Lisp
|
; There are different algorithms to solve this problem, such as adding areas, adding angles, etc... but these
; solutions are sensitive to rounding errors intrinsic to float operations. We want to avoid these issues, therefore we
; use the following algorithm which only uses multiplication and subtraction: we consider one side of the triangle
; and see on which side of it is the point P located. We can give +1 if it is on the right hand side, -1 for the
; left side, or 0 if it is on the line. If the point is located on the same side relative to all three sides of the triangle
; then the point is inside of it. This has an added advantage that it can be scaled up to other more complicated figures
; (even concave ones, with some minor modifications).
(defun point-inside-triangle (P A B C)
"Is the point P inside the triangle formed by ABC?"
(= (side-of-line P A B)
(side-of-line P B C)
(side-of-line P C A) ))
; This is the version to include those points which are on one of the sides
(defun point-inside-or-on-triangle (P A B C)
"Is the point P inside the triangle formed by ABC or on one of the sides?"
(apply #'= (remove 0 (list (side-of-line P A B) (side-of-line P B C) (side-of-line P C A)))) )
(defun side-of-line (P A B)
"Return +1 if it is on the right side, -1 for the left side, or 0 if it is on the line"
; We use the sign of the determinant of vectors (AB,AM), where M(X,Y) is the query point:
; position = sign((Bx - Ax) * (Y - Ay) - (By - Ay) * (X - Ax))
(signum (- (* (- (car B) (car A))
(- (cdr P) (cdr A)) )
(* (- (cdr B) (cdr A))
(- (car P) (car A)) ))))
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Shen
|
Shen
|
(define flatten
[] -> []
[X|Y] -> (append (flatten X) (flatten Y))
X -> [X])
(flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []])
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#C
|
C
|
#include <stdio.h>
void recurse(unsigned int i)
{
printf("%d\n", i);
recurse(i+1); // 523756
}
int main()
{
recurse(0);
return 0;
}
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#C.23
|
C#
|
using System;
class RecursionLimit
{
static void Main(string[] args)
{
Recur(0);
}
private static void Recur(int i)
{
Console.WriteLine(i);
Recur(i + 1);
}
}
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#C.23
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
public class FindPalindromicNumbers
{
static void Main(string[] args)
{
var query =
PalindromicTernaries()
.Where(IsPalindromicBinary)
.Take(6);
foreach (var x in query) {
Console.WriteLine("Decimal: " + x);
Console.WriteLine("Ternary: " + ToTernary(x));
Console.WriteLine("Binary: " + Convert.ToString(x, 2));
Console.WriteLine();
}
}
public static IEnumerable<long> PalindromicTernaries() {
yield return 0;
yield return 1;
yield return 13;
yield return 23;
var f = new List<long> {0};
long fMiddle = 9;
while (true) {
for (long edge = 1; edge < 3; edge++) {
int i;
do {
//construct the result
long result = fMiddle;
long fLeft = fMiddle * 3;
long fRight = fMiddle / 3;
for (int j = f.Count - 1; j >= 0; j--) {
result += (fLeft + fRight) * f[j];
fLeft *= 3;
fRight /= 3;
}
result += (fLeft + fRight) * edge;
yield return result;
//next permutation
for (i = f.Count - 1; i >= 0; i--) {
if (f[i] == 2) {
f[i] = 0;
} else {
f[i]++;
break;
}
}
} while (i >= 0);
}
f.Add(0);
fMiddle *= 3;
}
}
public static bool IsPalindromicBinary(long number) {
long n = number;
long reverse = 0;
while (n != 0) {
reverse <<= 1;
if ((n & 1) == 1) reverse++;
n >>= 1;
}
return reverse == number;
}
public static string ToTernary(long n)
{
if (n == 0) return "0";
string result = "";
while (n > 0) { {
result = (n % 3) + result;
n /= 3;
}
return result;
}
}
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Perl
|
Perl
|
use ntheory qw/:all/;
use Math::GMPz;
sub lltp {
my($n, $b, $best) = (shift, Math::GMPz->new(1));
my @v = map { Math::GMPz->new($_) } @{primes($n-1)};
while (@v) {
$best = vecmax(@v);
$b *= $n;
my @u;
foreach my $vi (@v) {
push @u, grep { is_prob_prime($_) } map { $vi + $_*$b } 1 .. $n-1;
}
@v = @u;
}
die unless is_provable_prime($best);
$best;
}
printf "%2d %s\n", $_, lltp($_) for 3 .. 17;
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#ECL
|
ECL
|
DataRec := RECORD
STRING s;
END;
DataRec MakeDataRec(UNSIGNED c) := TRANSFORM
SELF.s := MAP
(
c % 15 = 0 => 'FizzBuzz',
c % 3 = 0 => 'Fizz',
c % 5 = 0 => 'Buzz',
(STRING)c
);
END;
d := DATASET(100,MakeDataRec(COUNTER));
OUTPUT(d);
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#11l
|
11l
|
F find_common_directory_path(paths, sep = ‘/’)
V pos = 0
L
L(path) paths
I pos < path.len & path[pos] == paths[0][pos]
L.continue
L pos > 0
pos--
I paths[0][pos] == sep
L.break
R paths[0][0.<pos]
pos++
print(find_common_directory_path([
‘/home/user1/tmp/coverage/test’,
‘/home/user1/tmp/covert/operator’,
‘/home/user1/tmp/coven/members’]))
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#D
|
D
|
import std.algorithm; //.comparison for min and max
import std.stdio;
immutable EPS = 0.001;
immutable EPS_SQUARE = EPS * EPS;
double side(double x1, double y1, double x2, double y2, double x, double y) {
return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1);
}
bool naivePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double checkSide1 = side(x1, y1, x2, y2, x, y) >= 0;
double checkSide2 = side(x2, y2, x3, y3, x, y) >= 0;
double checkSide3 = side(x3, y3, x1, y1, x, y) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
bool pointInTriangleBoundingBox(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
double xMin = min(x1, x2, x3) - EPS;
double xMax = max(x1, x2, x3) + EPS;
double yMin = min(y1, y2, y3) - EPS;
double yMax = max(y1, y2, y3) + EPS;
return !(x < xMin || xMax < x || y < yMin || yMax < y);
}
double distanceSquarePointToSegment(double x1, double y1, double x2, double y2, double x, double y) {
double p1_p2_squareLength = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
double dotProduct = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_squareLength;
if (dotProduct < 0) {
return (x - x1) * (x - x1) + (y - y1) * (y - y1);
} else if (dotProduct <= 1) {
double p_p1_squareLength = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
} else {
return (x - x2) * (x - x2) + (y - y2) * (y - y2);
}
}
bool accuratePointInTriangle(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
if (!pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y)) {
return false;
}
if (naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)) {
return true;
}
if (distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE) {
return true;
}
return false;
}
void printPoint(double x, double y) {
write('(', x, ", ", y, ')');
}
void printTriangle(double x1, double y1, double x2, double y2, double x3, double y3) {
write("Triangle is [");
printPoint(x1, y1);
write(", ");
printPoint(x2, y2);
write(", ");
printPoint(x3, y3);
writeln(']');
}
void test(double x1, double y1, double x2, double y2, double x3, double y3, double x, double y) {
printTriangle(x1, y1, x2, y2, x3, y3);
write("Point ");
printPoint(x, y);
write(" is within triangle? ");
writeln(accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y));
}
void main() {
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 0);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 0, 1);
test(1.5, 2.4, 5.1, -3.1, -3.8, 1.2, 3, 1);
writeln;
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, 25, 11.11111111111111, 5.414285714285714, 14.349206349206348);
writeln;
test(0.1, 0.1111111111111111, 12.5, 33.333333333333336, -12.5, 16.666666666666668, 5.414285714285714, 14.349206349206348);
writeln;
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Sidef
|
Sidef
|
func flatten(a) {
var flat = []
a.each { |item|
flat += (item.kind_of(Array) ? flatten(item) : [item])
}
return flat
}
var arr = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
say flatten(arr) # used-defined function
say arr.flatten # built-in Array method
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#C.2B.2B
|
C++
|
#include <iostream>
void recurse(unsigned int i)
{
std::cout<<i<<"\n";
recurse(i+1);
}
int main()
{
recurse(0);
}
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Clojure
|
Clojure
|
=> (def *stack* 0)
=> ((fn overflow [] ((def *stack* (inc *stack*))(overflow))))
java.lang.StackOverflowError (NO_SOURCE_FILE:0)
=> *stack*
10498
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Common_Lisp
|
Common Lisp
|
(defun palindromep (str)
(string-equal str (reverse str)) )
(loop
for i from 0
with results = 0
until (>= results 6)
do
(when (and (palindromep (format nil "~B" i))
(palindromep (format nil "~3R" i)) )
(format t "n:~a~:* [2]:~B~:* [3]:~3R~%" i)
(incf results) ))
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Phix
|
Phix
|
with javascript_semantics
include mpfr.e
sequence tens = mpz_inits(1,1),
vals = mpz_inits(1),
digits = {0}
mpz answer = mpz_init(0)
integer base, seen_depth
procedure add_digit(integer i)
atom t1 = time()+1
if i>length(vals) then
vals &= mpz_init_set(vals[i-1])
tens &= mpz_init_set(tens[i-1])
mpz_mul_si(tens[i],tens[i],base)
digits &= 0
end if
for d=1 to base-1 do
digits[i] = d
mpz_set(vals[i], vals[i-1])
mpz_addmul_ui(vals[i], tens[i], d)
if mpz_prime(vals[i]) then
if i>seen_depth
or (i==seen_depth and mpz_cmp(vals[i], answer)>0) then
mpz_set(answer, vals[i])
seen_depth = i
end if
add_digit(i+1)
end if
if time()>t1 and platform()!=JS then
printf(1," base %d: (%d) %v \r", {base, seen_depth, digits[1..i]})
end if
end for
end procedure
procedure do_base()
atom t0 = time()
seen_depth = 0
mpz_set_si(answer, 0)
mpz_set_si(tens[1], 1)
for i=2 to length(tens) do
mpz_mul_si(tens[i], tens[i-1], base)
end for
for i=1 to base do
integer pi = get_prime(i)
if pi>=base then exit end if
mpz_set_si(vals[1], pi)
digits[1] = pi
add_digit(2)
end for
string rd = mpz_get_str(answer),
rb = mpz_get_str(answer,base)
t0 = time()-t0
string t = iff(t0>0.1?" ["&elapsed(t0)&"]":"")
printf(1,"%3d %-41s (%s, %d digits)%s\n", {base,rd,rb,length(rb),t})
end procedure
atom t0 = time()
for b=3 to 31 do
if (platform()!=JS or not find(b,{12,14,16,21,25,27,31}))
and (b<=17 or remainder(b,2)=1) then
base = b
do_base()
end if
end for
?elapsed(time()-t0)
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Eero
|
Eero
|
#import <Foundation/Foundation.h>
int main()
autoreleasepool
for int i in 1 .. 100
s := ''
if i % 3 == 0
s << 'Fizz'
if i % 5 == 0
s << 'Buzz'
Log( '(%d) %@', i, s )
return 0
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Common_Path is
function "rem" (A, B : String) return String is
Slash : Integer := A'First; -- At the last slash seen in A
At_A : Integer := A'first;
At_B : Integer := B'first;
begin
loop
if At_A > A'Last then
if At_B > B'Last or else B (At_B) = '/' then
return A;
else
return A (A'First..Slash - 1);
end if;
elsif At_B > B'Last then
if A (At_A) = '/' then -- A cannot be shorter than B here
return B;
else
return A (A'First..Slash - 1);
end if;
elsif A (At_A) /= B (At_B) then
return A (A'First..Slash - 1);
elsif A (At_A) = '/' then
Slash := At_A;
end if;
At_A := At_A + 1;
At_B := At_B + 1;
end loop;
end "rem";
begin
Put_Line
( "/home/user1/tmp/coverage/test" rem
"/home/user1/tmp/covert/operator" rem
"/home/user1/tmp/coven/members"
);
end Test_Common_Path;
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#Factor
|
Factor
|
USING: accessors fry io kernel locals math math.order sequences ;
TUPLE: point x y ;
C: <point> point
: >point< ( point -- x y ) [ x>> ] [ y>> ] bi ;
TUPLE: triangle p1 p2 p3 ;
C: <triangle> triangle
: >triangle< ( triangle -- x1 y1 x2 y2 x3 y3 )
[ p1>> ] [ p2>> ] [ p3>> ] tri [ >point< ] tri@ ;
:: point-in-triangle? ( point triangle -- ? )
point >point< triangle >triangle< :> ( x y x1 y1 x2 y2 x3 y3 )
y2 y3 - x1 * x3 x2 - y1 * + x2 y3 * + y2 x3 * - :> d
y3 y1 - x * x1 x3 - y * + x1 y3 * - y1 x3 * + d / :> t1
y2 y1 - x * x1 x2 - y * + x1 y2 * - y1 x2 * + d neg / :> t2
t1 t2 + :> s
t1 t2 [ 0 1 between? ] bi@ and s 1 <= and ;
! Test if it works.
20 <iota> dup [ swap <point> ] cartesian-map ! Make a matrix of points
3 3 <point> 16 10 <point> 10 16 <point> <triangle> ! Make a triangle
'[ [ _ point-in-triangle? "#" "." ? write ] each nl ] each nl ! Show points inside the triangle with '#'
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Slate
|
Slate
|
s@(Sequence traits) flatten
[
[| :out | s flattenOn: out] writingAs: s
].
s@(Sequence traits) flattenOn: w@(WriteStream traits)
[
s do: [| :value |
(value is: s)
ifTrue: [value flattenOn: w]
ifFalse: [w nextPut: value]].
].
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#COBOL
|
COBOL
|
identification division.
program-id. recurse.
data division.
working-storage section.
01 depth-counter pic 9(3).
01 install-address usage is procedure-pointer.
01 install-flag pic x comp-x value 0.
01 status-code pic x(2) comp-5.
01 ind pic s9(9) comp-5.
linkage section.
01 err-msg pic x(325).
procedure division.
100-main.
set install-address to entry "300-err".
call "CBL_ERROR_PROC" using install-flag
install-address
returning status-code.
if status-code not = 0
display "ERROR INSTALLING ERROR PROC"
stop run
end-if
move 0 to depth-counter.
display 'Mung until no good.'.
perform 200-mung.
display 'No good.'.
stop run.
200-mung.
add 1 to depth-counter.
display depth-counter.
perform 200-mung.
300-err.
entry "300-err" using err-msg.
perform varying ind from 1 by 1
until (err-msg(ind:1) = x"00") or (ind = length of err-msg)
continue
end-perform
display err-msg(1:ind).
*> room for a better-than-abrupt death here.
exit program.
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#D
|
D
|
import core.stdc.stdio, std.ascii;
bool isPalindrome2(ulong n) pure nothrow @nogc @safe {
ulong x = 0;
if (!(n & 1))
return !n;
while (x < n) {
x = (x << 1) | (n & 1);
n >>= 1;
}
return n == x || n == (x >> 1);
}
ulong reverse3(ulong n) pure nothrow @nogc @safe {
ulong x = 0;
while (n) {
x = x * 3 + (n % 3);
n /= 3;
}
return x;
}
void printReversed(ubyte base)(ulong n) nothrow @nogc {
' '.putchar;
do {
digits[n % base].putchar;
n /= base;
} while(n);
printf("(%d)", base);
}
void main() nothrow @nogc {
ulong top = 1, mul = 1, even = 0;
uint count = 0;
for (ulong i = 0; true; i++) {
if (i == top) {
if (even ^= 1)
top *= 3;
else {
i = mul;
mul = top;
}
}
immutable n = i * mul + reverse3(even ? i / 3 : i);
if (isPalindrome2(n)) {
printf("%llu", n);
printReversed!3(n);
printReversed!2(n);
'\n'.putchar;
if (++count >= 6) // Print first 6.
break;
}
}
}
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Python
|
Python
|
import random
def is_probable_prime(n,k):
#this uses the miller-rabin primality test found from rosetta code
if n==0 or n==1:
return False
if n==2:
return True
if n % 2 == 0:
return False
s = 0
d = n-1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True # n is definitely composite
for i in range(k):
a = random.randrange(2, n)
if try_composite(a):
return False
return True # no base tested showed n as composite
def largest_left_truncatable_prime(base):
radix = 0
candidates = [0]
while True:
new_candidates=[]
multiplier = base**radix
for i in range(1,base):
new_candidates += [x+i*multiplier for x in candidates if is_probable_prime(x+i*multiplier,30)]
if len(new_candidates)==0:
return max(candidates)
candidates = new_candidates
radix += 1
for b in range(3,24):
print("%d:%d\n" % (b,largest_left_truncatable_prime(b)))
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Egel
|
Egel
|
import "prelude.eg"
import "io.ego"
using System
using IO
def fizzbuzz =
[ 100 -> print "100\n"
| N ->
if and ((N%3) == 0) ((N%5) == 0) then
let _ = print "fizz buzz, " in fizzbuzz (N+1)
else if (N%3) == 0 then
let _ = print "fizz, " in fizzbuzz (N+1)
else if (N%5) == 0 then
let _ = print "buzz, " in fizzbuzz (N+1)
else
let _ = print N ", " in fizzbuzz (N+1) ]
def main = fizzbuzz 1
|
http://rosettacode.org/wiki/File_size_distribution
|
File size distribution
|
Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
|
#Action.21
|
Action!
|
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
PROC SizeDistribution(CHAR ARRAY filter INT ARRAY limits,counts BYTE count)
CHAR ARRAY line(255),tmp(4)
INT size
BYTE i,dev=[1]
FOR i=0 TO count-1
DO
counts(i)=0
OD
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
IF line(0)=0 THEN
EXIT
FI
SCopyS(tmp,line,line(0)-3,line(0))
size=ValI(tmp)
FOR i=0 TO count-1
DO
IF size<limits(i) THEN
counts(i)==+1
EXIT
FI
OD
OD
Close(dev)
RETURN
PROC GenerateLimits(INT ARRAY limits BYTE count)
BYTE i
INT l
l=1
FOR i=0 TO count-1
DO
limits(i)=l
l==LSH 1
IF l>1000 THEN l=1000 FI
OD
RETURN
PROC PrintBar(INT len,max,size)
INT i,count
count=4*len*size/max
IF count=0 AND len>0 THEN
count=1
FI
FOR i=0 TO count/4-1
DO
Put(160)
OD
i=count MOD 4
IF i=1 THEN Put(22)
ELSEIF i=2 THEN Put(25)
ELSEIF i=3 THEN Put(130) FI
RETURN
PROC PrintResult(CHAR ARRAY filter
INT ARRAY limits,counts BYTE count)
BYTE i
CHAR ARRAY tmp(5)
INT min,max,total
total=0 max=0
FOR i=0 TO count-1
DO
total==+counts(i)
IF counts(i)>max THEN
max=counts(i)
FI
OD
PrintF("File size distribution of ""%S"" in sectors:%E",filter) PutE()
PrintE("From To Count Perc")
min=0
FOR i=0 TO count-1
DO
StrI(min,tmp) PrintF("%4S ",tmp)
StrI(limits(i)-1,tmp) PrintF("%3S ",tmp)
StrI(counts(i),tmp) PrintF("%3S ",tmp)
StrI(counts(i)*100/total,tmp) PrintF("%3S%% ",tmp)
PrintBar(counts(i),max,17) PutE()
min=limits(i)
OD
RETURN
PROC Main()
DEFINE LIMITCOUNT="11"
CHAR ARRAY filter="H1:*.*"
INT ARRAY limits(LIMITCOUNT),counts(LIMITCOUNT)
Put(125) PutE() ;clear the screen
GenerateLimits(limits,LIMITCOUNT)
SizeDistribution(filter,limits,counts,LIMITCOUNT)
PrintResult(filter,limits,counts,LIMITCOUNT)
RETURN
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Aime
|
Aime
|
cdp(...)
{
integer e;
record r;
text s;
ucall(r_add, 1, r, 0);
if (~r) {
s = r.low;
s = s.cut(0, e = b_trace(s, prefix(s, r.high), '/'));
s = ~s || e == -1 ? s : "/";
}
s;
}
main(void)
{
o_(cdp("/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"), "\n");
0;
}
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#ALGOL_68
|
ALGOL 68
|
# Utilities code #
CHAR dir sep = "/"; # Assume POSIX #
PROC dir name = (STRING dir)STRING: (
STRING out;
FOR pos FROM UPB dir BY -1 TO LWB dir DO
IF dir[pos] = dir sep THEN
out := dir[:pos-1];
GO TO out exit
FI
OD;
# else: # out:="";
out exit: out
);
PROC shortest = ([]STRING string list)STRING: (
INT min := max int;
INT min key := LWB string list - 1;
FOR key FROM LWB string list TO UPB string list DO
IF UPB string list[key][@1] < min THEN
min := UPB string list[key][@1];
min key := key
FI
OD;
string list[min key]
);
# Actual code #
PROC common prefix = ([]STRING strings)STRING: (
IF LWB strings EQ UPB strings THEN
# exit: # strings[LWB strings]
ELSE
STRING prefix := shortest(strings);
FOR pos FROM LWB prefix TO UPB prefix DO
CHAR first = prefix[pos];
FOR key FROM LWB strings+1 TO UPB strings DO
IF strings[key][@1][pos] NE first THEN
prefix := prefix[:pos-1];
GO TO prefix exit
FI
OD
OD;
prefix exit: prefix
FI
);
# Test code #
test:(
[]STRING dir list = (
"/home/user1/tmp/coverage/test",
"/home/user1/tmp/covert/operator",
"/home/user1/tmp/coven/members"
);
print((dir name(common prefix(dir list)), new line))
)
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#FreeBASIC
|
FreeBASIC
|
type p2d
x as double 'define a two-dimensional point
y as double
end type
function in_tri( A as p2d, B as p2d, C as p2d, P as p2d ) as boolean
'uses barycentric coordinates to determine if point P is inside
'the triangle defined by points A, B, C
dim as double AreaD = (-B.y*C.x + A.y*(-B.x + C.x) + A.x*(B.y - C.y) + B.x*C.y)
dim as double s = (A.y*C.x - A.x*C.y + (C.y - A.y)*P.x + (A.x - C.x)*P.y)/AreaD
dim as double t = (A.x*B.y - A.y*B.x + (A.y - B.y)*P.x + (B.x - A.x)*P.y)/AreaD
if s<=0 then return false
if t<=0 then return false
if s+t>=1 then return false
return true
end function
dim as p2d A,B,C,P 'generate some arbitrary triangle
A.x = 4.14 : A.y = -1.12
B.x = 8.1 : B.y =-4.9
C.x = 1.5: C.y = -9.3
for y as double = -0.25 to -9.75 step -0.5 'display a 10x10 square
for x as double = 0.125 to 9.875 step 0.25
P.x = x : P.y = y
if in_tri(A,B,C,P) then print "@"; else print "."; 'with all the points inside the triangle indicated
next x
print
next y
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Smalltalk
|
Smalltalk
|
OrderedCollection extend [
flatten [ |f|
f := OrderedCollection new.
self do: [ :i |
i isNumber
ifTrue: [ f add: i ]
ifFalse: [ |t|
t := (OrderedCollection withAll: i) flatten.
f addAll: t
]
].
^ f
]
].
|list|
list := OrderedCollection
withAll: { {1} . 2 . { {3 . 4} . 5 } .
{{{}}} . {{{6}}} . 7 . 8 . {} }.
(list flatten) printNl.
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#CoffeeScript
|
CoffeeScript
|
recurse = ( depth = 0 ) ->
try
recurse depth + 1
catch exception
depth
console.log "Recursion depth on this system is #{ do recurse }"
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Common_Lisp
|
Common Lisp
|
(defun recurse () (recurse))
(trace recurse)
(recurse)
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Elixir
|
Elixir
|
defmodule Palindromic do
import Integer, only: [is_odd: 1]
def number23 do
Stream.concat([0,1], Stream.unfold(1, &number23/1))
end
def number23(i) do
n3 = Integer.to_string(i,3)
n = (n3 <> "1" <> String.reverse(n3)) |> String.to_integer(3)
n2 = Integer.to_string(n,2)
if is_odd(String.length(n2)) and n2 == String.reverse(n2),
do: {n, i+1},
else: number23(i+1)
end
def task do
IO.puts " decimal ternary binary"
number23()
|> Enum.take(6)
|> Enum.each(fn n ->
n3 = Integer.to_charlist(n,3) |> :string.centre(25)
n2 = Integer.to_charlist(n,2) |> :string.centre(39)
:io.format "~12w ~s ~s~n", [n, n3, n2]
end)
end
end
Palindromic.task
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#F.23
|
F#
|
// Find palindromic numbers in both binary and ternary bases. December 19th., 2018
let fG(n,g)=(Seq.unfold(fun(g,e)->if e<1L then None else Some((g%3L)*e,(g/3L,e/3L)))(n,g/3L)|>Seq.sum)+g+n*g*3L
Seq.concat[seq[0L;1L;2L];Seq.unfold(fun(i,e)->Some (fG(i,e),(i+1L,if i=e-1L then e*3L else e)))(1L,3L)]
|>Seq.filter(fun n->let n=System.Convert.ToString(n,2).ToCharArray() in n=Array.rev n)|>Seq.take 6|>Seq.iter (printfn "%d")
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Racket
|
Racket
|
#lang racket
(require math/number-theory)
(define (prepend-digit b d i n)
(+ (* d (expt b i)) n))
(define (extend b i ts)
(define ts*
(for/list ([t (in-set ts)])
(for/set ([d (in-range 1 b)]
#:when (prime? (prepend-digit b d i t)))
(prepend-digit b d i t))))
(apply set-union ts*))
(define (truncables b n)
; return set of truncables of length n in base b
(if (= n 1)
(for/set ([d (in-range 1 b)] #:when (prime? d)) d)
(extend b (- n 1) (truncables b (- n 1)))))
(define (largest b)
(let loop ([ts (truncables b 1)]
[n 1])
(define ts* (extend b n ts))
(if (set-empty? ts*)
(apply max (set->list ts))
(loop ts* (+ n 1)))))
(for/list ([b (in-range 3 18)])
(define l (largest b))
; (displayln (list b l))
(list b l))
; Output:
'((3 23)
(4 4091)
(5 7817)
(6 4836525320399)
(7 817337)
(8 14005650767869)
(9 1676456897)
(10 357686312646216567629137)
(11 2276005673)
(12 13092430647736190817303130065827539)
(13 812751503)
(14 615419590422100474355767356763)
(15 34068645705927662447286191)
(16 1088303707153521644968345559987)
(17 13563641583101))
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Raku
|
Raku
|
use ntheory:from<Perl5> <is_prime>;
for 3 .. 11 -> $base {
say "Starting base $base...";
my @stems = grep { .is-prime }, ^$base;
for 1 .. * -> $digits {
print ' ', @stems.elems;
my @new;
my $place = $base ** $digits;
for 1 ..^ $base -> $digit {
my $left = $digit * $place;
@new.append: (@stems »+» $left).grep: { is_prime("$_") }
}
last unless +@new;
@stems = @new;
}
say "\nLargest ltp in base $base = {@stems.max} or :$base\<@stems.max.base($base)}>\n";
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Eiffel
|
Eiffel
|
class
APPLICATION
create
make
feature
make
do
fizzbuzz
end
fizzbuzz
--Numbers up to 100, prints "Fizz" instead of multiples of 3, and "Buzz" for multiples of 5.
--For multiples of both 3 and 5 prints "FizzBuzz".
do
across
1 |..| 100 as c
loop
if c.item \\ 15 = 0 then
io.put_string ("FIZZBUZZ%N")
elseif c.item \\ 3 = 0 then
io.put_string ("FIZZ%N")
elseif c.item \\ 5 = 0 then
io.put_string ("BUZZ%N")
else
io.put_string (c.item.out + "%N")
end
end
end
end
|
http://rosettacode.org/wiki/File_size_distribution
|
File size distribution
|
Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
|
#Ada
|
Ada
|
with Ada.Numerics.Elementary_Functions;
with Ada.Directories; use Ada.Directories;
with Ada.Strings.Fixed; use Ada.Strings;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
with Dir_Iterators.Recursive;
procedure File_Size_Distribution is
type Exponent_Type is range 0 .. 18;
type File_Count is range 0 .. Long_Integer'Last;
Counts : array (Exponent_Type) of File_Count := (others => 0);
Non_Zero_Index : Exponent_Type := 0;
Directory_Name : constant String := (if Argument_Count = 0
then "."
else Argument (1));
Directory_Walker : Dir_Iterators.Recursive.Recursive_Dir_Walk
:= Dir_Iterators.Recursive.Walk (Directory_Name);
begin
if not Exists (Directory_Name) or else Kind (Directory_Name) /= Directory then
Put_Line ("Directory does not exist");
return;
end if;
for Directory_Entry of Directory_Walker loop
declare
use Ada.Numerics.Elementary_Functions;
Size_Of_File : File_Size;
Exponent : Exponent_Type;
begin
if Kind (Directory_Entry) = Ordinary_File then
Size_Of_File := Size (Directory_Entry);
if Size_Of_File = 0 then
Counts (0) := Counts (0) + 1;
else
Exponent := Exponent_Type (Float'Ceiling (Log (Float (Size_Of_File),
Base => 10.0)));
Counts (Exponent) := Counts (Exponent) + 1;
end if;
end if;
end;
end loop;
for I in reverse Counts'Range loop
if Counts (I) /= 0 then
Non_Zero_Index := I;
exit;
end if;
end loop;
for I in Counts'First .. Non_Zero_Index loop
Put ("Less than 10**");
Put (Fixed.Trim (Exponent_Type'Image (I), Side => Left));
Put (": ");
Put (File_Count'Image (Counts (I)));
New_Line;
end loop;
end File_Size_Distribution;
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Arturo
|
Arturo
|
commonPathPrefix: function [lst][
paths: map lst => [split.by:"/" &]
common: new []
firstPath: first paths
loop .with:'i firstPath 'part [
found: true
loop paths 'p [
if part <> get p i [
found: false
break
]
]
if found -> 'common ++ part
]
return join.with:"/" common
]
print commonPathPrefix [
"/home/user1/tmp/coverage/test"
"/home/user1/tmp/covert/operator"
"/home/user1/tmp/coven/members"
]
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#AutoHotkey
|
AutoHotkey
|
Dir1 := "/home/user1/tmp/coverage/test"
Dir2 := "/home/user1/tmp/covert/operator"
Dir3 := "/home/user1/tmp/coven/members"
StringSplit, Dir1_, Dir1, /
StringSplit, Dir2_, Dir2, /
StringSplit, Dir3_, Dir3, /
Loop
If (Dir1_%A_Index% = Dir2_%A_Index%)
And (Dir1_%A_Index% = Dir3_%A_Index%)
Result .= (A_Index=1 ? "" : "/") Dir1_%A_Index%
Else Break
MsgBox, % Result
|
http://rosettacode.org/wiki/Filter
|
Filter
|
Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
|
#11l
|
11l
|
V array = Array(1..10)
V even = array.filter(n -> n % 2 == 0)
print(even)
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#Go
|
Go
|
package main
import (
"fmt"
"math"
)
const EPS = 0.001
const EPS_SQUARE = EPS * EPS
func side(x1, y1, x2, y2, x, y float64) float64 {
return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1)
}
func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
checkSide1 := side(x1, y1, x2, y2, x, y) >= 0
checkSide2 := side(x2, y2, x3, y3, x, y) >= 0
checkSide3 := side(x3, y3, x1, y1, x, y) >= 0
return checkSide1 && checkSide2 && checkSide3
}
func pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y float64) bool {
xMin := math.Min(x1, math.Min(x2, x3)) - EPS
xMax := math.Max(x1, math.Max(x2, x3)) + EPS
yMin := math.Min(y1, math.Min(y2, y3)) - EPS
yMax := math.Max(y1, math.Max(y2, y3)) + EPS
return !(x < xMin || xMax < x || y < yMin || yMax < y)
}
func distanceSquarePointToSegment(x1, y1, x2, y2, x, y float64) float64 {
p1_p2_squareLength := (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)
dotProduct := ((x-x1)*(x2-x1) + (y-y1)*(y2-y1)) / p1_p2_squareLength
if dotProduct < 0 {
return (x-x1)*(x-x1) + (y-y1)*(y-y1)
} else if dotProduct <= 1 {
p_p1_squareLength := (x1-x)*(x1-x) + (y1-y)*(y1-y)
return p_p1_squareLength - dotProduct*dotProduct*p1_p2_squareLength
} else {
return (x-x2)*(x-x2) + (y-y2)*(y-y2)
}
}
func accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool {
if !pointInTriangleBoundingBox(x1, y1, x2, y2, x3, y3, x, y) {
return false
}
if naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y) {
return true
}
if distanceSquarePointToSegment(x1, y1, x2, y2, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x2, y2, x3, y3, x, y) <= EPS_SQUARE {
return true
}
if distanceSquarePointToSegment(x3, y3, x1, y1, x, y) <= EPS_SQUARE {
return true
}
return false
}
func main() {
pts := [][2]float64{{0, 0}, {0, 1}, {3, 1}}
tri := [][2]float64{{3.0 / 2, 12.0 / 5}, {51.0 / 10, -31.0 / 10}, {-19.0 / 5, 1.2}}
fmt.Println("Triangle is", tri)
x1, y1 := tri[0][0], tri[0][1]
x2, y2 := tri[1][0], tri[1][1]
x3, y3 := tri[2][0], tri[2][1]
for _, pt := range pts {
x, y := pt[0], pt[1]
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle?", within)
}
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {100.0 / 4, 100.0 / 9}}
fmt.Println("Triangle is", tri)
x1, y1 = tri[0][0], tri[0][1]
x2, y2 = tri[1][0], tri[1][1]
x3, y3 = tri[2][0], tri[2][1]
x := x1 + (3.0/7)*(x2-x1)
y := y1 + (3.0/7)*(y2-y1)
pt := [2]float64{x, y}
within := accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
fmt.Println()
tri = [][2]float64{{1.0 / 10, 1.0 / 9}, {100.0 / 8, 100.0 / 3}, {-100.0 / 8, 100.0 / 6}}
fmt.Println("Triangle is", tri)
x3 = tri[2][0]
y3 = tri[2][1]
within = accuratePointInTriangle(x1, y1, x2, y2, x3, y3, x, y)
fmt.Println("Point", pt, "is within triangle ?", within)
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Standard_ML
|
Standard ML
|
datatype 'a nestedList =
L of 'a (* leaf *)
| N of 'a nestedList list (* node *)
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Crystal
|
Crystal
|
def recurse(counter = 0)
puts counter
recurse(counter + 1)
end
recurse()
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#D
|
D
|
import std.c.stdio;
void recurse(in uint i=0) {
printf("%u ", i);
recurse(i + 1);
}
void main() {
recurse();
}
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Factor
|
Factor
|
USING: combinators.short-circuit formatting io kernel lists
lists.lazy literals math math.parser sequences tools.time ;
IN: rosetta-code.2-3-palindromes
CONSTANT: info $[
"The first 6 numbers which are palindromic in both binary "
"and ternary:" append
]
: expand ( n -- m ) 3 >base dup <reversed> "1" glue 3 base> ;
: 2-3-pal? ( n -- ? )
expand >bin
{ [ length odd? ] [ dup <reversed> sequence= ] } 1&& ;
: first6 ( -- seq )
4 0 lfrom [ 2-3-pal? ] lfilter ltake list>array
[ expand ] map { 0 1 } prepend ;
: main ( -- )
info print nl first6 [
dup [ >bin ] [ 3 >base ] bi
"Decimal : %d\nBinary : %s\nTernary : %s\n\n" printf
] each ;
[ main ] time
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#FreeBASIC
|
FreeBASIC
|
' FB 1.05.0 Win64
'converts decimal "n" to its ternary equivalent
Function Ter(n As UInteger) As String
If n = 0 Then Return "0"
Dim result As String = ""
While n > 0
result = (n Mod 3) & result
n \= 3
Wend
Return result
End Function
' check if a binary or ternary numeric string "s" is palindromic
Function isPalindromic(s As String) As Boolean
' we can assume "s" will have an odd number of digits, so can ignore the middle digit
Dim As UInteger length = Len(s)
For i As UInteger = 0 To length \ 2 - 1
If s[i] <> s[length - 1 - i] Then Return False
Next
Return True
End Function
' print a number which is both a binary and ternary palindrome in all three bases
Sub printPalindrome(n As UInteger)
Print "Decimal : "; Str(n)
Print "Binary : "; bin(n)
Print "Ternary : "; ter(n)
Print
End Sub
' create a ternary palindrome whose left part is the ternary equivalent of "n" and return its decimal equivalent
Function createPalindrome3(n As UInteger) As UInteger
Dim As String ternary = Ter(n)
Dim As UInteger power3 = 1, sum = 0, length = Len(ternary)
For i As Integer = 0 To Length - 1 ''right part of palindrome is mirror image of left part
If ternary[i] > 48 Then '' i.e. non-zero
sum += (ternary[i] - 48) * power3
End If
power3 *= 3
Next
sum += power3 '' middle digit must be 1
power3 *= 3
sum += n * power3 '' value of left part is simply "n" multiplied by appropriate power of 3
Return sum
End Function
Dim t As Double = timer
Dim As UInteger i = 1, p3, count = 2
Dim As String binStr
Print "The first 6 numbers which are palindromic in both binary and ternary are :"
Print
' we can assume the first two palindromic numbers as per the task description
printPalindrome(0) '' 0 is a palindrome in all 3 bases
printPalindrome(1) '' 1 is a palindrome in all 3 bases
Do
p3 = createPalindrome3(i)
If p3 Mod 2 > 0 Then ' cannot be even as binary equivalent would end in zero
binStr = Bin(p3) '' Bin function is built into FB
If Len(binStr) Mod 2 = 1 Then '' binary palindrome must have an odd number of digits
If isPalindromic(binStr) Then
printPalindrome(p3)
count += 1
End If
End If
End If
i += 1
Loop Until count = 6
Print "Took ";
Print Using "#.###"; timer - t;
Print " seconds on i3 @ 2.13 GHz"
Print "Press any key to quit"
Sleep
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Ruby
|
Ruby
|
# Compute the largest left truncatable prime
#
# Nigel_Galloway
# September 15th., 2012.
#
require 'prime'
BASE = 3
MAX = 500
stems = Prime.each(BASE-1).to_a
(1..MAX-1).each {|i|
print "#{stems.length} "
t = []
b = BASE ** i
stems.each {|z|
(1..BASE-1).each {|n|
c = n*b+z
t.push(c) if c.prime?
}}
break if t.empty?
stems = t
}
puts "The largest left truncatable prime #{"less than #{BASE ** MAX} " if MAX < 500}in base #{BASE} is #{stems.max}"
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Scala
|
Scala
|
import scala.collection.parallel.immutable.ParSeq
object LeftTruncatablePrime extends App {
private def leftTruncatablePrime(maxRadix: Int, millerRabinCertainty: Int) {
def getLargestLeftTruncatablePrime(radix: Int, millerRabinCertainty: Int): BigInt = {
def getNextLeftTruncatablePrimes(n: BigInt, radix: Int, millerRabinCertainty: Int) = {
def baseString = if (n == 0) "" else n.toString(radix)
for {i <- (1 until radix).par
p = BigInt(Integer.toString(i, radix) + baseString, radix)
if p.isProbablePrime(millerRabinCertainty)
} yield p
}
def iter(list: ParSeq[BigInt], lastList: ParSeq[BigInt]): ParSeq[BigInt] = {
if (list.isEmpty) lastList
else
iter((for (n <- list.par) yield getNextLeftTruncatablePrimes(n, radix, millerRabinCertainty)).flatten, list)
}
iter(getNextLeftTruncatablePrimes(0, radix, millerRabinCertainty), ParSeq.empty).max
}
for (radix <- (3 to maxRadix).par) {
val largest = getLargestLeftTruncatablePrime(radix, millerRabinCertainty)
println(f"n=$radix%3d: " +
(if (largest == null) "No left-truncatable prime"
else f"$largest%35d (in base $radix%3d) ${largest.toString(radix)}"))
}
}
val argu: Array[String] = if (args.length >=2 ) args.slice(0, 2) else Array("17", "100")
val maxRadix = argu(0).toInt.ensuring(_ > 2, "Radix must be an integer greater than 2.")
try {
val millerRabinCertainty = argu(1).toInt
println(s"Run with maxRadix = $maxRadix and millerRabinCertainty = $millerRabinCertainty")
leftTruncatablePrime(maxRadix, millerRabinCertainty)
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}
catch {
case _: NumberFormatException => Console.err.println("Miller-Rabin Certainty must be an integer.")
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Ela
|
Ela
|
open list
prt x | x % 15 == 0 = "FizzBuzz"
| x % 3 == 0 = "Fizz"
| x % 5 == 0 = "Buzz"
| else = x
[1..100] |> map prt
|
http://rosettacode.org/wiki/File_size_distribution
|
File size distribution
|
Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
|
#C
|
C
|
#include<windows.h>
#include<string.h>
#include<stdio.h>
#define MAXORDER 25
int main(int argC, char* argV[])
{
char str[MAXORDER],commandString[1000],*startPath;
long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max;
int i,j,len;
double scale;
FILE* fp;
if(argC==1)
printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]);
else{
if(strchr(argV[1],' ')!=NULL){
len = strlen(argV[1]);
startPath = (char*)malloc((len+2)*sizeof(char));
startPath[0] = '\"';
startPath[len+1]='\"';
strncpy(startPath+1,argV[1],len);
startPath[len+2] = argV[1][len];
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath);
}
else if(strlen(argV[1])==1 && argV[1][0]=='.')
strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1");
else
sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]);
fp = popen(commandString,"r");
while(fgets(str,100,fp)!=NULL){
if(str[0]=='0')
fileSizeLog[0]++;
else
fileSizeLog[strlen(str)]++;
}
if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]);
}
}
else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){
CONSOLE_SCREEN_BUFFER_INFO csbi;
int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi);
if(val)
{
max = fileSizeLog[0];
for(i=1;i<MAXORDER;i++)
(fileSizeLog[i]>max)?max=fileSizeLog[i]:max;
(max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max);
for(i=0;i<MAXORDER;i++){
printf("\nSize Order < 10^%2d bytes |",i);
for(j=0;j<(int)(scale*fileSizeLog[i]);j++)
printf("%c",219);
printf("%Ld",fileSizeLog[i]);
}
}
}
return 0;
}
}
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#AWK
|
AWK
|
# Finds the longest common directory of paths[1], paths[2], ...,
# paths[count], where sep is a single-character directory separator.
function common_dir(paths, count, sep, b, c, f, i, j, p) {
if (count < 1)
return ""
p = "" # Longest common prefix
f = 0 # Final index before last sep
# Loop for c = each character of paths[1].
for (i = 1; i <= length(paths[1]); i++) {
c = substr(paths[1], i, 1)
# If c is not the same in paths[2], ..., paths[count]
# then break both loops.
b = 0
for (j = 2; j <= count; j++) {
if (c != substr(paths[j], i, 1)) {
b = 1
break
}
}
if (b)
break
# Append c to prefix. Update f.
p = p c
if (c == sep)
f = i - 1
}
# Return only f characters of prefix.
return substr(p, 1, f)
}
BEGIN {
a[1] = "/home/user1/tmp/coverage/test"
a[2] = "/home/user1/tmp/covert/operator"
a[3] = "/home/user1/tmp/coven/members"
print common_dir(a, 3, "/")
}
|
http://rosettacode.org/wiki/Filter
|
Filter
|
Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
|
#ACL2
|
ACL2
|
(defun filter-evens (xs)
(cond ((endp xs) nil)
((evenp (first xs))
(cons (first xs) (filter-evens (rest xs))))
(t (filter-evens (rest xs)))))
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#GW-BASIC
|
GW-BASIC
|
10 PIT1X! = 3 : PIT1Y! = 1.3 : REM arbitrary triangle for demonstration
20 PIT2X! = 17.222 : PIT2Y! = 10
30 PIT3X! = 5.5 : PIT3Y! = 18.212
40 FOR PITPY! = 0 TO 19 STEP 1
50 FOR PITPX! = 0 TO 20 STEP .5
60 GOSUB 1000
70 IF PITRES% = 0 THEN PRINT "."; ELSE PRINT "#";
80 NEXT PITPX!
90 PRINT
100 NEXT PITPY!
110 END
1000 REM Detect if point is in triangle. Takes 8 double-precision
1010 REM values: (PIT1X!, PIT1Y!), (PIT2X!, PIT2Y!), (PIT3X!, PIT3Y!)
1020 REM for the coordinates of the corners of the triangle
1030 REM and (PITPX!, PITPY!) for the coordinates of the test point
1040 REM Returns PITRES%: 1=in triangle, 0=not in it
1050 PITDAR! = -PIT2Y!*PIT3X! + PIT1Y!*(-PIT2X! + PIT3X!) + PIT1X!*(PIT2Y - PIT3Y!) + PIT2X!*PIT3Y!
1060 PITXXS = (PIT1Y!*PIT3X! - PIT1X!*PIT3Y! + (PIT3Y! - PIT1Y!)*PITPX! + (PIT1X! - PIT3X!)*PITPY!)/PITDAR!
1070 PITXXT = (PIT1X!*PIT2Y! - PIT1Y!*PIT2X! + (PIT1Y! - PIT2Y!)*PITPX! + (PIT2X! - PIT1X!)*PITPY!)/PITDAR!
1080 PITRES% = 0
1090 IF PITXXS!<=0 THEN RETURN
1100 IF PITXXT!<=0 THEN RETURN
1110 IF PITXXS!+PITXXT!>=1 THEN RETURN
1120 PITRES% = 1
1130 RETURN
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Suneido
|
Suneido
|
ob = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
ob.Flatten()
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#SuperCollider
|
SuperCollider
|
a = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []];
a.flatten(1); // answers [ 1, 2, [ 3, 4 ], 5, [ [ ] ], [ [ 6 ] ], 7, 8 ]
a.flat; // answers [ 1, 2, 3, 4, 5, 6, 7, 8 ]
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Dc
|
Dc
|
## f(n) = (n < 1) ? n : f(n-1) + n;
[q]sg
[dSn d1[>g 1- lfx]x Ln+]sf
[ [n=]Pdn []pP lfx [--> ]P p ]sh
65400 lhx
65600 lhx
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#Delphi
|
Delphi
|
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils;
function Recursive(Level : Integer) : Integer;
begin
try
Level := Level + 1;
Result := Recursive(Level);
except
on E: EStackOverflow do
Result := Level;
end;
end;
begin
Writeln('Recursion Level is ', Recursive(0));
Writeln('Press any key to Exit');
Readln;
end.
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Go
|
Go
|
package main
import (
"fmt"
"strconv"
"time"
)
func isPalindrome2(n uint64) bool {
x := uint64(0)
if (n & 1) == 0 {
return n == 0
}
for x < n {
x = (x << 1) | (n & 1)
n >>= 1
}
return n == x || n == (x>>1)
}
func reverse3(n uint64) uint64 {
x := uint64(0)
for n != 0 {
x = x*3 + (n % 3)
n /= 3
}
return x
}
func show(n uint64) {
fmt.Println("Decimal :", n)
fmt.Println("Binary :", strconv.FormatUint(n, 2))
fmt.Println("Ternary :", strconv.FormatUint(n, 3))
fmt.Println("Time :", time.Since(start))
fmt.Println()
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
var start time.Time
func main() {
start = time.Now()
fmt.Println("The first 7 numbers which are palindromic in both binary and ternary are :\n")
show(0)
cnt := 1
var lo, hi, pow2, pow3 uint64 = 0, 1, 1, 1
for {
i := lo
for ; i < hi; i++ {
n := (i*3+1)*pow3 + reverse3(i)
if !isPalindrome2(n) {
continue
}
show(n)
cnt++
if cnt >= 7 {
return
}
}
if i == pow3 {
pow3 *= 3
} else {
pow2 *= 4
}
for {
for pow2 <= pow3 {
pow2 *= 4
}
lo2 := (pow2/pow3 - 1) / 3
hi2 := (pow2*2/pow3-1)/3 + 1
lo3 := pow3 / 3
hi3 := pow3
if lo2 >= hi3 {
pow3 *= 3
} else if lo3 >= hi2 {
pow2 *= 4
} else {
lo = max(lo2, lo3)
hi = min(hi2, hi3)
break
}
}
}
}
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Sidef
|
Sidef
|
func lltp(n) {
var b = 1
var best = nil
var v = (n-1 -> primes)
while (v) {
best = v.max
b *= n
v.map! { |vi|
{|i| i*b + vi }.map(1..^n).grep{.is_prime}...
}
}
return best
}
for i in (3..17) {
printf("%2d %s\n", i, lltp(i))
}
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Swift
|
Swift
|
import BigInt
func largestLeftTruncatablePrime(_ base: Int) -> BigInt {
var radix = 0
var candidates = [BigInt(0)]
while true {
let multiplier = BigInt(base).power(radix)
var newCandidates = [BigInt]()
for i in 1..<BigInt(base) {
newCandidates += candidates.map({ ($0+i*multiplier, ($0+i*multiplier).isPrime(rounds: 30)) })
.filter({ $0.1 })
.map({ $0.0 })
}
if newCandidates.count == 0 {
return candidates.max()!
}
candidates = newCandidates
radix += 1
}
}
for i in 3..<18 {
print("\(i): \(largestLeftTruncatablePrime(i))")
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Elixir
|
Elixir
|
Enum.each 1..100, fn x ->
IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do
{ true, true } -> "FizzBuzz"
{ true, false } -> "Fizz"
{ false, true } -> "Buzz"
{ false, false } -> x
end)
end
|
http://rosettacode.org/wiki/File_size_distribution
|
File size distribution
|
Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <array>
#include <filesystem>
#include <iomanip>
#include <iostream>
void file_size_distribution(const std::filesystem::path& directory) {
constexpr size_t n = 9;
constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,
100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };
std::array<size_t, n + 1> count = { 0 };
size_t files = 0;
std::uintmax_t total_size = 0;
std::filesystem::recursive_directory_iterator iter(directory);
for (const auto& dir_entry : iter) {
if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {
std::uintmax_t file_size = dir_entry.file_size();
total_size += file_size;
auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);
size_t index = std::distance(sizes.begin(), i);
++count[index];
++files;
}
}
std::cout << "File size distribution for " << directory << ":\n";
for (size_t i = 0; i <= n; ++i) {
if (i == n)
std::cout << "> " << sizes[i - 1];
else
std::cout << std::setw(16) << sizes[i];
std::cout << " bytes: " << count[i] << '\n';
}
std::cout << "Number of files: " << files << '\n';
std::cout << "Total file size: " << total_size << " bytes\n";
}
int main(int argc, char** argv) {
std::cout.imbue(std::locale(""));
try {
const char* directory(argc > 1 ? argv[1] : ".");
std::filesystem::path path(directory);
if (!is_directory(path)) {
std::cerr << directory << " is not a directory.\n";
return EXIT_FAILURE;
}
file_size_distribution(path);
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#BASIC
|
BASIC
|
DECLARE FUNCTION commonPath$ (paths() AS STRING, pathSep AS STRING)
DATA "/home/user2", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"
DIM x(0 TO 2) AS STRING, n AS INTEGER
FOR n = 0 TO 2
READ x(n)
NEXT
PRINT "Common path is '"; commonPath$(x(), "/"); "'"
FUNCTION commonPath$ (paths() AS STRING, pathSep AS STRING)
DIM tmpint1 AS INTEGER, tmpint2 AS INTEGER, tmpstr1 AS STRING, tmpstr2 AS STRING
DIM L0 AS INTEGER, L1 AS INTEGER, lowerbound AS INTEGER, upperbound AS INTEGER
lowerbound = LBOUND(paths): upperbound = UBOUND(paths)
IF (lowerbound) = upperbound THEN 'Some quick error checking...
commonPath$ = paths(lowerbound)
ELSEIF lowerbound > upperbound THEN 'How in the...?
commonPath$ = ""
ELSE
tmpstr1 = paths(lowerbound)
FOR L0 = (lowerbound + 1) TO upperbound 'Find common strings.
tmpstr2 = paths(L0)
tmpint1 = LEN(tmpstr1)
tmpint2 = LEN(tmpstr2)
IF tmpint1 > tmpint2 THEN tmpint1 = tmpint2
FOR L1 = 1 TO tmpint1
IF MID$(tmpstr1, L1, 1) <> MID$(tmpstr2, L1, 1) THEN
tmpint1 = L1 - 1
EXIT FOR
END IF
NEXT
tmpstr1 = LEFT$(tmpstr1, tmpint1)
NEXT
IF RIGHT$(tmpstr1, 1) <> pathSep THEN
FOR L1 = tmpint1 TO 2 STEP -1
IF (pathSep) = MID$(tmpstr1, L1, 1) THEN
tmpstr1 = LEFT$(tmpstr1, L1 - 1)
EXIT FOR
END IF
NEXT
IF LEN(tmpstr1) = tmpint1 THEN tmpstr1 = ""
ELSEIF tmpint1 > 1 THEN
tmpstr1 = LEFT$(tmpstr1, tmpint1 - 1)
END IF
commonPath$ = tmpstr1
END IF
END FUNCTION
|
http://rosettacode.org/wiki/Filter
|
Filter
|
Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
|
#Action.21
|
Action!
|
DEFINE PTR="CARD"
INT value ;used in predicate
PROC PrintArray(INT ARRAY a BYTE size)
BYTE i
Put('[)
FOR i=0 TO size-1
DO
PrintI(a(i))
IF i<size-1 THEN
Put(' )
FI
OD
Put(']) PutE()
RETURN
;jump addr is stored in X and A registers
BYTE FUNC Predicate=*(PTR jumpAddr)
DEFINE STX="$8E"
DEFINE STA="$8D"
DEFINE JSR="$20"
DEFINE RTS="$60"
[STX Predicate+8
STA Predicate+7
JSR $00 $00
RTS]
PROC DoFilter(PTR predicateFun
INT ARRAY src BYTE srcSize
INT ARRAY dst BYTE POINTER dstSize)
INT i
dstSize^=0
FOR i=0 TO srcSize-1
DO
value=src(i)
IF Predicate(predicateFun) THEN
dst(dstSize^)=value
dstSize^==+1
FI
OD
RETURN
PROC DoFilterInplace(PTR predicateFun
INT ARRAY data BYTE POINTER size)
INT i,j
i=0
WHILE i<size^
DO
value=data(i)
IF Predicate(predicateFun)=0 THEN
FOR j=i TO size^-2
DO
data(j)=data(j+1)
OD
size^==-1
ELSE
i==+1
FI
OD
RETURN
BYTE FUNC Even()
IF (value&1)=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC NonNegative()
IF value>=0 THEN
RETURN (1)
FI
RETURN (0)
PROC Main()
INT ARRAY src=[65532 3 5 2 65529 1 0 65300 4123],dst(9)
BYTE srcSize=[9],dstSize
PrintE("Non destructive operations:") PutE()
PrintE("Original array:")
PrintArray(src,srcSize)
DoFilter(Even,src,srcSize,dst,@dstSize)
PrintE("Select all even numbers:")
PrintArray(dst,dstSize)
DoFilter(NonNegative,src,srcSize,dst,@dstSize)
PrintE("Select all non negative numbers:")
PrintArray(dst,dstSize)
PutE()
PrintE("Destructive operations:") PutE()
PrintE("Original array:")
PrintArray(src,srcSize)
DoFilterInplace(Even,src,@srcSize)
PrintE("Select all even numbers:")
PrintArray(src,srcSize)
DoFilterInplace(NonNegative,src,@srcSize)
PrintE("Select all non negative numbers:")
PrintArray(src,srcSize)
RETURN
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#Haskell
|
Haskell
|
type Pt a = (a, a)
data Overlapping = Inside | Outside | Boundary
deriving (Show, Eq)
data Triangle a = Triangle (Pt a) (Pt a) (Pt a)
deriving Show
vertices (Triangle a b c) = [a, b, c]
-- Performs the affine transformation
-- which turns a triangle to Triangle (0,0) (0,s) (s,0)
-- where s is half of the triangles' area
toTriangle :: Num a => Triangle a -> Pt a -> (a, Pt a)
toTriangle t (x,y) = let
[(x0,y0), (x1,y1), (x2,y2)] = vertices t
s = x2*(y0-y1)+x0*(y1-y2)+x1*(-y0+y2)
in ( abs s
, ( signum s * (x2*(-y+y0)+x0*(y-y2)+x*(-y0+y2))
, signum s * (x1*(y-y0)+x*(y0-y1)+x0*(-y+y1))))
overlapping :: (Eq a, Ord a, Num a) =>
Triangle a -> Pt a -> Overlapping
overlapping t p = case toTriangle t p of
(s, (x, y))
| s == 0 && (x == 0 || y == 0) -> Boundary
| s == 0 -> Outside
| x > 0 && y > 0 && y < s - x -> Inside
| (x <= s && x >= 0) &&
(y <= s && y >= 0) &&
(x == 0 || y == 0 || y == s - x) -> Boundary
| otherwise -> Outside
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Swift
|
Swift
|
func list(s: Any...) -> [Any] {
return s
}
func flatten<T>(s: [Any]) -> [T] {
var r = [T]()
for e in s {
switch e {
case let a as [Any]:
r += flatten(a)
case let x as T:
r.append(x)
default:
assert(false, "value of wrong type")
}
}
return r
}
let s = list(list(1),
2,
list(list(3, 4), 5),
list(list(list())),
list(list(list(6))),
7,
8,
list()
)
println(s)
let result : [Int] = flatten(s)
println(result)
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#DWScript
|
DWScript
|
var level : Integer;
procedure Recursive;
begin
Inc(level);
try
Recursive;
except
end;
end;
Recursive;
Println('Recursion Level is ' + IntToStr(level));
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
rec-fun n:
!. n
rec-fun ++ n
rec-fun 0
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Haskell
|
Haskell
|
import Data.Char (digitToInt, intToDigit, isDigit)
import Data.List (transpose, unwords)
import Numeric (readInt, showIntAtBase)
---------- PALINDROMIC IN BOTH BINARY AND TERNARY --------
dualPalindromics :: [Integer]
dualPalindromics =
0 :
1 :
take
4
( filter
isBinPal
(readBase3 . base3Palindrome <$> [1 ..])
)
base3Palindrome :: Integer -> String
base3Palindrome =
((<>) <*> (('1' :) . reverse)) . showBase 3
isBinPal :: Integer -> Bool
isBinPal n =
( \s ->
( \(q, r) ->
(1 == r)
&& drop (succ q) s == reverse (take q s)
)
$ quotRem (length s) 2
)
$ showBase 2 n
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
putStrLn
( unwords
<$> transpose
( ( fmap
=<< flip justifyLeft ' '
. succ
. maximum
. fmap length
)
<$> transpose
( ["Decimal", "Ternary", "Binary"] :
fmap
( (<*>) [show, showBase 3, showBase 2]
. return
)
dualPalindromics
)
)
)
where
justifyLeft n c s = take n (s <> replicate n c)
-------------------------- BASES -------------------------
readBase3 :: String -> Integer
readBase3 = fst . head . readInt 3 isDigit digitToInt
showBase :: Integer -> Integer -> String
showBase base n = showIntAtBase base intToDigit n []
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Tcl
|
Tcl
|
package require Tcl 8.5
proc tcl::mathfunc::modexp {a b n} {
for {set c 1} {$b} {set a [expr {$a*$a%$n}]} {
if {$b & 1} {
set c [expr {$c*$a%$n}]
}
set b [expr {$b >> 1}]
}
return $c
}
# Based on Miller-Rabin primality testing, but with small prime check first
proc is_prime {n {count 10}} {
# fast check against small primes
foreach p {
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
} {
if {$n == $p} {return true}
if {$n % $p == 0} {return false}
}
# write n-1 as 2^s·d with d odd by factoring powers of 2 from n-1
set d [expr {$n - 1}]
for {set s 0} {$d & 1 == 0} {incr s} {
set d [expr {$d >> 1}]
}
for {} {$count > 0} {incr count -1} {
set a [expr {2 + int(rand()*($n - 4))}]
set x [expr {modexp($a, $d, $n)}]
if {$x == 1 || $x == $n - 1} continue
for {set r 1} {$r < $s} {incr r} {
set x [expr {modexp($x, 2, $n)}]
if {$x == 1} {return false}
if {$x == $n - 1} break
}
if {$x != $n-1} {return false}
}
return true
}
proc max_left_truncatable_prime {base} {
set stems {}
for {set i 2} {$i < $base} {incr i} {
if {[is_prime $i]} {
lappend stems $i
}
}
set primes $stems
set size 0
for {set b $base} {[llength $stems]} {set b [expr {$b * $base}]} {
# Progress monitoring is nice once we get to 10 and beyond...
if {$base > 9} {
puts "\t[llength $stems] candidates at length [incr size]"
}
set primes $stems
set certainty [expr {[llength $primes] > 100 ? 1 : 5}]
set stems {}
foreach s $primes {
for {set i 1} {$i < $base} {incr i} {
set n [expr {$b*$i + $s}]
if {[is_prime $n $certainty]} {
lappend stems $n
}
}
}
}
# Could be several at same length; choose largest
return [tcl::mathfunc::max {*}$primes]
}
for {set i 3} {$i <= 20} {incr i} {
puts "$i: [max_left_truncatable_prime $i]"
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Elm
|
Elm
|
import Html exposing (text)
import List exposing (map)
main =
[1..100] |> map getWordForNum |> text
getWordForNum num =
if num % 15 == 0 then
"FizzBuzz"
else if num % 3 == 0 then
"Fizz"
else if num % 5 == 0 then
"Buzz"
else
String.fromInt num
|
http://rosettacode.org/wiki/File_size
|
File size
|
Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
|
#11l
|
11l
|
V size1 = fs:file_size(‘input.txt’)
V size2 = fs:file_size(‘/input.txt’)
|
http://rosettacode.org/wiki/File_modification_time
|
File modification time
|
Task
Get and set the modification time of a file.
|
#Ada
|
Ada
|
with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
procedure File_Time_Test is
begin
Put_Line (Image (Modification_Time ("file_time_test.adb")));
end File_Time_Test;
|
http://rosettacode.org/wiki/File_size_distribution
|
File size distribution
|
Task
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.
My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.
Don't forget that empty files may exist, to serve as a marker.
Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
|
#Delphi
|
Delphi
|
program File_size_distribution;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Math,
Winapi.Windows;
function Commatize(n: Int64): string;
begin
result := n.ToString;
if n < 0 then
delete(result, 1, 1);
var le := result.Length;
var i := le - 3;
while i >= 1 do
begin
Insert(',', result, i + 1);
dec(i, 3);
end;
if n >= 0 then
exit;
Result := '-' + result;
end;
procedure Walk(Root: string; walkFunc: TProc<string, TWin32FindData>); overload;
var
rec: TWin32FindData;
h: THandle;
directory, PatternName: string;
begin
if not Assigned(walkFunc) then
exit;
Root := IncludeTrailingPathDelimiter(Root);
h := FindFirstFile(Pchar(Root + '*.*'), rec);
if (INVALID_HANDLE_VALUE <> h) then
repeat
if rec.cFileName[0] = '.' then
Continue;
walkFunc(directory, rec);
if ((rec.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) =
FILE_ATTRIBUTE_DIRECTORY) and (rec.cFileName[0] <> '.') then
Walk(Root + rec.cFileName, walkFunc);
until not FindNextFile(h, rec);
FindClose(h);
end;
procedure FileSizeDistribution(root: string);
var
sizes: TArray<Integer>;
files, directories, totalSize, size, i: UInt64;
c: string;
begin
SetLength(sizes, 12);
files := 0;
directories := 0;
totalSize := 0;
size := 0;
Walk(root,
procedure(path: string; info: TWin32FindData)
var
logSize: Extended;
index: integer;
begin
inc(files);
if (info.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) =
FILE_ATTRIBUTE_DIRECTORY then
inc(directories);
size := info.nFileSizeHigh shl 32 + info.nFileSizeLow;
if size = 0 then
begin
sizes[0] := sizes[0] + 1;
exit;
end;
inc(totalSize, size);
logSize := Log10(size);
index := Floor(logSize);
sizes[index] := sizes[index] + 1;
end);
writeln('File size distribution for "', root, '" :-'#10);
for i := 0 to High(sizes) do
begin
if i = 0 then
write(' ')
else
write('+ ');
writeln(format('Files less than 10 ^ %-2d bytes : %5d', [i, sizes[i]]));
end;
writeln(' -----');
writeln('= Total number of files : ', files: 5);
writeln(' including directories : ', directories: 5);
c := commatize(totalSize);
writeln(#10' Total size of files : ', c, 'bytes');
end;
begin
fileSizeDistribution('.');
readln;
end.
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#BASIC256
|
BASIC256
|
x = "/home/user1/tmp/coverage/test"
y = "/home/user1/tmp/covert/operator"
z = "/home/user1/tmp/coven/members"
a = length(x)
if a > length(y) then a = length(y)
if a > length(z) then a = length(z)
for i = 1 to a
if mid(x, i, 1) <> mid(y, i, 1) then exit for
next i
a = i - 1
for i = 1 to a
if mid(x, i, 1) <> mid(z, i, 1) then exit for
next i
a = i - 1
if mid(x, i, 1) <> "/" then
for i = a to 1 step -1
if "/" = mid(x, i, 1) then exit for
next i
end if
REM Task description says no trailing slash, so...
a = i - 1
print "Common path is '"; left(x, a); "'"
|
http://rosettacode.org/wiki/Find_common_directory_path
|
Find common directory path
|
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
|
#Batch_File
|
Batch File
|
@echo off
setlocal enabledelayedexpansion
call:commonpath /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members
pause>nul
exit /b
:commonpath
setlocal enabledelayedexpansion
for %%i in (%*) do (
set /a args+=1
set arg!args!=%%i
set fullarg!args!=%%i
)
for /l %%i in (1,1,%args%) do set fullarg%%i=!fullarg%%i:/= !
for /l %%i in (1,1,%args%) do (
set tempcount=0
for %%j in (!fullarg%%i!) do (
set /a tempcount+=1
set arg%%it!tempcount!=%%j
set arg%%itokencount=!tempcount!
)
)
set mintokencount=%arg1tokencount%
set leasttokens=1
for /l %%i in (1,1,%args%) do (
set currenttokencount=!arg%%itokencount!
if !currenttokencount! lss !mintokencount! (
set mintokencount=!currenttokencount!
set leasttokens=%%i
)
)
for /l %%i in (1,1,%mintokencount%) do set commonpath%%i=!arg%leasttokens%t%%i!
for /l %%i in (1,1,%mintokencount%) do (
for /l %%j in (1,1,%args%) do (
set currentpath=!arg%%jt%%i!
if !currentpath!==!commonpath%%i! set pathtokens%%j=%%i
)
)
set minpathtokens=%pathtokens1%
set leastpathtokens=1
for /l %%i in (1,1,%args%) do (
set currentpathtokencount=!pathtokens%%i!
if !currentpathtokencount! lss !minpathtokens! (
set minpathtokencount=!currentpathtokencount!
set leastpathtokens=%%i
)
)
set commonpath=/
for /l %%i in (1,1,!pathtokens%leastpathtokens%!) do set commonpath=!commonpath!!arg%leastpathtokens%t%%i!/
echo %commonpath%
endlocal
exit /b
|
http://rosettacode.org/wiki/Filter
|
Filter
|
Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
|
#ActionScript
|
ActionScript
|
var arr:Array = new Array(1, 2, 3, 4, 5);
var evens:Array = new Array();
for (var i:int = 0; i < arr.length(); i++) {
if (arr[i] % 2 == 0)
evens.push(arr[i]);
}
|
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
|
Find if a point is within a triangle
|
Find if a point is within a triangle.
Task
Assume points are on a plane defined by (x, y) real number coordinates.
Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.
You may use any algorithm.
Bonus: explain why the algorithm you chose works.
Related tasks
Determine_if_two_triangles_overlap
Also see
Discussion of several methods. [[1]]
Determine if a point is in a polygon [[2]]
Triangle based coordinate systems [[3]]
Wolfram entry [[4]]
|
#Java
|
Java
|
import java.util.Objects;
public class FindTriangle {
private static final double EPS = 0.001;
private static final double EPS_SQUARE = EPS * EPS;
public static class Point {
private final double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
@Override
public String toString() {
return String.format("(%f, %f)", x, y);
}
}
public static class Triangle {
private final Point p1, p2, p3;
public Triangle(Point p1, Point p2, Point p3) {
this.p1 = Objects.requireNonNull(p1);
this.p2 = Objects.requireNonNull(p2);
this.p3 = Objects.requireNonNull(p3);
}
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public Point getP3() {
return p3;
}
private boolean pointInTriangleBoundingBox(Point p) {
var xMin = Math.min(p1.getX(), Math.min(p2.getX(), p3.getX())) - EPS;
var xMax = Math.max(p1.getX(), Math.max(p2.getX(), p3.getX())) + EPS;
var yMin = Math.min(p1.getY(), Math.min(p2.getY(), p3.getY())) - EPS;
var yMax = Math.max(p1.getY(), Math.max(p2.getY(), p3.getY())) + EPS;
return !(p.getX() < xMin || xMax < p.getX() || p.getY() < yMin || yMax < p.getY());
}
private static double side(Point p1, Point p2, Point p) {
return (p2.getY() - p1.getY()) * (p.getX() - p1.getX()) + (-p2.getX() + p1.getX()) * (p.getY() - p1.getY());
}
private boolean nativePointInTriangle(Point p) {
boolean checkSide1 = side(p1, p2, p) >= 0;
boolean checkSide2 = side(p2, p3, p) >= 0;
boolean checkSide3 = side(p3, p1, p) >= 0;
return checkSide1 && checkSide2 && checkSide3;
}
private double distanceSquarePointToSegment(Point p1, Point p2, Point p) {
double p1_p2_squareLength = (p2.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p2.getY() - p1.getY()) * (p2.getY() - p1.getY());
double dotProduct = ((p.getX() - p1.getX()) * (p2.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p2.getY() - p1.getY())) / p1_p2_squareLength;
if (dotProduct < 0) {
return (p.getX() - p1.getX()) * (p.getX() - p1.getX()) + (p.getY() - p1.getY()) * (p.getY() - p1.getY());
}
if (dotProduct <= 1) {
double p_p1_squareLength = (p1.getX() - p.getX()) * (p1.getX() - p.getX()) + (p1.getY() - p.getY()) * (p1.getY() - p.getY());
return p_p1_squareLength - dotProduct * dotProduct * p1_p2_squareLength;
}
return (p.getX() - p2.getX()) * (p.getX() - p2.getX()) + (p.getY() - p2.getY()) * (p.getY() - p2.getY());
}
private boolean accuratePointInTriangle(Point p) {
if (!pointInTriangleBoundingBox(p)) {
return false;
}
if (nativePointInTriangle(p)) {
return true;
}
if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
return true;
}
if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
return true;
}
return distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE;
}
public boolean within(Point p) {
Objects.requireNonNull(p);
return accuratePointInTriangle(p);
}
@Override
public String toString() {
return String.format("Triangle[%s, %s, %s]", p1, p2, p3);
}
}
private static void test(Triangle t, Point p) {
System.out.println(t);
System.out.printf("Point %s is within triangle? %s\n", p, t.within(p));
}
public static void main(String[] args) {
var p1 = new Point(1.5, 2.4);
var p2 = new Point(5.1, -3.1);
var p3 = new Point(-3.8, 1.2);
var tri = new Triangle(p1, p2, p3);
test(tri, new Point(0, 0));
test(tri, new Point(0, 1));
test(tri, new Point(3, 1));
System.out.println();
p1 = new Point(1.0 / 10, 1.0 / 9);
p2 = new Point(100.0 / 8, 100.0 / 3);
p3 = new Point(100.0 / 4, 100.0 / 9);
tri = new Triangle(p1, p2, p3);
var pt = new Point(p1.getX() + (3.0 / 7) * (p2.getX() - p1.getX()), p1.getY() + (3.0 / 7) * (p2.getY() - p1.getY()));
test(tri, pt);
System.out.println();
p3 = new Point(-100.0 / 8, 100.0 / 6);
tri = new Triangle(p1, p2, p3);
test(tri, pt);
}
}
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Tailspin
|
Tailspin
|
templates flatten
[ $ -> # ] !
when <[]> do
$... -> #
otherwise
$ !
end flatten
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] -> flatten -> !OUT::write
|
http://rosettacode.org/wiki/Flatten_a_list
|
Flatten a list
|
Task
Write a function to flatten the nesting in an arbitrary list of values.
Your program should work on the equivalent of this list:
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
[1, 2, 3, 4, 5, 6, 7, 8]
Related task
Tree traversal
|
#Tcl
|
Tcl
|
proc flatten list {
for {set old {}} {$old ne $list} {} {
set old $list
set list [join $list]
}
return $list
}
puts [flatten {{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}}]
# ===> 1 2 3 4 5 6 7 8
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#E
|
E
|
func recurse i . .
print i
call recurse i + 1
.
call recurse 0
|
http://rosettacode.org/wiki/Find_limit_of_recursion
|
Find limit of recursion
|
Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
|
#EasyLang
|
EasyLang
|
func recurse i . .
print i
call recurse i + 1
.
call recurse 0
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#J
|
J
|
isPalin=: -: |. NB. check if palindrome
toBase=: #.inv"0 NB. convert to base(s) in left arg
filterPalinBase=: ] #~ isPalin@toBase/ NB. palindromes for base(s)
find23Palindromes=: 3 filterPalinBase 2 filterPalinBase ] NB. palindromes in both base 2 and base 3
showBases=: [: ;:inv@|: <@({&'0123456789ABCDEFGH')@toBase/ NB. display numbers in bases
NB.*getfirst a Adverb to get first y items returned by verb u
getfirst=: adverb define
100000x u getfirst y
:
res=. 0$0
start=. 0
blk=. i.x
whilst. y > #res do.
tmp=. u start + blk
start=. start + x
res=. res, tmp
end.
y{.res
)
|
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
|
Find palindromic numbers in both binary and ternary bases
|
Find palindromic numbers in both binary and ternary bases
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in both:
base 2
base 3
Display 0 (zero) as the first number found, even though some other definitions ignore it.
Optionally, show the decimal number found in its binary and ternary form.
Show all output here.
It's permissible to assume the first two numbers and simply list them.
See also
Sequence A60792, numbers that are palindromic in bases 2 and 3 on The On-Line Encyclopedia of Integer Sequences.
|
#Java
|
Java
|
public class Pali23 {
public static boolean isPali(String x){
return x.equals(new StringBuilder(x).reverse().toString());
}
public static void main(String[] args){
for(long i = 0, count = 0; count < 6;i++){
if((i & 1) == 0 && (i != 0)) continue; //skip non-zero evens, nothing that ends in 0 in binary can be in this sequence
//maybe speed things up through short-circuit evaluation by putting toString in the if
//testing up to 10M, base 2 has slightly fewer palindromes so do that one first
if(isPali(Long.toBinaryString(i)) && isPali(Long.toString(i, 3))){
System.out.println(i + ", " + Long.toBinaryString(i) + ", " + Long.toString(i, 3));
count++;
}
}
}
}
|
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
|
Find largest left truncatable prime in a given base
|
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2.
Let's consider what happens in base 10. Obviously the right most digit must be prime, so in base 10 candidates are 2,3,5,7. Putting a digit in the range 1 to base-1 in front of each candidate must result in a prime. So 2 and 5, like the whale and the petunias in The Hitchhiker's Guide to the Galaxy, come into existence only to be extinguished before they have time to realize it, because 2 and 5 preceded by any digit in the range 1 to base-1 is not prime. Some numbers formed by preceding 3 or 7 by a digit in the range 1 to base-1 are prime. So 13,17,23,37,43,47,53,67,73,83,97 are candidates. Again, putting a digit in the range 1 to base-1 in front of each candidate must be a prime. Repeating until there are no larger candidates finds the largest left truncatable prime.
Let's work base 3 by hand:
0 and 1 are not prime so the last digit must be 2. 123 = 510 which is prime, 223 = 810 which is not so 123 is the only candidate. 1123 = 1410 which is not prime, 2123 = 2310 which is, so 2123 is the only candidate. 12123 = 5010 which is not prime, 22123 = 7710 which also is not prime. So there are no more candidates, therefore 23 is the largest left truncatable prime in base 3.
The task is to reconstruct as much, and possibly more, of the table in the OEIS as you are able.
Related Tasks:
Miller-Rabin primality test
|
#Wren
|
Wren
|
import "/big" for BigInt
import "/fmt" for Conv, Fmt
import "/sort" for Sort
import "/ioutil" for Input
var nextLeftTruncatablePrimes = Fn.new { |n, radix, certainty|
var probablePrimes = []
var baseString = (n == BigInt.zero) ? "" : n.toBaseString(radix)
for (i in 1...radix) {
var p = BigInt.fromBaseString(Conv.itoa(i, radix) + baseString, radix)
if (p.isProbablePrime(certainty)) probablePrimes.add(p)
}
return probablePrimes
}
var largestLeftTruncatablePrime = Fn.new { |radix, certainty|
var lastList = null
var list = nextLeftTruncatablePrimes.call(BigInt.zero, radix, certainty)
while (!list.isEmpty) {
lastList = list
list = []
for (n in lastList) list.addAll(nextLeftTruncatablePrimes.call(n, radix, certainty))
}
if (!lastList) return null
Sort.quick(lastList)
return lastList[-1]
}
var maxRadix = Input.integer("Enter maximum radix : ", 3, 36)
var certainty = Input.integer("Enter certainty : ", 1, 100)
System.print()
for (radix in 3..maxRadix) {
var largest = largestLeftTruncatablePrime.call(radix, certainty)
Fmt.write("Base = $-2d : ", radix)
if (!largest) {
System.print("No left truncatable prime")
} else {
Fmt.print("$-35i -> $s", largest, largest.toBaseString(radix))
}
}
|
http://rosettacode.org/wiki/FizzBuzz
|
FizzBuzz
|
Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
|
#Emacs_Lisp
|
Emacs Lisp
|
(defun fizzbuzz (n)
(cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz")
((zerop (% n 3)) "Fizz")
((zerop (% n 5)) "Buzz")
(t n)))
;; loop & print from 0 to 100
(dotimes (i 101)
(message "%s" (fizzbuzz i)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.