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/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #D | D | import core.stdc.stdio, std.math, std.typecons, std.string, std.conv,
std.algorithm, std.ascii, std.array, bitmap, grayscale_image;
enum maxBrightness = 255;
alias Pixel = short;
alias IntT = typeof(size_t.init.signed);
// If normalize is true, map pixels to range 0...maxBrightness.
void convolution(bool normalize)(in Pixel[] inp, Pixel[] outp,
in float[] kernel,
in IntT nx, in IntT ny, in IntT kn)
pure nothrow @nogc in {
assert(kernel.length == kn ^^ 2);
assert(kn % 2 == 1);
assert(nx > kn && ny > kn);
assert(inp.length == outp.length);
} body {
//immutable IntT kn = sqrti(kernel.length);
immutable IntT khalf = kn / 2;
static if (normalize) {
float pMin = float.max, pMax = -float.max;
foreach (immutable m; khalf .. nx - khalf) {
foreach (immutable n; khalf .. ny - khalf) {
float pixel = 0.0;
size_t c;
foreach (immutable j; -khalf .. khalf + 1) {
foreach (immutable i; -khalf .. khalf + 1) {
pixel += inp[(n - j) * nx + m - i] * kernel[c];
c++;
}
}
if (pixel < pMin) pMin = pixel;
if (pixel > pMax) pMax = pixel;
}
}
}
foreach (immutable m; khalf .. nx - khalf) {
foreach (immutable n; khalf .. ny - khalf) {
float pixel = 0.0;
size_t c;
foreach (immutable j; -khalf .. khalf + 1) {
foreach (immutable i; -khalf .. khalf + 1) {
pixel += inp[(n - j) * nx + m - i] * kernel[c];
c++;
}
}
static if (normalize)
pixel = maxBrightness * (pixel - pMin) / (pMax - pMin);
outp[n * nx + m] = cast(Pixel)pixel;
}
}
}
void gaussianFilter(in Pixel[] inp, Pixel[] outp,
in IntT nx, in IntT ny, in float sigma)
pure nothrow in {
assert(inp.length == outp.length);
} body {
immutable IntT n = 2 * cast(IntT)(2 * sigma) + 3;
immutable float mean = floor(n / 2.0);
auto kernel = new float[n * n];
debug fprintf(stderr,
"gaussianFilter: kernel size %d, sigma=%g\n",
n, sigma);
size_t c;
foreach (immutable i; 0 .. n) {
foreach (immutable j; 0 .. n) {
kernel[c] = exp(-0.5 * (((i - mean) / sigma) ^^ 2 +
((j - mean) / sigma) ^^ 2))
/ (2 * PI * sigma * sigma);
c++;
}
}
convolution!true(inp, outp, kernel, nx, ny, n);
}
Image!Pixel cannyEdgeDetection(in Image!Pixel inp,
in IntT tMin, in IntT tMax,
in float sigma)
pure nothrow in {
assert(inp !is null);
} body {
immutable IntT nx = inp.nx.signed;
immutable IntT ny = inp.ny.signed;
auto outp = new Pixel[nx * ny];
gaussianFilter(inp.image, outp, nx, ny, sigma);
static immutable float[] Gx = [-1, 0, 1,
-2, 0, 2,
-1, 0, 1];
auto after_Gx = new Pixel[nx * ny];
convolution!false(outp, after_Gx, Gx, nx, ny, 3);
static immutable float[] Gy = [ 1, 2, 1,
0, 0, 0,
-1,-2,-1];
auto after_Gy = new Pixel[nx * ny];
convolution!false(outp, after_Gy, Gy, nx, ny, 3);
auto G = new Pixel[nx * ny];
foreach (i; 1 .. nx - 1)
foreach (j; 1 .. ny - 1) {
immutable size_t c = i + nx * j;
G[c] = cast(Pixel)hypot(after_Gx[c], after_Gy[c]);
}
// Non-maximum suppression, straightforward implementation.
auto nms = new Pixel[nx * ny];
foreach (immutable i; 1 .. nx - 1)
foreach (immutable j; 1 .. ny - 1) {
immutable IntT c = i + nx * j,
nn = c - nx,
ss = c + nx,
ww = c + 1,
ee = c - 1,
nw = nn + 1,
ne = nn - 1,
sw = ss + 1,
se = ss - 1;
immutable aux = atan2(double(after_Gy[c]),
double(after_Gx[c])) + PI;
immutable float dir = float((aux % PI) / PI) * 8;
if (((dir <= 1 || dir > 7) && G[c] > G[ee] &&
G[c] > G[ww]) || // 0 deg.
((dir > 1 && dir <= 3) && G[c] > G[nw] &&
G[c] > G[se]) || // 45 deg.
((dir > 3 && dir <= 5) && G[c] > G[nn] &&
G[c] > G[ss]) || // 90 deg.
((dir > 5 && dir <= 7) && G[c] > G[ne] &&
G[c] > G[sw])) // 135 deg.
nms[c] = G[c];
else
nms[c] = 0;
}
// Reuse array used as a stack. nx*ny/2 elements should be enough.
IntT[] edges = (cast(IntT*)after_Gy.ptr)[0 .. after_Gy.length / 2];
outp[] = Pixel.init;
edges[] = 0;
// Tracing edges with hysteresis. Non-recursive implementation.
size_t c = 1;
foreach (immutable j; 1 .. ny - 1) {
foreach (immutable i; 1 .. nx - 1) {
if (nms[c] >= tMax && outp[c] == 0) { // Trace edges.
outp[c] = maxBrightness;
IntT nedges = 1;
edges[0] = c;
do {
nedges--;
immutable IntT t = edges[nedges];
immutable IntT[8] neighbours = [
t - nx, // nn
t + nx, // ss
t + 1, // ww
t - 1, // ee
t - nx + 1, // nw
t - nx - 1, // ne
t + nx + 1, // sw
t + nx - 1]; // se
foreach (immutable n; neighbours)
if (nms[n] >= tMin && outp[n] == 0) {
outp[n] = maxBrightness;
edges[nedges] = n;
nedges++;
}
} while (nedges > 0);
}
c++;
}
}
return Image!Pixel.fromData(outp, nx, ny);
}
void main(in string[] args) {
immutable fileName = (args.length == 2) ? args[1] : "lena.pgm";
Image!Pixel imIn;
imIn = imIn.loadPGM(fileName);
printf("Image size: %d x %d\n", imIn.nx, imIn.ny);
imIn.cannyEdgeDetection(45, 50, 1.0f).savePGM("lena_canny.pgm");
} |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #C.2B.2B | C++ | #include <cstdint>
#include <iomanip>
#include <iostream>
#include <sstream>
// Class representing an IPv4 address + netmask length
class ipv4_cidr {
public:
ipv4_cidr() {}
ipv4_cidr(std::uint32_t address, unsigned int mask_length)
: address_(address), mask_length_(mask_length) {}
std::uint32_t address() const {
return address_;
}
unsigned int mask_length() const {
return mask_length_;
}
friend std::istream& operator>>(std::istream&, ipv4_cidr&);
private:
std::uint32_t address_ = 0;
unsigned int mask_length_ = 0;
};
// Stream extraction operator, also performs canonicalization
std::istream& operator>>(std::istream& in, ipv4_cidr& cidr) {
int a, b, c, d, m;
char ch;
if (!(in >> a >> ch) || a < 0 || a > UINT8_MAX || ch != '.'
|| !(in >> b >> ch) || b < 0 || b > UINT8_MAX || ch != '.'
|| !(in >> c >> ch) || c < 0 || c > UINT8_MAX || ch != '.'
|| !(in >> d >> ch) || d < 0 || d > UINT8_MAX || ch != '/'
|| !(in >> m) || m < 1 || m > 32) {
in.setstate(std::ios_base::failbit);
return in;
}
uint32_t mask = ~((1 << (32 - m)) - 1);
uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;
address &= mask;
cidr.address_ = address;
cidr.mask_length_ = m;
return in;
}
// Stream insertion operator
std::ostream& operator<<(std::ostream& out, const ipv4_cidr& cidr) {
uint32_t address = cidr.address();
unsigned int d = address & UINT8_MAX;
address >>= 8;
unsigned int c = address & UINT8_MAX;
address >>= 8;
unsigned int b = address & UINT8_MAX;
address >>= 8;
unsigned int a = address & UINT8_MAX;
out << a << '.' << b << '.' << c << '.' << d << '/'
<< cidr.mask_length();
return out;
}
int main(int argc, char** argv) {
const char* tests[] = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
for (auto test : tests) {
std::istringstream in(test);
ipv4_cidr cidr;
if (in >> cidr)
std::cout << std::setw(18) << std::left << test << " -> "
<< cidr << '\n';
else
std::cerr << test << ": invalid CIDR\n";
}
return 0;
} |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #D | D | import std.stdio, std.algorithm, std.range;
uint[] castOut(in uint base=10, in uint start=1, in uint end=999999) {
auto ran = iota(base - 1)
.filter!(x => x % (base - 1) == (x * x) % (base - 1));
auto x = start / (base - 1);
immutable y = start % (base - 1);
typeof(return) result;
while (true) {
foreach (immutable n; ran) {
immutable k = (base - 1) * x + n;
if (k < start)
continue;
if (k > end)
return result;
result ~= k;
}
x++;
}
}
void main() {
castOut(16, 1, 255).writeln;
castOut(10, 1, 99).writeln;
castOut(17, 1, 288).writeln;
} |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Nim | Nim | import algorithm
import tables
const None = -1 # Index number used to indicate no data.
type
Point = array[3, float]
Face = seq[int]
Edge = object
pn1: int # Point number 1.
pn2: int # Point number 2.
fn1: int # Face number 1.
fn2: int # Face number 2.
cp: Point # Center point.
PointEx = object
p: Point
n: int
PointNums = tuple[pn1, pn2: int]
####################################################################################################
# Point operations.
func `+`(p1, p2: Point): Point =
## Adds points p1 and p2.
for i in 0..Point.high:
result[i] = p1[i] + p2[i]
#---------------------------------------------------------------------------------------------------
func `*`(p: Point; m: float): Point =
## Multiply point p by m.
for i in 0..Point.high:
result[i] = p[i] * m
#---------------------------------------------------------------------------------------------------
func `/`(p: Point; d: float): Point =
## Divide point p by d.
for i in 0..Point.high:
result[i] = p[i] / d
#---------------------------------------------------------------------------------------------------
func centerPoint(p1, p2: Point): Point =
## Return a point in the center of the segment ended by points p1 and p2.
for i in 0..Point.high:
result[i] = (p1[i] + p2[i]) / 2
####################################################################################################
func getFacePoints(inputPoints: seq[Point]; inputFaces: seq[Face]): seq[Point] =
## For each face, a face point is created which is the average of all the points of the face.
result.setLen(inputFaces.len)
for i, currFace in inputFaces:
var facePoint: Point
for currPointIndex in currFace:
# Add currPoint to facePoint. Will divide later.
facePoint = facePoint + inputPoints[currPointIndex]
result[i] = facePoint / currFace.len.toFloat
#---------------------------------------------------------------------------------------------------
func getEdgesFaces(inputPoints: seq[Point]; inputFaces: seq[Face]): seq[Edge] =
## Get list of edges and the one or two adjacent faces in a list.
## Also get center point of edge.
# Get edges for each face.
var edges: seq[array[3, int]]
for faceNum, face in inputFaces:
# Loop over index into face.
for pointIndex in 0..face.high:
# If not last point then edge is current point and next point
# and for last point, edge is current point and first point.
var pointNum1 = face[pointIndex]
var pointNum2 = if pointIndex < face.high: face[pointIndex + 1] else: face[0]
# Order points in edge by lowest point number.
if pointNum1 > pointNum2:
swap pointNum1, pointNum2
edges &= [pointNum1, pointNum2, faceNum]
# Sort edges by pointNum1, pointNum2, faceNum.
edges.sort(proc(a1, a2: array[3, int]): int =
result = cmp(a1[0], a2[0])
if result == 0:
result = cmp(a1[1], a2[1])
if result == 0:
result = cmp(a1[2], a2[2]))
# Merge edges with 2 adjacent faces:
# [pointNum1, pointNum2, faceNum1, faceNum2] or
# [pointNum1, pointNum2, faceNum1, None]
var eIndex = 0
var mergedEdges: seq[array[4, int]]
while eIndex < edges.len:
let e1 = edges[eIndex]
# Check if not last edge.
if eIndex < edges.high:
let e2 = edges[eIndex + 1]
if e1[0] == e2[0] and e1[1] == e2[1]:
mergedEdges &= [e1[0], e1[1], e1[2], e2[2]]
inc eIndex, 2
else:
mergedEdges &= [e1[0], e1[1], e1[2], None]
inc eIndex
else:
mergedEdges &= [e1[0], e1[1], e1[2], None]
inc eIndex
# Add edge centers.
for me in mergedEdges:
let p1 = inputPoints[me[0]]
let p2 = inputPoints[me[1]]
let cp = centerPoint(p1, p2)
result.add(Edge(pn1: me[0], pn2: me[1], fn1: me[2], fn2: me[3], cp: cp))
#---------------------------------------------------------------------------------------------------
func getEdgePoints(inputPoints: seq[Point];
edgesFaces: seq[Edge];
facePoints: seq[Point]): seq[Point] =
## For each edge, an edge point is created which is the average between the center of the
## edge and the center of the segment made with the face points of the two adjacent faces.
result.setLen(edgesFaces.len)
for i, edge in edgesFaces:
# Get center of two facepoints.
let fp1 = facePoints[edge.fn1]
# If not two faces, just use one facepoint (should not happen for solid like a cube).
let fp2 = if edge.fn2 == None: fp1 else: facePoints[edge.fn2]
let cfp = centerPoint(fp1, fp2)
# Get average between center of edge and center of facePoints.
result[i] = centerPoint(edge.cp, cfp)
#---------------------------------------------------------------------------------------------------
func getAvgFacePoints(inputPoints: seq[Point];
inputFaces: seq[Face];
facePoints: seq[Point]): seq[Point] =
## For each point calculate the average of the face points of the faces the
## point belongs to (avgFacePoints), create a list of lists of two numbers
## [facePointSum, numPoints] by going through the points in all the faces then
## create the avgFacePoints list of point by dividing pointSum(x, y, z) by numPoints
var tempPoints = newSeq[PointEx](inputPoints.len)
# Loop through faces, updating tempPoints.
for faceNum, pointNums in inputFaces:
let fp = facePoints[faceNum]
for pointNum in pointNums:
let tp = tempPoints[pointNum].p
tempPoints[pointNum].p = tp + fp
inc tempPoints[pointNum].n
# Divide to build the result.
result.setLen(inputPoints.len)
for i, tp in tempPoints:
result[i] = tp.p / tp.n.toFloat
#---------------------------------------------------------------------------------------------------
func getAvgMidEdges(inputPoints: seq[Point]; edgesFaces: seq[Edge]): seq[Point] =
## Return the average of the centers of edges the point belongs to (avgMidEdges).
## Create list with entry for each point. Each entry has two elements. One is a point
## that is the sum of the centers of the edges and the other is the number of edges.
## After going through all edges divide by number of edges.
var tempPoints = newSeq[PointEx](inputPoints.len)
# Go through edgesFaces using center updating each point.
for edge in edgesFaces:
for pointNum in [edge.pn1, edge.pn2]:
let tp = tempPoints[pointNum].p
tempPoints[pointNum].p = tp + edge.cp
inc tempPoints[pointNum].n
# Divide out number of points to get average.
result.setLen(inputPoints.len)
for i, tp in tempPoints:
result[i] = tp.p / tp.n.toFloat
#---------------------------------------------------------------------------------------------------
func getPointsFaces(inputPoints: seq[Point]; inputFaces: seq[Face]): seq[int] =
# Return the number of faces for each point.
result.setLen(inputPoints.len)
# Loop through faces updating the result.
for pointNums in inputFaces:
for pointNum in pointNums:
inc result[pointNum]
#---------------------------------------------------------------------------------------------------
func getNewPoints(inputPoints: seq[Point]; pointsFaces: seq[int];
avgFacePoints, avgMidEdges: seq[Point]): seq[Point] =
## m1 = (n - 3.0) / n
## m2 = 1.0 / n
## m3 = 2.0 / n
## newCoords = (m1 * oldCoords) + (m2 * avgFacePoints) + (m3 * avgMidEdges)
result.setLen(inputPoints.len)
for pointNum, oldCoords in inputPoints:
let n = pointsFaces[pointNum].toFloat
let (m1, m2, m3) = ((n - 3) / n, 1 / n, 2 / n)
let p1 = oldCoords * m1
let afp = avgFacePoints[pointNum]
let p2 = afp * m2
let ame = avgMidEdges[pointNum]
let p3 = ame * m3
let p4 = p1 + p2
result[pointNum] = p4 + p3
#---------------------------------------------------------------------------------------------------
func switchNums(pointNums: PointNums): PointNums =
## Return tuple of point numbers sorted least to most.
if pointNums.pn1 < pointNums.pn2: pointNums
else: (pointNums.pn2, pointNums.pn1)
#---------------------------------------------------------------------------------------------------
func cmcSubdiv(inputPoints: seq[Point];
inputFaces: seq[Face]): tuple[p: seq[Point], f: seq[Face]] =
## For each face, a face point is created which is the average of all the points of the face.
## Each entry in the returned list is a point (x, y, z).
let facePoints = getFacePoints(inputPoints, inputFaces)
let edgesFaces = getEdgesFaces(inputPoints, inputFaces)
let edgePoints = getEdgePoints(inputPoints, edgesFaces, facePoints)
let avgFacePoints = getAvgFacePoints(inputPoints, inputFaces, facePoints)
let avgMidEdges = getAvgMidEdges(inputPoints, edgesFaces)
let pointsFaces = getPointsFaces(inputPoints, inputFaces)
var newPoints = getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges)
#[Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edgePoint ab, facePoint abc, edgePoint ca)
(b, edgePoint bc, facePoint abc, edgePoint ab)
(c, edgePoint ca, facePoint abc, edgePoint bc)
for a quad face (a,b,c,d):
(a, edgePoint ab, facePoint abcd, edgePoint da)
(b, edgePoint bc, facePoint abcd, edgePoint ab)
(c, edgePoint cd, facePoint abcd, edgePoint bc)
(d, edgePoint da, facePoint abcd, edgePoint cd)
facePoints is a list indexed by face number so that is easy to get.
edgePoints is a list indexed by the edge number which is an index into edgesFaces.
Need to add facePoints and edgePoints to newPoints and get index into each.
Then create two new structures:
facePointNums: list indexes by faceNum whose value is the index into newPoints.
edgePointNums: dictionary with key (pointNum1, pointNum2) and value is index into newPoints.
]#
# Add face points to newPoints.
var facePointNums: seq[int]
var nextPointNum = newPoints.len # PointNum after next append to newPoints.
for facePoint in facePoints:
newPoints.add(facePoint)
facePointNums.add(nextPointNum)
inc nextPointNum
# Add edge points to newPoints.
var edgePointNums: Table[tuple[pn1, pn2: int], int]
for edgeNum, edgesFace in edgesFaces:
let pointNum1 = edgesFace.pn1
let pointNum2 = edgesFace.pn2
newPoints.add(edgePoints[edgeNum])
edgePointNums[(pointNum1, pointNum2)] = nextPointNum
inc nextPointNum
# newPoints now has the points to output. Need new faces.
#[Just doing this case for now:
for a quad face (a,b,c,d):
(a, edgePoint ab, facePoint abcd, edgePoint da)
(b, edgePoint bc, facePoint abcd, edgePoint ab)
(c, edgePoint cd, facePoint abcd, edgePoint bc)
(d, edgePoint da, facePoint abcd, edgePoint cd)
newFaces will be a list of lists where the elements are like this:
[pointNum1, pointNum2, pointNum3, pointNum4]
]#
var newFaces: seq[Face]
for oldFaceNum, oldFace in inputFaces:
# 4 points face.
if oldFace.len == 4:
let (a, b, c, d) = (oldFace[0], oldface[1], oldface[2], oldface[3])
let facePointAbcd = facePointNums[oldFaceNum]
let edgePointAb = edgePointNums[switchNums((a, b))]
let edgePointDa = edgePointNums[switchNums((d, a))]
let edgePointBc = edgePointNums[switchNums((b, c))]
let edgePointCd = edgePointNums[switchNums((c, d))]
newFaces &= @[a, edgePointAb, facePointAbcd, edgePointDa]
newFaces &= @[b, edgePointBc, facePointAbcd, edgePointAb]
newFaces &= @[c, edgePointCd, facePointAbcd, edgePointBc]
newFaces &= @[d, edgePointDa, facePointAbcd, edgePointCd]
result = (newPoints, newFaces)
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
import strformat, strutils
let inputPoints = @[[-1.0, 1.0, 1.0],
[-1.0, -1.0, 1.0],
[1.0, -1.0, 1.0],
[1.0, 1.0, 1.0],
[1.0, -1.0, -1.0],
[1.0, 1.0, -1.0],
[-1.0, -1.0, -1.0],
[-1.0, 1.0, -1.0]]
let inputFaces = @[@[0, 1, 2, 3],
@[3, 2, 4, 5],
@[5, 4, 6, 7],
@[7, 0, 3, 5],
@[7, 6, 1, 0],
@[6, 1, 2, 4]]
var outputPoints = inputPoints
var outputFaces = inputFaces
const Iterations = 1
for i in 1..Iterations:
(outputPoints, outputFaces) = cmcSubdiv(outputPoints, outputFaces)
for p in outputPoints:
echo fmt"[{p[0]: .4f}, {p[1]: .4f}, {p[2]: .4f}]"
echo ""
for nums in outputFaces:
var s = "["
for n in nums:
s.addSep(", ", 1)
s.add(fmt"{n:2d}")
s.add(']')
echo s |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
int mod(int n, int d) {
return (d + n % d) % d;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
void print_carmichael_numbers(int prime1) {
for (int h3 = 1; h3 < prime1; ++h3) {
for (int d = 1; d < h3 + prime1; ++d) {
if (mod((h3 + prime1) * (prime1 - 1), d) != 0
|| mod(-prime1 * prime1, h3) != mod(d, h3))
continue;
int prime2 = 1 + (prime1 - 1) * (h3 + prime1)/d;
if (!is_prime(prime2))
continue;
int prime3 = 1 + prime1 * prime2/h3;
if (!is_prime(prime3))
continue;
if (mod(prime2 * prime3, prime1 - 1) != 1)
continue;
unsigned int c = prime1 * prime2 * prime3;
std::cout << std::setw(2) << prime1 << " x "
<< std::setw(4) << prime2 << " x "
<< std::setw(5) << prime3 << " = "
<< std::setw(10) << c << '\n';
}
}
}
int main() {
for (int p = 2; p <= 61; ++p) {
if (is_prime(p))
print_carmichael_numbers(p);
}
return 0;
} |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #CLU | CLU | % Reduction.
% First type = sequence type (must support S$elements and yield R)
% Second type = right (input) datatype
% Third type = left (output) datatype
reduce = proc [S,R,L: type] (f: proctype (L,R) returns (L),
id: L,
seq: S)
returns (L)
where S has elements: itertype (S) yields (R)
for elem: R in S$elements(seq) do
id := f(id, elem)
end
return(id)
end reduce
% This is necessary to get rid of the exceptions
add = proc (a,b: int) returns (int) return (a+b) end add
mul = proc (a,b: int) returns (int) return (a*b) end mul
% Usage
start_up = proc ()
% abbreviation - reducing int->int->int function over an array[int]
int_reduce = reduce[array[int], int, int]
po: stream := stream$primary_output()
nums: array[int] := array[int]$[1,2,3,4,5,6,7,8,9,10]
% find the sum and the product using reduce
sum: int := int_reduce(add, 0, nums)
product: int := int_reduce(mul, 1, nums)
stream$putl(po, "The sum of [1..10] is: " || int$unparse(sum))
stream$putl(po, "The product of [1..10] is: " || int$unparse(product))
end start_up |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Common_Lisp | Common Lisp | ; Basic usage
> (reduce #'* '(1 2 3 4 5))
120
; Using an initial value
> (reduce #'+ '(1 2 3 4 5) :initial-value 100)
115
; Using only a subsequence
> (reduce #'+ '(1 2 3 4 5) :start 1 :end 4)
9
; Apply a function to each element first
> (reduce #'+ '((a 1) (b 2) (c 3)) :key #'cadr)
6
; Right-associative reduction
> (reduce #'expt '(2 3 4) :from-end T)
2417851639229258349412352
; Compare with
> (reduce #'expt '(2 3 4))
4096 |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Phix | Phix | -- demo\rosetta\Chao_cipher.exw
with javascript_semantics
constant l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ",
r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
enum ENCRYPT, DECRYPT
function chao_cipher(string s, integer mode, bool show_steps)
integer len = length(s)
string out = repeat(' ',len),
left = l_alphabet,
right = r_alphabet
for i=1 to len do
if show_steps then printf(1,"%s %s\n", {left, right}) end if
integer index = find(s[i],iff(mode==ENCRYPT?right:left))
out[i] = iff(mode==ENCRYPT?left:right)[index]
if i==len then exit end if
/* permute left */
left = left[index..26]&left[1..index-1]
left[2..14] = left[3..14]&left[2]
/* permute right */
right = right[index+1..26]&right[1..index]
right[3..14] = right[4..14]&right[3]
end for
return out
end function
string plain_text = "WELLDONEISBETTERTHANWELLSAID"
printf(1,"The original plaintext is : %s\n", {plain_text})
--printf(1,"\nThe left and right alphabets after each permutation"&
-- " during encryption are :\n\n")
--string cipher_text = chao_cipher(plain_text, ENCRYPT, true)
string cipher_text = chao_cipher(plain_text, ENCRYPT, false)
printf(1,"\nThe ciphertext is : %s\n", {cipher_text})
string plain_text2 = chao_cipher(cipher_text, DECRYPT, false)
printf(1,"\nThe recovered plaintext is : %s\n", {plain_text2})
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #jq | jq | def binomial(n; k):
if k > n / 2 then binomial(n; n-k)
else reduce range(1; k+1) as $i (1; . * (n - $i + 1) / $i)
end;
# Direct (naive) computation using two numbers in Pascal's triangle:
def catalan_by_pascal: . as $n | binomial(2*$n; $n) - binomial(2*$n; $n-1); |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Julia | Julia | # v0.6
function pascal(n::Int)
r = ones(Int, n, n)
for i in 2:n, j in 2:n
r[i, j] = r[i-1, j] + r[i, j-1]
end
return r
end
function catalan_num(n::Int)
p = pascal(n + 2)
p[n+4:n+3:end-1] - diag(p, 2)
end
@show catalan_num(15) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Haskell | Haskell | import Text.Printf
main = printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg
where dog = "Benjamin"
dOG = "Samba"
dOg = "Bernie" |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Icon_and_Unicon | Icon and Unicon | procedure main()
dog := "Benjamin"
Dog := "Samba"
DOG := "Bernie"
if dog == DOG then
write("There is just one dog named ", dog,".")
else
write("The three dogs are named ", dog, ", ", Dog, " and ", DOG, ".")
end |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #D | D | import std.stdio;
void main() {
auto a = listProduct([1,2], [3,4]);
writeln(a);
auto b = listProduct([3,4], [1,2]);
writeln(b);
auto c = listProduct([1,2], []);
writeln(c);
auto d = listProduct([], [1,2]);
writeln(d);
}
auto listProduct(T)(T[] ta, T[] tb) {
struct Result {
int i, j;
bool empty() {
return i>=ta.length
|| j>=tb.length;
}
T[] front() {
return [ta[i], tb[j]];
}
void popFront() {
if (++j>=tb.length) {
j=0;
i++;
}
}
}
return Result();
} |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #AutoHotkey | AutoHotkey | Loop 15
out .= "`n" Catalan(A_Index)
Msgbox % clipboard := SubStr(out, 2)
catalan( n ) {
; By [VxE]. Returns ((2n)! / ((n + 1)! * n!)) if 0 <= N <= 22 (higher than 22 results in overflow)
If ( n < 3 ) ; values less than 3 are handled specially
Return n < 0 ? "" : n = 0 ? 1 : n
i := 1 ; initialize the accumulator to 1
Loop % n - 1 >> 1 ; build the numerator by multiplying odd values between 2N and N+1
i *= 1 + ( n - A_Index << 1 )
i <<= ( n - 2 >> 1 ) ; multiply the numerator by powers of 2 according to N
Loop % n - 3 >> 1 ; finish up by (integer) dividing by each of the non-cancelling factors
i //= A_Index + 2
Return i
} |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #ActionScript | ActionScript | // Static
MyClass.method(someParameter);
// Instance
myInstance.method(someParameter); |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #ALGOL_68 | ALGOL 68 | BEGIN
# draw a Cantor Set using ASCII #
INT lines = 5; # number of lines for the set #
# we must choose the line width so that the width of each segment is #
# divisible by 3 ( except for the final line where the segment width will #
# be 1 ) #
INT set width = 3 ^ ( lines - 1 );
[ set width ]CHAR set;
# start with a complete line #
FOR i TO set width DO set[ i ] := "#" OD;
print( ( set, newline ) );
# repeatedly modify the line, replacing the middle third of each segment #
# with blanks #
INT segment width := set width OVER 3;
WHILE segment width > 0 DO
INT set pos := 1;
WHILE set pos < ( set width - segment width ) DO
set pos +:= segment width;
FOR char pos FROM set pos TO ( set pos + segment width ) - 1 DO
set[ char pos ] := " "
OD;
set pos +:= segment width
OD;
print( ( set, newline ) );
segment width OVERAB 3
OD
END |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #Go | Go | package main
import (
ed "github.com/Ernyoke/Imger/edgedetection"
"github.com/Ernyoke/Imger/imgio"
"log"
)
func main() {
img, err := imgio.ImreadRGBA("Valve_original_(1).png")
if err != nil {
log.Fatal("Could not read image", err)
}
cny, err := ed.CannyRGBA(img, 15, 45, 5)
if err != nil {
log.Fatal("Could not perform Canny Edge detection")
}
err = imgio.Imwrite(cny, "Valve_canny_(1).png")
if err != nil {
log.Fatal("Could not write Canny image to disk")
}
} |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #C.23 | C# | using System;
using System.Net;
using System.Linq;
public class Program
{
public static void Main()
{
string[] tests = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
foreach (string t in tests) Console.WriteLine($"{t} => {Canonicalize(t)}");
}
static string Canonicalize(string cidr) => CIDR.Parse(cidr).Canonicalize().ToString();
}
readonly struct CIDR
{
public readonly IPAddress ip;
public readonly int length;
public static CIDR Parse(string cidr)
{
string[] parts = cidr.Split('/');
return new CIDR(IPAddress.Parse(parts[0]), int.Parse(parts[1]));
}
public CIDR(IPAddress ip, int length) => (this.ip, this.length) = (ip, length);
public CIDR Canonicalize() =>
new CIDR(
new IPAddress(
ToBytes(
ToInt(
ip.GetAddressBytes()
)
& ~((1 << (32 - length)) - 1)
)
),
length
);
private int ToInt(byte[] bytes) => bytes.Aggregate(0, (n, b) => (n << 8) | b);
private byte[] ToBytes(int n)
{
byte[] bytes = new byte[4];
for (int i = 3; i >= 0; i--) {
bytes[i] = (byte)(n & 0xFF);
n >>= 8;
}
return bytes;
}
public override string ToString() => $"{ip}/{length}";
} |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #FreeBASIC | FreeBASIC | Const base10 = 10
Dim As Integer c1 = 0, c2 = 0, k = 1
For k = 1 To base10^2
c1 += 1
If (k Mod (base10-1) = (k*k) Mod (base10-1)) Then c2 += 1: Print k;" ";
Next k
Print
Print Using "Intentar ## numeros en lugar de ### numeros ahorra un ##.##%"; c2; c1; 100-(100*c2/c1)
Sleep |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #OCaml | OCaml | open Dynar
let add3 (x1, y1, z1) (x2, y2, z2) (x3, y3, z3) =
( (x1 +. x2 +. x3),
(y1 +. y2 +. y3),
(z1 +. z2 +. z3) )
let mul m (x,y,z) = (m *. x, m *. y, m *. z)
let avg pts =
let n, (x,y,z) =
List.fold_left
(fun (n, (xt,yt,zt)) (xi,yi,zi) ->
succ n, (xt +. xi, yt +. yi, zt +. zi))
(1, List.hd pts) (List.tl pts)
in
let n = float_of_int n in
(x /. n, y /. n, z /. n)
let catmull ~points ~faces =
let da_points = Dynar.of_array points in
let new_faces = Dynar.of_array [| |] in
let push_face face = Dynar.push new_faces face in
let h1 = Hashtbl.create 43 in
let h2 = Hashtbl.create 43 in
let h3 = Hashtbl.create 43 in
let h4 = Hashtbl.create 43 in
let blg = Array.make (Array.length points) 0 in (* how many faces a point belongs to *)
let f_incr p = blg.(p) <- succ blg.(p) in
let eblg = Array.make (Array.length points) 0 in (* how many edges a point belongs to *)
let e_incr p = eblg.(p) <- succ eblg.(p) in
let edge a b = (min a b, max a b) in (* suitable for hash-table keys *)
let mid_edge p1 p2 =
let x1, y1, z1 = points.(p1)
and x2, y2, z2 = points.(p2) in
( (x1 +. x2) /. 2.0,
(y1 +. y2) /. 2.0,
(z1 +. z2) /. 2.0 )
in
let mid_face p1 p2 p3 p4 =
let x1, y1, z1 = points.(p1)
and x2, y2, z2 = points.(p2)
and x3, y3, z3 = points.(p3)
and x4, y4, z4 = points.(p4) in
( (x1 +. x2 +. x3 +. x4) /. 4.0,
(y1 +. y2 +. y3 +. y4) /. 4.0,
(z1 +. z2 +. z3 +. z4) /. 4.0 )
in
Array.iteri (fun i (a,b,c,d) ->
f_incr a; f_incr b; f_incr c; f_incr d;
let face_point = mid_face a b c d in
let face_pi = pushi da_points face_point in
Hashtbl.add h3 a face_point;
Hashtbl.add h3 b face_point;
Hashtbl.add h3 c face_point;
Hashtbl.add h3 d face_point;
let process_edge a b =
let ab = edge a b in
if not(Hashtbl.mem h1 ab)
then begin
let mid_ab = mid_edge a b in
let index = pushi da_points mid_ab in
Hashtbl.add h1 ab (index, mid_ab, [face_point]);
Hashtbl.add h2 a mid_ab;
Hashtbl.add h2 b mid_ab;
Hashtbl.add h4 mid_ab 1;
(index)
end
else begin
let index, mid_ab, fpl = Hashtbl.find h1 ab in
Hashtbl.replace h1 ab (index, mid_ab, face_point::fpl);
Hashtbl.add h4 mid_ab (succ(Hashtbl.find h4 mid_ab));
(index)
end
in
let mid_ab = process_edge a b
and mid_bc = process_edge b c
and mid_cd = process_edge c d
and mid_da = process_edge d a in
push_face (a, mid_ab, face_pi, mid_da);
push_face (b, mid_bc, face_pi, mid_ab);
push_face (c, mid_cd, face_pi, mid_bc);
push_face (d, mid_da, face_pi, mid_cd);
) faces;
Hashtbl.iter (fun (a,b) (index, mid_ab, fpl) ->
e_incr a; e_incr b;
if List.length fpl = 2 then
da_points.ar.(index) <- avg (mid_ab::fpl)
) h1;
Array.iteri (fun i old_vertex ->
let n = blg.(i)
and e_n = eblg.(i) in
(* if the vertex doesn't belongs to as many faces than edges
this means that this is a hole *)
if n = e_n then
begin
let avg_face_points =
let face_point_list = Hashtbl.find_all h3 i in
(avg face_point_list)
in
let avg_mid_edges =
let mid_edge_list = Hashtbl.find_all h2 i in
(avg mid_edge_list)
in
let n = float_of_int n in
let m1 = (n -. 3.0) /. n
and m2 = 1.0 /. n
and m3 = 2.0 /. n in
da_points.ar.(i) <-
add3 (mul m1 old_vertex)
(mul m2 avg_face_points)
(mul m3 avg_mid_edges)
end
else begin
let mid_edge_list = Hashtbl.find_all h2 i in
let mid_edge_list =
(* only average mid-edges near the hole *)
List.fold_left (fun acc mid_edge ->
match Hashtbl.find h4 mid_edge with
| 1 -> mid_edge::acc
| _ -> acc
) [] mid_edge_list
in
da_points.ar.(i) <- avg (old_vertex :: mid_edge_list)
end
) points;
(Dynar.to_array da_points,
Dynar.to_array new_faces)
;; |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #Clojure | Clojure |
(ns example
(:gen-class))
(defn prime? [n]
" Prime number test (using Java) "
(.isProbablePrime (biginteger n) 16))
(defn carmichael [p1]
" Triplets of Carmichael primes, with first element prime p1 "
(if (prime? p1)
(into [] (for [h3 (range 2 p1)
:let [g (+ h3 p1)]
d (range 1 g)
:when (and (= (mod (* g (dec p1)) d) 0)
(= (mod (- (* p1 p1)) h3) (mod d h3)))
:let [p2 (inc (quot (* (dec p1) g) d))]
:when (prime? p2)
:let [p3 (inc (quot (* p1 p2) h3))]
:when (prime? p3)
:when (= (mod (* p2 p3) (dec p1)) 1)]
[p1 p2 p3]))))
; Generate Result
(def numbers (mapcat carmichael (range 2 62)))
(println (count numbers) "Carmichael numbers found:")
(doseq [t numbers]
(println (format "%5d x %5d x %5d = %10d" (first t) (second t) (last t) (apply * t))))
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #D | D | void main() {
import std.stdio, std.algorithm, std.range, std.meta, std.numeric,
std.conv, std.typecons;
auto list = iota(1, 11);
alias ops = AliasSeq!(q{a + b}, q{a * b}, min, max, gcd);
foreach (op; ops)
writeln(op.stringof, ": ", list.reduce!op);
// std.algorithm.reduce supports multiple functions in parallel:
reduce!(ops[0], ops[3], text)(tuple(0, 0.0, ""), list).writeln;
} |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Python | Python | # Python3 implementation of Chaocipher
# left wheel = ciphertext wheel
# right wheel = plaintext wheel
def main():
# letters only! makealpha(key) helps generate lalpha/ralpha.
lalpha = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
ralpha = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
msg = "WELLDONEISBETTERTHANWELLSAID"
print("L:", lalpha)
print("R:", ralpha)
print("I:", msg)
print("O:", do_chao(msg, lalpha, ralpha, 1, 0), "\n")
do_chao(msg, lalpha, ralpha, 1, 1)
def do_chao(msg, lalpha, ralpha, en=1, show=0):
msg = correct_case(msg)
out = ""
if show:
print("="*54)
print(10*" " + "left:" + 21*" " + "right: ")
print("="*54)
print(lalpha, ralpha, "\n")
for L in msg:
if en:
lalpha, ralpha = rotate_wheels(lalpha, ralpha, L)
out += lalpha[0]
else:
ralpha, lalpha = rotate_wheels(ralpha, lalpha, L)
out += ralpha[0]
lalpha, ralpha = scramble_wheels(lalpha, ralpha)
if show:
print(lalpha, ralpha)
return out
def makealpha(key=""):
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
z = set()
key = [x.upper() for x in (key + alpha[::-1])
if not (x.upper() in z or z.add(x.upper()))]
return "".join(key)
def correct_case(string):
return "".join([s.upper() for s in string if s.isalpha()])
def permu(alp, num):
alp = alp[:num], alp[num:]
return "".join(alp[::-1])
def rotate_wheels(lalph, ralph, key):
newin = ralph.index(key)
return permu(lalph, newin), permu(ralph, newin)
def scramble_wheels(lalph, ralph):
# LEFT = cipher wheel
# Cycle second[1] through nadir[14] forward
lalph = list(lalph)
lalph = "".join([*lalph[0],
*lalph[2:14],
lalph[1],
*lalph[14:]])
# RIGHT = plain wheel
# Send the zenith[0] character to the end[25],
# cycle third[2] through nadir[14] characters forward
ralph = list(ralph)
ralph = "".join([*ralph[1:3],
*ralph[4:15],
ralph[3],
*ralph[15:],
ralph[0]])
return lalph, ralph
main() |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Kotlin | Kotlin | // version 1.1.2
import java.math.BigInteger
val ONE = BigInteger.ONE
fun pascal(n: Int, k: Int): BigInteger {
if (n == 0 || k == 0) return ONE
val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
return num / den
}
fun catalanFromPascal(n: Int) {
for (i in 1 until n step 2) {
val mi = i / 2 + 1
val catalan = pascal(i, mi) - pascal(i, mi - 2)
println("${"%2d".format(mi)} : $catalan")
}
}
fun main(args: Array<String>) {
val n = 15
catalanFromPascal(n * 2)
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #J | J | NB. These variables are all different
dog=: 'Benjamin'
Dog=: 'Samba'
DOG=: 'Bernie'
'The three dogs are named ',dog,', ',Dog,', and ',DOG
The three dogs are named Benjamin, Samba, and Bernie |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Java | Java | String dog = "Benjamin";
String Dog = "Samba"; //in general, identifiers that start with capital letters are class names
String DOG = "Bernie"; //in general, identifiers in all caps are constants
//the conventions listed in comments here are not enforced by the language
System.out.println("There are three dogs named " + dog + ", " + Dog + ", and " + DOG + "'"); |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Delphi | Delphi |
program Cartesian_product_of_two_or_more_lists;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TList = TArray<Integer>;
TLists = TArray<TList>;
TListHelper = record helper for TList
function ToString: string;
end;
TListsHelper = record helper for TLists
function ToString(BreakLines: boolean = false): string;
end;
function cartN(arg: TLists): TLists;
var
b, n: TList;
argc: Integer;
begin
argc := length(arg);
var c := 1;
for var a in arg do
c := c * length(a);
if c = 0 then
exit;
SetLength(result, c);
SetLength(b, c * argc);
SetLength(n, argc);
var s := 0;
for var i := 0 to c - 1 do
begin
var e := s + argc;
var Resi := copy(b, s, e - s);
Result[i] := Resi;
s := e;
for var j := 0 to high(n) do
begin
var nj := n[j];
Resi[j] := arg[j, nj];
end;
for var j := high(n) downto 0 do
begin
inc(n[j]);
if n[j] < Length(arg[j]) then
Break;
n[j] := 0;
end;
end;
end;
{ TListHelper }
function TListHelper.ToString: string;
begin
Result := '[';
for var i := 0 to High(self) do
begin
Result := Result + self[i].ToString;
if i < High(self) then
Result := Result + ' ';
end;
Result := Result + ']';
end;
{ TListsHelper }
function TListsHelper.ToString(BreakLines: boolean = false): string;
begin
Result := '[';
for var i := 0 to High(self) do
begin
Result := Result + self[i].ToString;
if i < High(self) then
begin
if BreakLines then
Result := Result + #10
else
Result := Result + ' ';
end;
end;
Result := Result + ']';
end;
begin
writeln(#10, cartN([[1, 2], [3, 4]]).ToString);
writeln(#10, cartN([[3, 4], [1, 2]]).ToString);
writeln(#10, cartN([[1, 2], []]).ToString);
writeln(#10, cartN([[], [1, 2]]).ToString);
writeln(#10, cartN([[1776, 1789], [17, 12], [4, 14, 23], [0, 1]]).ToString(True));
writeln(#10, cartN([[1, 2, 3], [30], [500, 100]]).ToString);
writeln(#10, cartN([[1, 2, 3], [], [500, 100]]).ToString);
{$IFNDEF UNIX} readln; {$ENDIF}
end. |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #AWK | AWK | # syntax: GAWK -f CATALAN_NUMBERS.AWK
BEGIN {
for (i=0; i<=15; i++) {
printf("%2d %10d\n",i,catalan(i))
}
exit(0)
}
function catalan(n, ans) {
if (n == 0) {
ans = 1
}
else {
ans = ((2*(2*n-1))/(n+1))*catalan(n-1)
}
return(ans)
} |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Ada | Ada | package My_Class is
type Object is tagged private;
procedure Primitive(Self: Object); -- primitive subprogram
procedure Dynamic(Self: Object'Class);
procedure Static;
private
type Object is tagged null record;
end My_Class; |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Apex | Apex | // Static
MyClass.method(someParameter);
// Instance
myInstance.method(someParameter); |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #ALGOL_W | ALGOL W | begin
% draw a Cantor Set using ASCII %
integer LINES; % number of lines for the set %
integer setWidth; % width of each line of the set %
% we must choose the line width so that the width of each segment is %
% divisible by 3 ( except for the final line where the segment width will %
% be 1 ) %
LINES := 5;
setWidth := round( 3 ** ( LINES - 1 ) );
begin % start new block so the array can have computed bounds %
logical array set ( 1 :: setWidth );
integer segmentWidth;
% start with a complete line %
for i := 1 until setWidth do set( i ) := true;
segmentWidth := setWidth;
for l := 1 until LINES do begin
% print the latest line, all lines start with a "#" %
write( "#" );
for i := 2 until setWidth do writeon( if set( i ) then "#" else " " );
% modify the line, replacing the middle third of each segment %
% with blanks, unless this was the last line %
if l < LINES then begin
integer setPos;
segmentWidth := segmentWidth div 3;
setPos := 1;
while setPos < ( setWidth - segmentWidth ) do begin
setPos := setPos + segmentWidth;
for charPos := setPos until ( setPos + segmentWidth ) - 1 do set( charPos ) := false;
setPos := setPos + segmentWidth
end while_setPos_in_range ;
end if_l_lt_LINES
end for_l
end
end. |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #AppleScript | AppleScript | ------------------------- CANTOR SET -----------------------
-- cantor :: [String] -> [String]
on cantor(xs)
script go
on |λ|(s)
set m to (length of s) div 3
set blocks to text 1 thru m of s
if "█" = text 1 of s then
{blocks, replicate(m, space), blocks}
else
{s}
end if
end |λ|
end script
concatMap(go, xs)
end cantor
---------------------------- TEST --------------------------
on run
showCantor(5)
end run
-- showCantor :: Int -> String
on showCantor(n)
unlines(map(my concat, ¬
take(n, iterate(cantor, ¬
{replicate(3 ^ (n - 1), "█")}))))
end showCantor
--------------------- GENERIC FUNCTIONS --------------------
-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
set lng to length of xs
if 0 < lng and string is class of (item 1 of xs) then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to lng
set acc to acc & item i of xs
end repeat
acc
end concat
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & |λ|(item i of xs, i, xs)
end repeat
end tell
return acc
end concatMap
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- iterate :: (a -> a) -> a -> Gen [a]
on iterate(f, x)
script
property v : missing value
property g : mReturn(f)'s |λ|
on |λ|()
if missing value is v then
set v to x
else
set v to g(v)
end if
return v
end |λ|
end script
end iterate
-- replicate :: Int -> String -> String
on replicate(n, s)
set out to ""
if n < 1 then return out
set dbl to s
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to xs's |λ|()
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- unlines :: [String] -> String
on unlines(xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set str to xs as text
set my text item delimiters to dlm
str
end unlines |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #J | J | NB. 2D convolution, filtering, ...
convolve =: 4 : 'x apply (($x) partition y)'
partition=: 2 1 3 0 |: {:@[ ]\ 2 1 0 |: {.@[ ]\ ]
apply=: [: +/ [: +/ *
max3x3 =: 3 : '(0<1{1{y) * (>./>./y)'
addborder =: (0&,@|:@|.)^:4
normalize =: ]%+/@,
attach =: 3 : 'max3x3 (3 3 partition (addborder y))'
unique =: 3 : 'y*i.$y'
connect =: 3 : 'attach^:_ unique y'
NB. on low memory devices, cropping or resampling of high-resolution images may be required
crop =: 4 : 0
'h w h0 w0' =: x
|: w{. w0}. |: h{. h0}. y
)
resample =: 4 : '|: (1{-x)(+/%#)\ |: (0{-x)(+/%#)\ y'
NB. on e. g. smartphones, image may need to be expanded for viewing
inflate1 =: 4 : 0
'h w' =: $y
r =: ,y
c =: #r
rr =: (c$x) # r
(h,x*w)$rr
)
inflate =: 4 : '|: x inflate1 (|: x inflate1 y)'
NB. Step 1 - gaussian smoothing
step1 =: 3 : 0
NB. Gaussian kernel (from Wikipedia article)
<] gaussianKernel =: 5 5$2 4 5 4 2 4 9 12 9 4 5 12 15 12 5 4 9 12 9 4 2 4 5 4 2
gaussianKernel =: gaussianKernel % 159
gaussianKernel convolve y
)
NB. Step 2 - gradient
step2 =: 3 : 0
<] gradientKernel =: 3 3$0 _1 0 0j_1 0 0j1 0 1 0
gradientKernel convolve y
)
NB. Step 3 - edge detection
step3 =: 3 : 0
NB. find the octant (eighth of circle) in which the gradient lies
octant =: 3 : '4|(>.(_0.5+((4%(o. 1))*(12&o. y))))'
<(i:6)(4 : 'octant (x j. y)')"0/(i:6)
NB. is this gradient greater than [the projection of] a neighbor?
greaterThan =: 4 : ' (9 o.((x|.y)%y))<1'
NB. is this gradient the greatest of immmediate colinear neighbore?
greatestOf =: 4 : '(x greaterThan y) *. ((-x) greaterThan y)'
NB. relative address of neighbor relevant to grad direction
krnl0 =. _1 0
krnl1 =. _1 _1
krnl2 =. 0 _1
krnl3 =. 1 _1
image =. y
og =. octant image
NB. mask for maximum gradient colinear with gradient
ok0 =. (0=og) *. krnl0 greatestOf image
ok1 =. (1=og) *. krnl1 greatestOf image
ok2 =. (2=og) *. krnl2 greatestOf image
ok3 =. (3=og) *. krnl3 greatestOf image
image *. (ok0 +. ok1 +. ok2 +. ok3)
)
NB. Step 4 - Weak edge suppression
step4 =: 3 : 0
magnitude =. 10&o. y
NB. weak, strong threshholds
NB. TODO: parameter picker algorithm or helper
threshholds =. 1e14 1e15
nearbyKernel =. 3 3 $ 4 1 4 # 1 0 1
weak =. magnitude > 0{threshholds
strong =. magnitude > 1{threshholds
strongs =. addborder (nearbyKernel convolve strong) > 0
strong +. (weak *. strongs)
)
NB. given the edge points, find the edges
step5 =: connect
canny =: step5 @ step4 @ step3 @ step2 @ step1
|
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #Common_Lisp | Common Lisp | (defun ip->bit-vector (ip)
(flet ((int->bits (int)
(loop :for i :below 8
:collect (if (logbitp i int) 1 0) :into bits
:finally (return (nreverse bits)))))
(loop :repeat 4
:with start := 0
:for pos := (position #\. ip :start start)
:collect (parse-integer ip :start start :end pos) :into res
:while pos
:do (setf start (1+ pos))
:finally (return (apply #'concatenate 'bit-vector (mapcar #'int->bits res))))))
(defun bit-vector->ip (vec &optional n)
(loop :repeat 4
:for end :from 8 :by 8
:for start := (- end 8)
:for sub := (subseq vec start end)
:collect (parse-integer (map 'string #'digit-char sub) :radix 2) :into res
:finally (return (format nil "~{~D~^.~}~@[/~A~]" res n))))
(defun canonicalize-cidr (cidr)
(let* ((n (position #\/ cidr))
(ip (subseq cidr 0 n))
(sn (parse-integer cidr :start (1+ n)))
(ip* (ip->bit-vector ip))
(canonical-ip (fill ip* 0 :start sn)))
(bit-vector->ip canonical-ip sn)))
(loop :for cidr :in '("36.18.154.103/12" "62.62.197.11/29"
"67.137.119.181/4" "161.214.74.21/24"
"184.232.176.184/18")
:for ccidr := (canonicalize-cidr cidr)
:do (format t "~&~A~20,T→ ~A~%" cidr ccidr))
|
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #Free_Pascal | Free Pascal | program castout9;
{$ifdef fpc}{$mode delphi}{$endif}
uses generics.collections;
type
TIntegerList = TSortedList<integer>;
procedure co9(const start,base,lim:integer;kaprekars:array of integer);
var
C1:integer = 0;
C2:integer = 0;
S:TIntegerlist;
k,i:integer;
begin
S:=TIntegerlist.Create;
for k := start to lim do
begin
inc(C1);
if k mod (base-1) = (k*k) mod (base-1) then
begin
inc(C2);
S.Add(k);
end;
end;
writeln('Valid subset: ');
for i in Kaprekars do
if not s.contains(i) then
writeln('invalid ',i);
for i in s do write(i:4);
writeln;
write('The Kaprekars in this range [');
for i in kaprekars do write(i:4);
writeln('] are included');
writeln('Trying ',C2, ' numbers instead of ', C1,' saves ',100-(C2 * 100 /C1):3:2,',%.');
writeln;
S.Free;
end;
begin
co9(1, 10, 99, [1,9,45,55,99]);
co9(1, 10, 1000, [1,9,45,55,99,297,703,999]);
end. |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Phix | Phix | -- demo\rosetta\Catmull_Clark_subdivision_surface.exw
with javascript_semantics
function newPoint() return {0,0,0} end function
function newPointEx() return {newPoint(),0} end function
function centerPoint(sequence p1, p2)
return sq_div(sq_add(p1, p2), 2)
end function
function getFacePoints(sequence inputPoints, inputFaces)
sequence facePoints = repeat(0,length(inputFaces))
for f=1 to length(inputFaces) do
sequence currFace = inputFaces[f],
facePoint = inputPoints[currFace[1]]
for i=2 to length(currFace) do
facePoint = sq_add(facePoint, inputPoints[currFace[i]])
end for
facePoints[f] = sq_div(facePoint, length(currFace))
end for
return facePoints
end function
function getEdgesFaces(sequence inputPoints, inputFaces)
sequence edges = {}
for faceNum=1 to length(inputFaces) do
sequence face = inputFaces[faceNum]
integer numPoints = length(face)
for pointIndex=1 to numPoints do
integer pointNum1 = face[pointIndex],
pointNum2 = face[iff(pointIndex<=numPoints-1?pointIndex+1:1)]
if pointNum1 > pointNum2 then
{pointNum1, pointNum2} = {pointNum2, pointNum1}
end if
edges = append(edges, {pointNum1, pointNum2, faceNum})
end for
end for
edges = sort(edges)
integer numEdges = length(edges),
eIndex = 1
sequence mergedEdges ={}
while eIndex<=numEdges do
sequence e1 = deep_copy(edges[eIndex])
integer e4 = -1
if eIndex<=numEdges-1
and e1[1..2]==edges[eIndex+1][1..2] then
e4 = deep_copy(edges[eIndex+1][3])
eIndex += 1
end if
e1 &= e4
mergedEdges = append(mergedEdges, e1)
eIndex += 1
end while
sequence edgesCenters = {}
for i=1 to length(mergedEdges) do
sequence me = deep_copy(mergedEdges[i]),
cp = centerPoint(inputPoints[me[1]],
inputPoints[me[2]])
me = append(me,cp)
edgesCenters = append(edgesCenters, me)
end for
return edgesCenters
end function
function getEdgePoints(sequence inputPoints, edgesFaces, facePoints)
sequence edgePoints = repeat(0, length(edgesFaces))
for i=1 to length(edgesFaces) do
sequence edge = edgesFaces[i],
cp = edge[5],
fp1 = facePoints[edge[3]],
fp2 = iff(edge[4]=-1?fp1:facePoints[edge[4]]),
cfp = centerPoint(fp1, fp2)
edgePoints[i] = centerPoint(cp, cfp)
end for
return edgePoints
end function
function getAvgFacePoints(sequence inputPoints, inputFaces, facePoints)
integer numPoints = length(inputPoints)
sequence tempPoints = repeat(newPointEx(),numPoints)
for faceNum=1 to length(inputFaces) do
sequence fp = facePoints[faceNum]
for i=1 to length(inputFaces[faceNum]) do
integer pointNum = inputFaces[faceNum][i]
sequence tp = tempPoints[pointNum][1]
tempPoints[pointNum][1] = sq_add(tp, fp)
tempPoints[pointNum][2] += 1
end for
end for
sequence avgFacePoints = repeat(0, numPoints)
for i=1 to length(tempPoints) do
sequence tp = tempPoints[i]
avgFacePoints[i] = sq_div(tp[1], tp[2])
end for
return avgFacePoints
end function
function getAvgMidEdges(sequence inputPoints, edgesFaces)
integer numPoints = length(inputPoints)
sequence tempPoints = repeat(newPointEx(), numPoints)
for i=1 to length(edgesFaces) do
sequence edge = edgesFaces[i],
cp = edge[5]
for edx=1 to 2 do
integer pointNum = edge[edx]
sequence tp = tempPoints[pointNum][1]
tempPoints[pointNum][1] = sq_add(tp, cp)
tempPoints[pointNum][2] += 1
end for
end for
sequence avgMidEdges = repeat(0, length(tempPoints))
for i=1 to length(tempPoints) do
sequence tp = tempPoints[i]
avgMidEdges[i] = sq_div(tp[1], tp[2])
end for
return avgMidEdges
end function
function getPointsFaces(sequence inputPoints, inputFaces)
integer numPoints = length(inputPoints)
sequence pointsFaces = repeat(0, numPoints)
for faceNum=1 to length(inputFaces) do
for i=1 to length(inputFaces[faceNum]) do
integer pointNum = inputFaces[faceNum][i]
pointsFaces[pointNum] += 1
end for
end for
return pointsFaces
end function
function getNewPoints(sequence inputPoints, pointsFaces, avgFacePoints, avgMidEdges)
sequence newPoints = repeat(0, length(inputPoints))
for pointNum=1 to length(inputPoints) do
integer n = pointsFaces[pointNum]
sequence p1 = sq_mul(inputPoints[pointNum], (n-3)/n),
p2 = sq_mul(avgFacePoints[pointNum], 1/n),
p3 = sq_mul(avgMidEdges[pointNum], 2/n)
newPoints[pointNum] = sq_add(sq_add(p1, p2), p3)
end for
return newPoints
end function
function switchNums(sequence pointNums)
if pointNums[1] < pointNums[2] then
return pointNums
end if
return {pointNums[2], pointNums[1]}
end function
function cmcSubdiv(sequence inputPoints, inputFaces)
sequence facePoints = getFacePoints(inputPoints, inputFaces),
edgesFaces = getEdgesFaces(inputPoints, inputFaces),
edgePoints = getEdgePoints(inputPoints, edgesFaces, facePoints),
avgFacePoints = getAvgFacePoints(inputPoints, inputFaces, facePoints),
avgMidEdges = getAvgMidEdges(inputPoints, edgesFaces),
pointsFaces = getPointsFaces(inputPoints, inputFaces),
newPoints = getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges),
facePointNums = {}
integer nextPointNum = length(newPoints)+1
for i=1 to length(facePoints) do
sequence facePoint = facePoints[i]
newPoints = append(newPoints, facePoint)
facePointNums = append(facePointNums, nextPointNum)
nextPointNum += 1
end for
integer edgePointNums = new_dict()
for edgeNum=1 to length(edgesFaces) do
integer {pointNum1,pointNum2} = edgesFaces[edgeNum]
sequence edgePoint = edgePoints[edgeNum]
newPoints = append(newPoints, edgePoint)
setd({pointNum1, pointNum2},nextPointNum,edgePointNums)
nextPointNum += 1
end for
sequence newFaces = {}
for oldFaceNum=1 to length(inputFaces) do
sequence oldFace = inputFaces[oldFaceNum]
if length(oldFace) == 4 then
integer {a, b, c, d} := oldFace,
facePointAbcd := facePointNums[oldFaceNum],
edgePointAb := getd(switchNums({a, b}),edgePointNums),
edgePointDa := getd(switchNums({d, a}),edgePointNums),
edgePointBc := getd(switchNums({b, c}),edgePointNums),
edgePointCd := getd(switchNums({c, d}),edgePointNums)
newFaces = append(newFaces, {a, edgePointAb, facePointAbcd, edgePointDa})
newFaces = append(newFaces, {b, edgePointBc, facePointAbcd, edgePointAb})
newFaces = append(newFaces, {c, edgePointCd, facePointAbcd, edgePointBc})
newFaces = append(newFaces, {d, edgePointDa, facePointAbcd, edgePointCd})
end if
end for
return {newPoints, newFaces}
end function
constant inputPoints = {{-1, 1, 1},
{-1,-1, 1},
{ 1,-1, 1},
{ 1, 1, 1},
{ 1,-1,-1},
{ 1, 1,-1},
{-1,-1,-1},
{-1, 1,-1}},
inputFaces = {{0, 1, 2, 3},
{3, 2, 4, 5},
{5, 4, 6, 7},
{7, 0, 3, 5},
{7, 6, 1, 0},
{6, 1, 2, 4}}
sequence outputPoints = inputPoints,
outputFaces = sq_add(inputFaces,1)
integer iterations = 1
for i=1 to iterations do
{outputPoints, outputFaces} = cmcSubdiv(outputPoints, outputFaces)
end for
ppOpt({pp_Nest,1,pp_FltFmt,"%7.4f",pp_IntFmt,"%7.4f",pp_IntCh,false})
pp(outputPoints)
pp(sq_sub(outputFaces,1),{pp_IntFmt,"%2d"})
|
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #D | D | enum mod = (in int n, in int m) pure nothrow @nogc=> ((n % m) + m) % m;
bool isPrime(in uint n) pure nothrow @nogc {
if (n == 2 || n == 3)
return true;
else if (n < 2 || n % 2 == 0 || n % 3 == 0)
return false;
for (uint div = 5, inc = 2; div ^^ 2 <= n;
div += inc, inc = 6 - inc)
if (n % div == 0)
return false;
return true;
}
void main() {
import std.stdio;
foreach (immutable p; 2 .. 62) {
if (!p.isPrime) continue;
foreach (immutable h3; 2 .. p) {
immutable g = h3 + p;
foreach (immutable d; 1 .. g) {
if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3)
continue;
immutable q = 1 + (p - 1) * g / d;
if (!q.isPrime) continue;
immutable r = 1 + (p * q / h3);
if (!r.isPrime || (q * r) % (p - 1) != 1) continue;
writeln(p, " x ", q, " x ", r);
}
}
}
} |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #DCL | DCL | $ list = "1,2,3,4,5"
$ call reduce list "+"
$ show symbol result
$
$ numbers = "5,4,3,2,1"
$ call reduce numbers "-"
$ show symbol result
$
$ call reduce list "*"
$ show symbol result
$ exit
$
$ reduce: subroutine
$ local_list = 'p1
$ value = f$integer( f$element( 0, ",", local_list ))
$ i = 1
$ loop:
$ element = f$element( i, ",", local_list )
$ if element .eqs. "," then $ goto done
$ value = value 'p2 f$integer( element )
$ i = i + 1
$ goto loop
$ done:
$ result == value
$ exit
$ endsubroutine |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Raku | Raku | my @left;
my @right;
sub reset {
@left = <HXUCZVAMDSLKPEFJRIGTWOBNYQ>.comb;
@right = <PTLNBQDEOYSFAVZKGJRIHWXUMC>.comb;
}
sub encode ($letter) {
my $index = @right.first: $letter.uc, :k;
my $enc = @left[$index];
$index.&permute;
$enc
}
sub decode ($letter) {
my $index = @left.first: $letter.uc, :k;
my $dec = @right[$index];
$index.&permute;
$dec
}
sub permute ($index) {
@left.=rotate: $index;
@left[1..13].=rotate;
@right.=rotate: $index + 1;
@right[2..13].=rotate;
}
reset;
say 'WELLDONEISBETTERTHANWELLSAID'.comb».&encode.join;
reset;
say 'OAHQHCNYNXTSZJRRHJBYHQKSOUJY'.comb».&decode.join; |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Lua | Lua | function nextrow (t)
local ret = {}
t[0], t[#t + 1] = 0, 0
for i = 1, #t do ret[i] = t[i - 1] + t[i] end
return ret
end
function catalans (n)
local t, middle = {1}
for i = 1, n do
middle = math.ceil(#t / 2)
io.write(t[middle] - (t[middle + 1] or 0) .. " ")
t = nextrow(nextrow(t))
end
end
catalans(15) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #JavaScript | JavaScript | var dog = "Benjamin";
var Dog = "Samba";
var DOG = "Bernie";
document.write("The three dogs are named " + dog + ", " + Dog + ", and " + DOG + "."); |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #jq | jq | def task(dog; Dog; DOG):
"The three dogs are named \(dog), \(Dog), and \(DOG)." ;
task("Benjamin"; "Samba"; "Bernie") |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #F.23 | F# |
//Nigel Galloway February 12th., 2018
let cP2 n g = List.map (fun (n,g)->[n;g]) (List.allPairs n g)
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #BASIC | BASIC | DECLARE FUNCTION catalan (n AS INTEGER) AS SINGLE
REDIM SHARED results(0) AS SINGLE
FOR x% = 1 TO 15
PRINT x%, catalan (x%)
NEXT
FUNCTION catalan (n AS INTEGER) AS SINGLE
IF UBOUND(results) < n THEN REDIM PRESERVE results(n)
IF 0 = n THEN
results(0) = 1
ELSE
results(n) = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1)
END IF
catalan = results(n)
END FUNCTION |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #AutoHotkey | AutoHotkey | class myClass
{
Method(someParameter){
MsgBox % SomeParameter
}
}
myClass.method("hi")
myInstance := new myClass
myInstance.Method("bye") |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Bracmat | Bracmat | ( ( myClass
= (name=aClass)
( Method
= .out$(str$("Output from " !(its.name) ": " !arg))
)
(new=.!arg:?(its.name))
)
& (myClass.Method)$"Example of calling a 'class' method"
& new$(myClass,object1):?MyObject
& (MyObject..Method)$"Example of calling an instance method"
& !MyObject:?Alias
& (Alias..Method)$"Example of calling an instance method from an alias"
); |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #C | C |
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int x;
int (*funcPtr)(int);
}functionPair;
int factorial(int num){
if(num==0||num==1)
return 1;
else
return num*factorial(num-1);
}
int main(int argc,char** argv)
{
functionPair response;
if(argc!=2)
return printf("Usage : %s <non negative integer>",argv[0]);
else{
response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
}
return 0;
}
|
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
with Interfaces.C; use Interfaces.C;
with System; use System;
with Ada.Unchecked_Conversion;
procedure Shared_Library_Call is
--
-- Interface to kernel32.dll which is responsible for loading DLLs under Windows.
-- There are ready to use Win32 bindings. We don't want to use them here.
--
type HANDLE is new Unsigned_32; -- on x64 system, replace by Unsigned_64 to make it work
function LoadLibrary (lpFileName : char_array) return HANDLE;
pragma Import (stdcall, LoadLibrary, "LoadLibrary", "_LoadLibraryA"); -- Ada95 does not have the @n suffix.
function GetProcAddress (hModule : HANDLE; lpProcName : char_array)
return Address;
pragma Import (stdcall, GetProcAddress, "GetProcAddress", "_GetProcAddress"); --
--
-- The interface of the function we want to call. It is a pointer (access type)
-- because we will link it dynamically. The function is from User32.dll
--
type MessageBox is access function
( hWnd : Address := Null_Address;
lpText : char_array;
lpCaption : char_array := To_C ("Greeting");
uType : Unsigned_16 := 0
) return Integer_16;
pragma Convention (Stdcall, MessageBox);
function To_MessageBox is new Ada.Unchecked_Conversion (Address, MessageBox);
Library : HANDLE := LoadLibrary (To_C ("user32.dll"));
Pointer : Address := GetProcAddress (Library, To_C ("MessageBoxA"));
begin
if Pointer /= Null_Address then
declare
Result : Integer_16;
begin
Result := To_MessageBox (Pointer) (lpText => To_C ("Hello!"));
end;
else
Put_Line ("Unable to load the library " & HANDLE'Image (Library));
end if;
end Shared_Library_Call; |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Arturo | Arturo | width: 81
height: 5
lines: array.of: height repeat `*` width
cantor: function [start length idx].export:[lines][
seg: length / 3
if seg = 0 -> return null
loop idx..dec height 'i [
loop (start + seg).. dec start + 2 * seg 'j
-> set lines\[i] j ` `
]
cantor start seg idx+1
cantor start + 2 * seg seg idx+1
]
cantor 0 width 1
loop lines 'line
-> print join line |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to use a rational number data type.
It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.
It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:
[a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1]
Example
The fraction 9/4 has odd continued fraction representation 2; 3, 1, giving a binary representation of 100011,
which means 9/4 appears as the 35th term of the sequence.
Task part 2
Find the position of the number 83116/51639 in the Calkin-Wilf sequence.
See also
Wikipedia entry: Calkin-Wilf tree
Continued fraction
Continued fraction/Arithmetic/Construct from rational number
| #11l | 11l | T CalkinWilf
n = 1
d = 1
F ()()
V r = (.n, .d)
.n = 2 * (.n I/ .d) * .d + .d - .n
swap(&.n, &.d)
R r
print(‘The first 20 terms of the Calkwin-Wilf sequence are:’)
V cw = CalkinWilf()
[String] seq
L 20
V (n, d) = cw()
seq.append(I d == 1 {String(n)} E n‘/’d)
print(seq.join(‘, ’))
cw = CalkinWilf()
V index = 1
L cw() != (83116, 51639)
index++
print("\nThe element 83116/51639 is at position "index‘ in the sequence.’) |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #Java | Java | import java.awt.image.BufferedImage;
import java.util.Arrays;
/**
* <p><em>This software has been released into the public domain.
* <strong>Please read the notes in this source file for additional information.
* </strong></em></p>
*
* <p>This class provides a configurable implementation of the Canny edge
* detection algorithm. This classic algorithm has a number of shortcomings,
* but remains an effective tool in many scenarios. <em>This class is designed
* for single threaded use only.</em></p>
*
* <p>Sample usage:</p>
*
* <pre><code>
* //create the detector
* CannyEdgeDetector detector = new CannyEdgeDetector();
* //adjust its parameters as desired
* detector.setLowThreshold(0.5f);
* detector.setHighThreshold(1f);
* //apply it to an image
* detector.setSourceImage(frame);
* detector.process();
* BufferedImage edges = detector.getEdgesImage();
* </code></pre>
*
* <p>For a more complete understanding of this edge detector's parameters
* consult an explanation of the algorithm.</p>
*
* @author Tom Gibara
*
*/
public class CannyEdgeDetector {
// statics
private final static float GAUSSIAN_CUT_OFF = 0.005f;
private final static float MAGNITUDE_SCALE = 100F;
private final static float MAGNITUDE_LIMIT = 1000F;
private final static int MAGNITUDE_MAX = (int) (MAGNITUDE_SCALE * MAGNITUDE_LIMIT);
// fields
private int height;
private int width;
private int picsize;
private int[] data;
private int[] magnitude;
private BufferedImage sourceImage;
private BufferedImage edgesImage;
private float gaussianKernelRadius;
private float lowThreshold;
private float highThreshold;
private int gaussianKernelWidth;
private boolean contrastNormalized;
private float[] xConv;
private float[] yConv;
private float[] xGradient;
private float[] yGradient;
// constructors
/**
* Constructs a new detector with default parameters.
*/
public CannyEdgeDetector() {
lowThreshold = 2.5f;
highThreshold = 7.5f;
gaussianKernelRadius = 2f;
gaussianKernelWidth = 16;
contrastNormalized = false;
}
// accessors
/**
* The image that provides the luminance data used by this detector to
* generate edges.
*
* @return the source image, or null
*/
public BufferedImage getSourceImage() {
return sourceImage;
}
/**
* Specifies the image that will provide the luminance data in which edges
* will be detected. A source image must be set before the process method
* is called.
*
* @param image a source of luminance data
*/
public void setSourceImage(BufferedImage image) {
sourceImage = image;
}
/**
* Obtains an image containing the edges detected during the last call to
* the process method. The buffered image is an opaque image of type
* BufferedImage.TYPE_INT_ARGB in which edge pixels are white and all other
* pixels are black.
*
* @return an image containing the detected edges, or null if the process
* method has not yet been called.
*/
public BufferedImage getEdgesImage() {
return edgesImage;
}
/**
* Sets the edges image. Calling this method will not change the operation
* of the edge detector in any way. It is intended to provide a means by
* which the memory referenced by the detector object may be reduced.
*
* @param edgesImage expected (though not required) to be null
*/
public void setEdgesImage(BufferedImage edgesImage) {
this.edgesImage = edgesImage;
}
/**
* The low threshold for hysteresis. The default value is 2.5.
*
* @return the low hysteresis threshold
*/
public float getLowThreshold() {
return lowThreshold;
}
/**
* Sets the low threshold for hysteresis. Suitable values for this parameter
* must be determined experimentally for each application. It is nonsensical
* (though not prohibited) for this value to exceed the high threshold value.
*
* @param threshold a low hysteresis threshold
*/
public void setLowThreshold(float threshold) {
if (threshold < 0) throw new IllegalArgumentException();
lowThreshold = threshold;
}
/**
* The high threshold for hysteresis. The default value is 7.5.
*
* @return the high hysteresis threshold
*/
public float getHighThreshold() {
return highThreshold;
}
/**
* Sets the high threshold for hysteresis. Suitable values for this
* parameter must be determined experimentally for each application. It is
* nonsensical (though not prohibited) for this value to be less than the
* low threshold value.
*
* @param threshold a high hysteresis threshold
*/
public void setHighThreshold(float threshold) {
if (threshold < 0) throw new IllegalArgumentException();
highThreshold = threshold;
}
/**
* The number of pixels across which the Gaussian kernel is applied.
* The default value is 16.
*
* @return the radius of the convolution operation in pixels
*/
public int getGaussianKernelWidth() {
return gaussianKernelWidth;
}
/**
* The number of pixels across which the Gaussian kernel is applied.
* This implementation will reduce the radius if the contribution of pixel
* values is deemed negligable, so this is actually a maximum radius.
*
* @param gaussianKernelWidth a radius for the convolution operation in
* pixels, at least 2.
*/
public void setGaussianKernelWidth(int gaussianKernelWidth) {
if (gaussianKernelWidth < 2) throw new IllegalArgumentException();
this.gaussianKernelWidth = gaussianKernelWidth;
}
/**
* The radius of the Gaussian convolution kernel used to smooth the source
* image prior to gradient calculation. The default value is 16.
*
* @return the Gaussian kernel radius in pixels
*/
public float getGaussianKernelRadius() {
return gaussianKernelRadius;
}
/**
* Sets the radius of the Gaussian convolution kernel used to smooth the
* source image prior to gradient calculation.
*
* @return a Gaussian kernel radius in pixels, must exceed 0.1f.
*/
public void setGaussianKernelRadius(float gaussianKernelRadius) {
if (gaussianKernelRadius < 0.1f) throw new IllegalArgumentException();
this.gaussianKernelRadius = gaussianKernelRadius;
}
/**
* Whether the luminance data extracted from the source image is normalized
* by linearizing its histogram prior to edge extraction. The default value
* is false.
*
* @return whether the contrast is normalized
*/
public boolean isContrastNormalized() {
return contrastNormalized;
}
/**
* Sets whether the contrast is normalized
* @param contrastNormalized true if the contrast should be normalized,
* false otherwise
*/
public void setContrastNormalized(boolean contrastNormalized) {
this.contrastNormalized = contrastNormalized;
}
// methods
public void process() {
width = sourceImage.getWidth();
height = sourceImage.getHeight();
picsize = width * height;
initArrays();
readLuminance();
if (contrastNormalized) normalizeContrast();
computeGradients(gaussianKernelRadius, gaussianKernelWidth);
int low = Math.round(lowThreshold * MAGNITUDE_SCALE);
int high = Math.round( highThreshold * MAGNITUDE_SCALE);
performHysteresis(low, high);
thresholdEdges();
writeEdges(data);
}
// private utility methods
private void initArrays() {
if (data == null || picsize != data.length) {
data = new int[picsize];
magnitude = new int[picsize];
xConv = new float[picsize];
yConv = new float[picsize];
xGradient = new float[picsize];
yGradient = new float[picsize];
}
}
//NOTE: The elements of the method below (specifically the technique for
//non-maximal suppression and the technique for gradient computation)
//are derived from an implementation posted in the following forum (with the
//clear intent of others using the code):
// http://forum.java.sun.com/thread.jspa?threadID=546211&start=45&tstart=0
//My code effectively mimics the algorithm exhibited above.
//Since I don't know the providence of the code that was posted it is a
//possibility (though I think a very remote one) that this code violates
//someone's intellectual property rights. If this concerns you feel free to
//contact me for an alternative, though less efficient, implementation.
private void computeGradients(float kernelRadius, int kernelWidth) {
//generate the gaussian convolution masks
float kernel[] = new float[kernelWidth];
float diffKernel[] = new float[kernelWidth];
int kwidth;
for (kwidth = 0; kwidth < kernelWidth; kwidth++) {
float g1 = gaussian(kwidth, kernelRadius);
if (g1 <= GAUSSIAN_CUT_OFF && kwidth >= 2) break;
float g2 = gaussian(kwidth - 0.5f, kernelRadius);
float g3 = gaussian(kwidth + 0.5f, kernelRadius);
kernel[kwidth] = (g1 + g2 + g3) / 3f / (2f * (float) Math.PI * kernelRadius * kernelRadius);
diffKernel[kwidth] = g3 - g2;
}
int initX = kwidth - 1;
int maxX = width - (kwidth - 1);
int initY = width * (kwidth - 1);
int maxY = width * (height - (kwidth - 1));
//perform convolution in x and y directions
for (int x = initX; x < maxX; x++) {
for (int y = initY; y < maxY; y += width) {
int index = x + y;
float sumX = data[index] * kernel[0];
float sumY = sumX;
int xOffset = 1;
int yOffset = width;
for(; xOffset < kwidth ;) {
sumY += kernel[xOffset] * (data[index - yOffset] + data[index + yOffset]);
sumX += kernel[xOffset] * (data[index - xOffset] + data[index + xOffset]);
yOffset += width;
xOffset++;
}
yConv[index] = sumY;
xConv[index] = sumX;
}
}
for (int x = initX; x < maxX; x++) {
for (int y = initY; y < maxY; y += width) {
float sum = 0f;
int index = x + y;
for (int i = 1; i < kwidth; i++)
sum += diffKernel[i] * (yConv[index - i] - yConv[index + i]);
xGradient[index] = sum;
}
}
for (int x = kwidth; x < width - kwidth; x++) {
for (int y = initY; y < maxY; y += width) {
float sum = 0.0f;
int index = x + y;
int yOffset = width;
for (int i = 1; i < kwidth; i++) {
sum += diffKernel[i] * (xConv[index - yOffset] - xConv[index + yOffset]);
yOffset += width;
}
yGradient[index] = sum;
}
}
initX = kwidth;
maxX = width - kwidth;
initY = width * kwidth;
maxY = width * (height - kwidth);
for (int x = initX; x < maxX; x++) {
for (int y = initY; y < maxY; y += width) {
int index = x + y;
int indexN = index - width;
int indexS = index + width;
int indexW = index - 1;
int indexE = index + 1;
int indexNW = indexN - 1;
int indexNE = indexN + 1;
int indexSW = indexS - 1;
int indexSE = indexS + 1;
float xGrad = xGradient[index];
float yGrad = yGradient[index];
float gradMag = hypot(xGrad, yGrad);
//perform non-maximal supression
float nMag = hypot(xGradient[indexN], yGradient[indexN]);
float sMag = hypot(xGradient[indexS], yGradient[indexS]);
float wMag = hypot(xGradient[indexW], yGradient[indexW]);
float eMag = hypot(xGradient[indexE], yGradient[indexE]);
float neMag = hypot(xGradient[indexNE], yGradient[indexNE]);
float seMag = hypot(xGradient[indexSE], yGradient[indexSE]);
float swMag = hypot(xGradient[indexSW], yGradient[indexSW]);
float nwMag = hypot(xGradient[indexNW], yGradient[indexNW]);
float tmp;
/*
* An explanation of what's happening here, for those who want
* to understand the source: This performs the "non-maximal
* supression" phase of the Canny edge detection in which we
* need to compare the gradient magnitude to that in the
* direction of the gradient; only if the value is a local
* maximum do we consider the point as an edge candidate.
*
* We need to break the comparison into a number of different
* cases depending on the gradient direction so that the
* appropriate values can be used. To avoid computing the
* gradient direction, we use two simple comparisons: first we
* check that the partial derivatives have the same sign (1)
* and then we check which is larger (2). As a consequence, we
* have reduced the problem to one of four identical cases that
* each test the central gradient magnitude against the values at
* two points with 'identical support'; what this means is that
* the geometry required to accurately interpolate the magnitude
* of gradient function at those points has an identical
* geometry (upto right-angled-rotation/reflection).
*
* When comparing the central gradient to the two interpolated
* values, we avoid performing any divisions by multiplying both
* sides of each inequality by the greater of the two partial
* derivatives. The common comparand is stored in a temporary
* variable (3) and reused in the mirror case (4).
*
*/
if (xGrad * yGrad <= (float) 0 /*(1)*/
? Math.abs(xGrad) >= Math.abs(yGrad) /*(2)*/
? (tmp = Math.abs(xGrad * gradMag)) >= Math.abs(yGrad * neMag - (xGrad + yGrad) * eMag) /*(3)*/
&& tmp > Math.abs(yGrad * swMag - (xGrad + yGrad) * wMag) /*(4)*/
: (tmp = Math.abs(yGrad * gradMag)) >= Math.abs(xGrad * neMag - (yGrad + xGrad) * nMag) /*(3)*/
&& tmp > Math.abs(xGrad * swMag - (yGrad + xGrad) * sMag) /*(4)*/
: Math.abs(xGrad) >= Math.abs(yGrad) /*(2)*/
? (tmp = Math.abs(xGrad * gradMag)) >= Math.abs(yGrad * seMag + (xGrad - yGrad) * eMag) /*(3)*/
&& tmp > Math.abs(yGrad * nwMag + (xGrad - yGrad) * wMag) /*(4)*/
: (tmp = Math.abs(yGrad * gradMag)) >= Math.abs(xGrad * seMag + (yGrad - xGrad) * sMag) /*(3)*/
&& tmp > Math.abs(xGrad * nwMag + (yGrad - xGrad) * nMag) /*(4)*/
) {
magnitude[index] = gradMag >= MAGNITUDE_LIMIT ? MAGNITUDE_MAX : (int) (MAGNITUDE_SCALE * gradMag);
//NOTE: The orientation of the edge is not employed by this
//implementation. It is a simple matter to compute it at
//this point as: Math.atan2(yGrad, xGrad);
} else {
magnitude[index] = 0;
}
}
}
}
//NOTE: It is quite feasible to replace the implementation of this method
//with one which only loosely approximates the hypot function. I've tested
//simple approximations such as Math.abs(x) + Math.abs(y) and they work fine.
private float hypot(float x, float y) {
return (float) Math.hypot(x, y);
}
private float gaussian(float x, float sigma) {
return (float) Math.exp(-(x * x) / (2f * sigma * sigma));
}
private void performHysteresis(int low, int high) {
//NOTE: this implementation reuses the data array to store both
//luminance data from the image, and edge intensity from the processing.
//This is done for memory efficiency, other implementations may wish
//to separate these functions.
Arrays.fill(data, 0);
int offset = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (data[offset] == 0 && magnitude[offset] >= high) {
follow(x, y, offset, low);
}
offset++;
}
}
}
private void follow(int x1, int y1, int i1, int threshold) {
int x0 = x1 == 0 ? x1 : x1 - 1;
int x2 = x1 == width - 1 ? x1 : x1 + 1;
int y0 = y1 == 0 ? y1 : y1 - 1;
int y2 = y1 == height -1 ? y1 : y1 + 1;
data[i1] = magnitude[i1];
for (int x = x0; x <= x2; x++) {
for (int y = y0; y <= y2; y++) {
int i2 = x + y * width;
if ((y != y1 || x != x1)
&& data[i2] == 0
&& magnitude[i2] >= threshold) {
follow(x, y, i2, threshold);
return;
}
}
}
}
private void thresholdEdges() {
for (int i = 0; i < picsize; i++) {
data[i] = data[i] > 0 ? -1 : 0xff000000;
}
}
private int luminance(float r, float g, float b) {
return Math.round(0.299f * r + 0.587f * g + 0.114f * b);
}
private void readLuminance() {
int type = sourceImage.getType();
if (type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB) {
int[] pixels = (int[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
int p = pixels[i];
int r = (p & 0xff0000) >> 16;
int g = (p & 0xff00) >> 8;
int b = p & 0xff;
data[i] = luminance(r, g, b);
}
} else if (type == BufferedImage.TYPE_BYTE_GRAY) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xff);
}
} else if (type == BufferedImage.TYPE_USHORT_GRAY) {
short[] pixels = (short[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xffff) / 256;
}
} else if (type == BufferedImage.TYPE_3BYTE_BGR) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
int offset = 0;
for (int i = 0; i < picsize; i++) {
int b = pixels[offset++] & 0xff;
int g = pixels[offset++] & 0xff;
int r = pixels[offset++] & 0xff;
data[i] = luminance(r, g, b);
}
} else {
throw new IllegalArgumentException("Unsupported image type: " + type);
}
}
private void normalizeContrast() {
int[] histogram = new int[256];
for (int i = 0; i < data.length; i++) {
histogram[data[i]]++;
}
int[] remap = new int[256];
int sum = 0;
int j = 0;
for (int i = 0; i < histogram.length; i++) {
sum += histogram[i];
int target = sum*255/picsize;
for (int k = j+1; k <=target; k++) {
remap[k] = i;
}
j = target;
}
for (int i = 0; i < data.length; i++) {
data[i] = remap[data[i]];
}
}
private void writeEdges(int pixels[]) {
//NOTE: There is currently no mechanism for obtaining the edge data
//in any other format other than an INT_ARGB type BufferedImage.
//This may be easily remedied by providing alternative accessors.
if (edgesImage == null) {
edgesImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
edgesImage.getWritableTile(0, 0).setDataElements(0, 0, width, height, pixels);
}
} |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #Factor | Factor | USING: command-line formatting grouping io kernel math.parser
namespaces prettyprint sequences splitting ;
IN: rosetta-code.canonicalize-cidr
! canonicalize a CIDR block: make sure none of the host bits are set
command-line get [ lines ] when-empty
[
! ( CIDR-IP -- bits-in-network-part dotted-decimal )
"/" split first2 string>number swap
! get IP as binary string
"." split [ string>number "%08b" sprintf ] map "" join
! replace the host part with all zeros
over cut length [ CHAR: 0 ] "" replicate-as append
! convert back to dotted-decimal
8 group [ bin> number>string ] map "." join swap
! and output
"%s/%d\n" printf
] each |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #Go | Go | package main
import (
"fmt"
"log"
"strconv"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
// canonicalize a CIDR block: make sure none of the host bits are set
func canonicalize(cidr string) string {
// dotted-decimal / bits in network part
split := strings.Split(cidr, "/")
dotted := split[0]
size, err := strconv.Atoi(split[1])
check(err)
// get IP as binary string
var bin []string
for _, n := range strings.Split(dotted, ".") {
i, err := strconv.Atoi(n)
check(err)
bin = append(bin, fmt.Sprintf("%08b", i))
}
binary := strings.Join(bin, "")
// replace the host part with all zeros
binary = binary[0:size] + strings.Repeat("0", 32-size)
// convert back to dotted-decimal
var canon []string
for i := 0; i < len(binary); i += 8 {
num, err := strconv.ParseInt(binary[i:i+8], 2, 64)
check(err)
canon = append(canon, fmt.Sprintf("%d", num))
}
// and return
return strings.Join(canon, ".") + "/" + split[1]
}
func main() {
tests := []string{
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18",
}
for _, test := range tests {
fmt.Printf("%-18s -> %s\n", test, canonicalize(test))
}
} |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #Go | Go | package main
import (
"fmt"
"log"
"strconv"
)
// A casting out nines algorithm.
// Quoting from: http://mathforum.org/library/drmath/view/55926.html
/*
First, for any number we can get a single digit, which I will call the
"check digit," by repeatedly adding the digits. That is, we add the
digits of the number, then if there is more than one digit in the
result we add its digits, and so on until there is only one digit
left.
...
You may notice that when you add the digits of 6395, if you just
ignore the 9, and the 6+3 = 9, you still end up with 5 as your check
digit. This is because any 9's make no difference in the result.
That's why the process is called "casting out" nines. Also, at any
step in the process, you can add digits, not just at the end: to do
8051647, I can say 8 + 5 = 13, which gives 4; plus 1 is 5, plus 6 is
11, which gives 2, plus 4 is 6, plus 7 is 13 which gives 4. I never
have to work with numbers bigger than 18.
*/
// The twist is that co9Peterson returns a function to do casting out nines
// in any specified base from 2 to 36.
func co9Peterson(base int) (cob func(string) (byte, error), err error) {
if base < 2 || base > 36 {
return nil, fmt.Errorf("co9Peterson: %d invalid base", base)
}
// addDigits adds two digits in the specified base.
// People perfoming casting out nines by hand would usually have their
// addition facts memorized. In a program, a lookup table might be
// analogous, but we expediently use features of the programming language
// to add digits in the specified base.
addDigits := func(a, b byte) (string, error) {
ai, err := strconv.ParseInt(string(a), base, 64)
if err != nil {
return "", err
}
bi, err := strconv.ParseInt(string(b), base, 64)
if err != nil {
return "", err
}
return strconv.FormatInt(ai+bi, base), nil
}
// a '9' in the specified base. that is, the greatest digit.
s9 := strconv.FormatInt(int64(base-1), base)
b9 := s9[0]
// define result function. The result function may return an error
// if n is not a valid number in the specified base.
cob = func(n string) (r byte, err error) {
r = '0'
for i := 0; i < len(n); i++ { // for each digit of the number
d := n[i]
switch {
case d == b9: // if the digit is '9' of the base, cast it out
continue
// if the result so far is 0, the digit becomes the result
case r == '0':
r = d
continue
}
// otherwise, add the new digit to the result digit
s, err := addDigits(r, d)
if err != nil {
return 0, err
}
switch {
case s == s9: // if the sum is "9" of the base, cast it out
r = '0'
continue
// if the sum is a single digit, it becomes the result
case len(s) == 1:
r = s[0]
continue
}
// otherwise, reduce this two digit intermediate result before
// continuing.
r, err = cob(s)
if err != nil {
return 0, err
}
}
return
}
return
}
// Subset code required by task. Given a base and a range specified with
// beginning and ending number in that base, return candidate Kaprekar numbers
// based on the observation that k%(base-1) must equal (k*k)%(base-1).
// For the % operation, rather than the language built-in operator, use
// the method of casting out nines, which in fact implements %(base-1).
func subset(base int, begin, end string) (s []string, err error) {
// convert begin, end to native integer types for easier iteration
begin64, err := strconv.ParseInt(begin, base, 64)
if err != nil {
return nil, fmt.Errorf("subset begin: %v", err)
}
end64, err := strconv.ParseInt(end, base, 64)
if err != nil {
return nil, fmt.Errorf("subset end: %v", err)
}
// generate casting out nines function for specified base
cob, err := co9Peterson(base)
if err != nil {
return
}
for k := begin64; k <= end64; k++ {
ks := strconv.FormatInt(k, base)
rk, err := cob(ks)
if err != nil { // assertion
panic(err) // this would indicate a bug in subset
}
rk2, err := cob(strconv.FormatInt(k*k, base))
if err != nil { // assertion
panic(err) // this would indicate a bug in subset
}
// test for candidate Kaprekar number
if rk == rk2 {
s = append(s, ks)
}
}
return
}
var testCases = []struct {
base int
begin, end string
kaprekar []string
}{
{10, "1", "100", []string{"1", "9", "45", "55", "99"}},
{17, "10", "gg", []string{"3d", "d4", "gg"}},
}
func main() {
for _, tc := range testCases {
fmt.Printf("\nTest case base = %d, begin = %s, end = %s:\n",
tc.base, tc.begin, tc.end)
s, err := subset(tc.base, tc.begin, tc.end)
if err != nil {
log.Fatal(err)
}
fmt.Println("Subset: ", s)
fmt.Println("Kaprekar:", tc.kaprekar)
sx := 0
for _, k := range tc.kaprekar {
for {
if sx == len(s) {
fmt.Printf("Fail:", k, "not in subset")
return
}
if s[sx] == k {
sx++
break
}
sx++
}
}
fmt.Println("Valid subset.")
}
} |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Python | Python |
"""
Input and output are assumed to be in this form based on the talk
page for the task:
input_points = [
[-1.0, 1.0, 1.0],
[-1.0, -1.0, 1.0],
[ 1.0, -1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, -1.0, -1.0],
[ 1.0, 1.0, -1.0],
[-1.0, -1.0, -1.0],
[-1.0, 1.0, -1.0]
]
input_faces = [
[0, 1, 2, 3],
[3, 2, 4, 5],
[5, 4, 6, 7],
[7, 0, 3, 5],
[7, 6, 1, 0],
[6, 1, 2, 4],
]
So, the graph is a list of points and a list of faces.
Each face is a list of indexes into the points list.
"""
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import sys
def center_point(p1, p2):
"""
returns a point in the center of the
segment ended by points p1 and p2
"""
cp = []
for i in range(3):
cp.append((p1[i]+p2[i])/2)
return cp
def sum_point(p1, p2):
"""
adds points p1 and p2
"""
sp = []
for i in range(3):
sp.append(p1[i]+p2[i])
return sp
def div_point(p, d):
"""
divide point p by d
"""
sp = []
for i in range(3):
sp.append(p[i]/d)
return sp
def mul_point(p, m):
"""
multiply point p by m
"""
sp = []
for i in range(3):
sp.append(p[i]*m)
return sp
def get_face_points(input_points, input_faces):
"""
From http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
1. for each face, a face point is created which is the average of all the points of the face.
"""
# 3 dimensional space
NUM_DIMENSIONS = 3
# face_points will have one point for each face
face_points = []
for curr_face in input_faces:
face_point = [0.0, 0.0, 0.0]
for curr_point_index in curr_face:
curr_point = input_points[curr_point_index]
# add curr_point to face_point
# will divide later
for i in range(NUM_DIMENSIONS):
face_point[i] += curr_point[i]
# divide by number of points for average
num_points = len(curr_face)
for i in range(NUM_DIMENSIONS):
face_point[i] /= num_points
face_points.append(face_point)
return face_points
def get_edges_faces(input_points, input_faces):
"""
Get list of edges and the one or two adjacent faces in a list.
also get center point of edge
Each edge would be [pointnum_1, pointnum_2, facenum_1, facenum_2, center]
"""
# will have [pointnum_1, pointnum_2, facenum]
edges = []
# get edges from each face
for facenum in range(len(input_faces)):
face = input_faces[facenum]
num_points = len(face)
# loop over index into face
for pointindex in range(num_points):
# if not last point then edge is curr point and next point
if pointindex < num_points - 1:
pointnum_1 = face[pointindex]
pointnum_2 = face[pointindex+1]
else:
# for last point edge is curr point and first point
pointnum_1 = face[pointindex]
pointnum_2 = face[0]
# order points in edge by lowest point number
if pointnum_1 > pointnum_2:
temp = pointnum_1
pointnum_1 = pointnum_2
pointnum_2 = temp
edges.append([pointnum_1, pointnum_2, facenum])
# sort edges by pointnum_1, pointnum_2, facenum
edges = sorted(edges)
# merge edges with 2 adjacent faces
# [pointnum_1, pointnum_2, facenum_1, facenum_2] or
# [pointnum_1, pointnum_2, facenum_1, None]
num_edges = len(edges)
eindex = 0
merged_edges = []
while eindex < num_edges:
e1 = edges[eindex]
# check if not last edge
if eindex < num_edges - 1:
e2 = edges[eindex+1]
if e1[0] == e2[0] and e1[1] == e2[1]:
merged_edges.append([e1[0],e1[1],e1[2],e2[2]])
eindex += 2
else:
merged_edges.append([e1[0],e1[1],e1[2],None])
eindex += 1
else:
merged_edges.append([e1[0],e1[1],e1[2],None])
eindex += 1
# add edge centers
edges_centers = []
for me in merged_edges:
p1 = input_points[me[0]]
p2 = input_points[me[1]]
cp = center_point(p1, p2)
edges_centers.append(me+[cp])
return edges_centers
def get_edge_points(input_points, edges_faces, face_points):
"""
for each edge, an edge point is created which is the average
between the center of the edge and the center of the segment made
with the face points of the two adjacent faces.
"""
edge_points = []
for edge in edges_faces:
# get center of edge
cp = edge[4]
# get center of two facepoints
fp1 = face_points[edge[2]]
# if not two faces just use one facepoint
# should not happen for solid like a cube
if edge[3] == None:
fp2 = fp1
else:
fp2 = face_points[edge[3]]
cfp = center_point(fp1, fp2)
# get average between center of edge and
# center of facepoints
edge_point = center_point(cp, cfp)
edge_points.append(edge_point)
return edge_points
def get_avg_face_points(input_points, input_faces, face_points):
"""
for each point calculate
the average of the face points of the faces the point belongs to (avg_face_points)
create a list of lists of two numbers [facepoint_sum, num_points] by going through the
points in all the faces.
then create the avg_face_points list of point by dividing point_sum (x, y, z) by num_points
"""
# initialize list with [[0.0, 0.0, 0.0], 0]
num_points = len(input_points)
temp_points = []
for pointnum in range(num_points):
temp_points.append([[0.0, 0.0, 0.0], 0])
# loop through faces updating temp_points
for facenum in range(len(input_faces)):
fp = face_points[facenum]
for pointnum in input_faces[facenum]:
tp = temp_points[pointnum][0]
temp_points[pointnum][0] = sum_point(tp,fp)
temp_points[pointnum][1] += 1
# divide to create avg_face_points
avg_face_points = []
for tp in temp_points:
afp = div_point(tp[0], tp[1])
avg_face_points.append(afp)
return avg_face_points
def get_avg_mid_edges(input_points, edges_faces):
"""
the average of the centers of edges the point belongs to (avg_mid_edges)
create list with entry for each point
each entry has two elements. one is a point that is the sum of the centers of the edges
and the other is the number of edges. after going through all edges divide by
number of edges.
"""
# initialize list with [[0.0, 0.0, 0.0], 0]
num_points = len(input_points)
temp_points = []
for pointnum in range(num_points):
temp_points.append([[0.0, 0.0, 0.0], 0])
# go through edges_faces using center updating each point
for edge in edges_faces:
cp = edge[4]
for pointnum in [edge[0], edge[1]]:
tp = temp_points[pointnum][0]
temp_points[pointnum][0] = sum_point(tp,cp)
temp_points[pointnum][1] += 1
# divide out number of points to get average
avg_mid_edges = []
for tp in temp_points:
ame = div_point(tp[0], tp[1])
avg_mid_edges.append(ame)
return avg_mid_edges
def get_points_faces(input_points, input_faces):
# initialize list with 0
num_points = len(input_points)
points_faces = []
for pointnum in range(num_points):
points_faces.append(0)
# loop through faces updating points_faces
for facenum in range(len(input_faces)):
for pointnum in input_faces[facenum]:
points_faces[pointnum] += 1
return points_faces
def get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges):
"""
m1 = (n - 3.0) / n
m2 = 1.0 / n
m3 = 2.0 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
"""
new_points =[]
for pointnum in range(len(input_points)):
n = points_faces[pointnum]
m1 = (n - 3.0) / n
m2 = 1.0 / n
m3 = 2.0 / n
old_coords = input_points[pointnum]
p1 = mul_point(old_coords, m1)
afp = avg_face_points[pointnum]
p2 = mul_point(afp, m2)
ame = avg_mid_edges[pointnum]
p3 = mul_point(ame, m3)
p4 = sum_point(p1, p2)
new_coords = sum_point(p4, p3)
new_points.append(new_coords)
return new_points
def switch_nums(point_nums):
"""
Returns tuple of point numbers
sorted least to most
"""
if point_nums[0] < point_nums[1]:
return point_nums
else:
return (point_nums[1], point_nums[0])
def cmc_subdiv(input_points, input_faces):
# 1. for each face, a face point is created which is the average of all the points of the face.
# each entry in the returned list is a point (x, y, z).
face_points = get_face_points(input_points, input_faces)
# get list of edges with 1 or 2 adjacent faces
# [pointnum_1, pointnum_2, facenum_1, facenum_2, center] or
# [pointnum_1, pointnum_2, facenum_1, None, center]
edges_faces = get_edges_faces(input_points, input_faces)
# get edge points, a list of points
edge_points = get_edge_points(input_points, edges_faces, face_points)
# the average of the face points of the faces the point belongs to (avg_face_points)
avg_face_points = get_avg_face_points(input_points, input_faces, face_points)
# the average of the centers of edges the point belongs to (avg_mid_edges)
avg_mid_edges = get_avg_mid_edges(input_points, edges_faces)
# how many faces a point belongs to
points_faces = get_points_faces(input_points, input_faces)
"""
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
"""
new_points = get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges)
"""
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_point ab, face_point abc, edge_point ca)
(b, edge_point bc, face_point abc, edge_point ab)
(c, edge_point ca, face_point abc, edge_point bc)
for a quad face (a,b,c,d):
(a, edge_point ab, face_point abcd, edge_point da)
(b, edge_point bc, face_point abcd, edge_point ab)
(c, edge_point cd, face_point abcd, edge_point bc)
(d, edge_point da, face_point abcd, edge_point cd)
face_points is a list indexed by face number so that is
easy to get.
edge_points is a list indexed by the edge number
which is an index into edges_faces.
need to add face_points and edge points to
new_points and get index into each.
then create two new structures
face_point_nums - list indexes by facenum
whose value is the index into new_points
edge_point num - dictionary with key (pointnum_1, pointnum_2)
and value is index into new_points
"""
# add face points to new_points
face_point_nums = []
# point num after next append to new_points
next_pointnum = len(new_points)
for face_point in face_points:
new_points.append(face_point)
face_point_nums.append(next_pointnum)
next_pointnum += 1
# add edge points to new_points
edge_point_nums = dict()
for edgenum in range(len(edges_faces)):
pointnum_1 = edges_faces[edgenum][0]
pointnum_2 = edges_faces[edgenum][1]
edge_point = edge_points[edgenum]
new_points.append(edge_point)
edge_point_nums[(pointnum_1, pointnum_2)] = next_pointnum
next_pointnum += 1
# new_points now has the points to output. Need new
# faces
"""
just doing this case for now:
for a quad face (a,b,c,d):
(a, edge_point ab, face_point abcd, edge_point da)
(b, edge_point bc, face_point abcd, edge_point ab)
(c, edge_point cd, face_point abcd, edge_point bc)
(d, edge_point da, face_point abcd, edge_point cd)
new_faces will be a list of lists where the elements are like this:
[pointnum_1, pointnum_2, pointnum_3, pointnum_4]
"""
new_faces =[]
for oldfacenum in range(len(input_faces)):
oldface = input_faces[oldfacenum]
# 4 point face
if len(oldface) == 4:
a = oldface[0]
b = oldface[1]
c = oldface[2]
d = oldface[3]
face_point_abcd = face_point_nums[oldfacenum]
edge_point_ab = edge_point_nums[switch_nums((a, b))]
edge_point_da = edge_point_nums[switch_nums((d, a))]
edge_point_bc = edge_point_nums[switch_nums((b, c))]
edge_point_cd = edge_point_nums[switch_nums((c, d))]
new_faces.append((a, edge_point_ab, face_point_abcd, edge_point_da))
new_faces.append((b, edge_point_bc, face_point_abcd, edge_point_ab))
new_faces.append((c, edge_point_cd, face_point_abcd, edge_point_bc))
new_faces.append((d, edge_point_da, face_point_abcd, edge_point_cd))
return new_points, new_faces
def graph_output(output_points, output_faces):
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
"""
Plot each face
"""
for facenum in range(len(output_faces)):
curr_face = output_faces[facenum]
xcurr = []
ycurr = []
zcurr = []
for pointnum in range(len(curr_face)):
xcurr.append(output_points[curr_face[pointnum]][0])
ycurr.append(output_points[curr_face[pointnum]][1])
zcurr.append(output_points[curr_face[pointnum]][2])
xcurr.append(output_points[curr_face[0]][0])
ycurr.append(output_points[curr_face[0]][1])
zcurr.append(output_points[curr_face[0]][2])
ax.plot(xcurr,ycurr,zcurr,color='b')
plt.show()
# cube
input_points = [
[-1.0, 1.0, 1.0],
[-1.0, -1.0, 1.0],
[ 1.0, -1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, -1.0, -1.0],
[ 1.0, 1.0, -1.0],
[-1.0, -1.0, -1.0],
[-1.0, 1.0, -1.0]
]
input_faces = [
[0, 1, 2, 3],
[3, 2, 4, 5],
[5, 4, 6, 7],
[7, 0, 3, 5],
[7, 6, 1, 0],
[6, 1, 2, 4],
]
if len(sys.argv) != 2:
print("Should have one argument integer number of iterations")
sys.exit()
else:
iterations = int(sys.argv[1])
output_points, output_faces = input_points, input_faces
for i in range(iterations):
output_points, output_faces = cmc_subdiv(output_points, output_faces)
graph_output(output_points, output_faces)
|
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #EchoLisp | EchoLisp |
;; charmichaël numbers up to N-th prime ; 61 is 18-th prime
(define (charms (N 18) local: (h31 0) (Prime2 0) (Prime3 0))
(for* ((Prime1 (primes N))
(h3 (in-range 1 Prime1))
(d (+ h3 Prime1)))
(set! h31 (+ h3 Prime1))
#:continue (!zero? (modulo (* h31 (1- Prime1)) d))
#:continue (!= (modulo d h3) (modulo (- (* Prime1 Prime1)) h3))
(set! Prime2 (1+ ( * (1- Prime1) (quotient h31 d))))
#:when (prime? Prime2)
(set! Prime3 (1+ (quotient (* Prime1 Prime2) h3)))
#:when (prime? Prime3)
#:when (= 1 (modulo (* Prime2 Prime3) (1- Prime1)))
(printf " 💥 %12d = %d x %d x %d" (* Prime1 Prime2 Prime3) Prime1 Prime2 Prime3)))
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | reduce f lst init:
if lst:
f reduce @f lst init pop-from lst
else:
init
!. reduce @+ [ 1 10 200 ] 4
!. reduce @- [ 1 10 200 ] 4
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Delphi | Delphi |
;; rem : the foldX family always need an initial value
;; fold left a list
(foldl + 0 (iota 10)) ;; 0 + 1 + .. + 9
→ 45
;; fold left a sequence
(lib 'sequences)
(foldl * 1 [ 1 .. 10])
→ 362880 ;; 10!
;; folding left and right
(foldl / 1 ' ( 1 2 3 4))
→ 8/3
(foldr / 1 '(1 2 3 4))
→ 3/8
;;scanl gives the list (or sequence) of intermediate values :
(scanl * 1 '( 1 2 3 4 5))
→ (1 1 2 6 24 120)
|
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Ruby | Ruby | txt = "WELLDONEISBETTERTHANWELLSAID"
@left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ".chars
@right = "PTLNBQDEOYSFAVZKGJRIHWXUMC".chars
def encrypt(char)
coded_char = @left[@right.index(char)]
@left.rotate!(@left.index(coded_char))
part = @left.slice!(1,13).rotate
@left.insert(1, *part)
@right.rotate!(@right.index(char)+1)
part = @right.slice!(2,12).rotate
@right.insert(2, *part)
@left[0]
end
puts txt.each_char.map{|c| encrypt(c) }.join
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #M2000_Interpreter | M2000 Interpreter |
Module CatalanNumbers {
Def Integer count, t_row, size=31
Dim triangle(1 to size, 1 to size)
\\ call sub
pascal_triangle(size, &triangle())
Print "The first 15 Catalan numbers are"
count = 1% : t_row = 2%
Do {
Print Format$("{0:0:-3}:{1:0:-15}", count, triangle(t_row, t_row) - triangle(t_row +1, t_row -1))
t_row++
count++
} Until count > 15
End
Sub pascal_triangle(rows As Integer, &Pas_tri())
Local x=0%, y=0%
For x = 1 To rows
Pas_tri( 1%, x ) = 1@
Pas_tri( x, 1% ) = 1@
Next x
if rows<2 then exit sub
For x = 2 To rows-1
For y = 2 To rows + 1 - x
Pas_tri(x, y) = pas_tri(x - 1 , y) + pas_tri(x, y - 1)
Next y
Next x
End Sub
}
CatalanNumbers
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Maple | Maple | catalan:=proc(n)
local i,a:=[1],C:=[1];
for i to n do
a:=[0,op(a)]+[op(a),0];
a:=[0,op(a)]+[op(a),0];
C:=[op(C),a[i+1]-a[i]];
od;
C
end:
catalan(10);
# [1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796] |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Julia | Julia | dog, Dog, DOG = "Benjamin", "Samba", "Bernie"
if dog === Dog
println("There is only one dog, ", DOG)
else
println("The three dogs are: ", dog, ", ", Dog, " and ", DOG)
end |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #K | K |
dog: "Benjamin"
Dog: "Samba"
DOG: "Bernie"
"There are three dogs named ",dog,", ",Dog," and ",DOG
"There are three dogs named Benjamin, Samba and Bernie"
|
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Factor | Factor | IN: scratchpad { 1 2 } { 3 4 } cartesian-product .
{ { { 1 3 } { 1 4 } } { { 2 3 } { 2 4 } } }
IN: scratchpad { 3 4 } { 1 2 } cartesian-product .
{ { { 3 1 } { 3 2 } } { { 4 1 } { 4 2 } } }
IN: scratchpad { 1 2 } { } cartesian-product .
{ { } { } }
IN: scratchpad { } { 1 2 } cartesian-product .
{ } |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #BASIC256 | BASIC256 | function factorial(n)
if n = 0 then return 1
return n * factorial(n - 1)
end function
function catalan1(n)
prod = 1
for i = n + 2 to 2 * n
prod *= i
next i
return int(prod / factorial(n))
end function
function catalan2(n)
if n = 0 then return 1
sum = 0
for i = 0 to n - 1
sum += catalan2(i) * catalan2(n - 1 - i)
next i
return sum
end function
function catalan3(n)
if n = 0 then return 1
return catalan3(n - 1) * 2 * (2 * n - 1) \ (n + 1)
end function
print "n", "First", "Second", "Third"
print "-", "-----", "------", "-----"
print
for i = 0 to 15
print i, catalan1(i), catalan2(i), catalan3(i)
next i |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #C.2B.2B | C++ | // Static
MyClass::method(someParameter);
// Instance
myInstance.method(someParameter);
// Pointer
MyPointer->method(someParameter);
|
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #C_sharp | C_sharp | // Static
MyClass.Method(someParameter);
// Instance
myInstance.Method(someParameter); |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #Arturo | Arturo | getCurlVersion: function [][
try? [
call.external:'curl "curl_version" .expect: :string []
]
else [
"library not found"
]
]
print ["curl version:" getCurlVersion] |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #AutoHotkey | AutoHotkey | ahkdll := DllCall("LoadLibrary", "str", "AutoHotkey.dll")
clientHandle := DllCall("AutoHotkey\ahkdll", "str", "dllclient.ahk", "str"
, "", "str", "parameter1 parameter2", "Cdecl Int") |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #AWK | AWK |
# syntax: GAWK -f CANTOR_SET.AWK
# converted from C
BEGIN {
WIDTH = 81
HEIGHT = 5
for (i=0; i<HEIGHT; ++i) {
for (j=0; j<WIDTH; ++j) {
lines[i][j] = "*"
}
}
cantor(0,WIDTH,1)
for (i=0; i<HEIGHT; ++i) {
for (j=0; j<WIDTH; ++j) {
printf("%s",lines[i][j])
}
printf("\n")
}
exit(0)
}
function cantor(start,leng,indx, i,j,seg) {
seg = int(leng/3)
if (seg == 0) { return }
for (i=indx; i<HEIGHT; ++i) {
for (j=start+seg; j<start+seg*2; ++j) {
lines[i][j] = " "
}
}
cantor(start,seg,indx+1)
cantor(start+seg*2,seg,indx+1)
}
|
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to use a rational number data type.
It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.
It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:
[a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1]
Example
The fraction 9/4 has odd continued fraction representation 2; 3, 1, giving a binary representation of 100011,
which means 9/4 appears as the 35th term of the sequence.
Task part 2
Find the position of the number 83116/51639 in the Calkin-Wilf sequence.
See also
Wikipedia entry: Calkin-Wilf tree
Continued fraction
Continued fraction/Arithmetic/Construct from rational number
| #ALGOL_68 | ALGOL 68 | BEGIN
# Show elements 1-20 of the Calkin-Wilf sequence as rational numbers #
# also show the position of a specific element in the seuence #
# Uses code from the Arithmetic/Rational #
# & Continued fraction/Arithmetic/Construct from rational number tasks #
# Code from the Arithmetic/Rational task #
# ============================================================== #
MODE FRAC = STRUCT( INT num #erator#, den #ominator#);
PROC gcd = (INT a, b) INT: # greatest common divisor #
(a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a));
PROC lcm = (INT a, b)INT: # least common multiple #
a OVER gcd(a, b) * b;
PRIO // = 9; # higher then the ** operator #
OP // = (INT num, den)FRAC: ( # initialise and normalise #
INT common = gcd(num, den);
IF den < 0 THEN
( -num OVER common, -den OVER common)
ELSE
( num OVER common, den OVER common)
FI
);
OP + = (FRAC a, b)FRAC: (
INT common = lcm(den OF a, den OF b);
FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common );
num OF result//den OF result
);
OP - = (FRAC a, b)FRAC: a + -b,
* = (FRAC a, b)FRAC: (
INT num = num OF a * num OF b,
den = den OF a * den OF b;
INT common = gcd(num, den);
(num OVER common) // (den OVER common)
);
OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac);
# ============================================================== #
# end code from the Arithmetic/Rational task #
# code from the Continued fraction/Arithmetic/Construct from rational number task #
# ================================================================================#
# returns the quotient of numerator over denominator and sets #
# numerator and denominator to the next values for #
# the continued fraction #
PROC r2cf = ( REF INT numerator, REF INT denominator )INT:
IF denominator = 0
THEN 0
ELSE INT quotient := numerator OVER denominator;
INT prev numerator = numerator;
numerator := denominator;
denominator := prev numerator MOD denominator;
quotient
FI # r2cf # ;
# ====================================================================================#
# end code from the Continued fraction/Arithmetic/Construct from rational number task #
# Additional FRACrelated operators #
OP * = ( INT a, FRAC b )FRAC: ( num OF b * a ) // den OF b;
OP / = ( FRAC a, b )FRAC: ( num OF a * den OF b ) // ( num OF b * den OF a );
OP FLOOR = ( FRAC a )INT: num OF a OVER den OF a;
OP + = ( INT a, FRAC b )FRAC: ( a // 1 ) + b;
FRAC one = 1 // 1;
# returns the first n elements of the Calkin-Wilf sequence #
PROC calkin wilf = ( INT n )[]FRAC:
BEGIN
[ 1 : n ]FRAC q;
IF n > 0 THEN
q[ 1 ] := 1 // 1;
FOR i FROM 2 TO UPB q DO
q[ i ] := one / ( ( 2 * FLOOR q[ i - 1 ] ) + one - q[ i - 1 ] )
OD
FI;
q
END # calkin wilf # ;
# returns the position of a FRAC in the Calkin-Wilf sequence by computing its #
# continued fraction representation and converting that to a bit string #
# - the position must fit in a 2-bit number #
PROC position in calkin wilf sequence = ( FRAC f )INT:
IF INT result := 0;
[ 1 : 32 ]INT cf; FOR i FROM LWB cf TO UPB cf DO cf[ i ] := 0 OD;
INT num := num OF f;
INT den := den OF f;
INT cf length := 0;
FOR i FROM LWB cf WHILE den /= 0 DO
cf[ cf length := i ] := r2cf( num, den )
OD;
NOT ODD cf length
THEN # the continued fraction does not have an odd length #
-1
ELSE # the continued fraction has an odd length so we can compute the seuence length #
# build the number by alternating d 1s and 0s where d is the digits of the #
# continued fraction, starting at the least significant #
INT digit := 1;
FOR d pos FROM cf length BY -1 TO 1 DO
FOR i TO cf[ d pos ] DO
result *:= 2 +:= digit
OD;
digit := IF digit = 0 THEN 1 ELSE 0 FI
OD;
result
FI # position in calkin wilf sequence # ;
BEGIN # task #
# get and show the first 20 Calkin-Wilf sequence numbers #
[]FRAC cw = calkin wilf( 20 );
print( ( "The first 20 elements of the Calkin-Wilf sequence are:", newline, " " ) );
FOR n FROM LWB cw TO UPB cw DO
FRAC sn = cw[ n ];
print( ( " ", whole( num OF sn, 0 ), "/", whole( den OF sn, 0 ) ) )
OD;
print( ( newline ) );
# show the position of a specific element in the sequence #
print( ( "Position of 83116/51639 in the sequence: "
, whole( position in calkin wilf sequence( 83116//51639 ), 0 )
)
)
END
END |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #Julia | Julia | using Images
canny_edges = canny(img, sigma = 1.4, upperThreshold = 0.80, lowerThreshold = 0.20) |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Export["out.bmp", EdgeDetect[Import[InputString[]]]]; |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #Hare | Hare | use fmt;
use net::ip;
use strings;
export fn main() void = {
const array = ["87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"];
for (let i = 0z; i < len(array); i += 1) {
match (canonicalizecidr(array[i])) {
case let s: str =>
fmt::printfln("{:-18} => {}", array[i], s)!;
free(s);
case net::ip::invalid =>
fmt::errorfln("Error: invalid item: {}", array[i])!;
};
};
};
fn canonicalizecidr(a: str) (str | net::ip::invalid) = {
const sub = net::ip::parsecidr(a)?;
match (sub.addr) {
case let addr4: net::ip::addr4 => void;
case net::ip::addr6 => return net::ip::invalid;
};
const net = sub.addr as [4]u8;
const msk = sub.mask as [4]u8;
const net: u32 = net[0]: u32 << 24 | net[1]: u32 << 16 | net[2]: u32 << 8 | net[3]: u32;
const msk: u32 = msk[0]: u32 << 24 | msk[1]: u32 << 16 | msk[2]: u32 << 8 | msk[3]: u32;
const result: u32 = net & msk;
return fmt::asprintf("{}.{}.{}.{}/{}",
result >> 24,
0xff & result >> 16,
0xff & result >> 8,
0xff & result,
strings::cut(a, "/").1);
}; |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #Haskell | Haskell | import Control.Monad (guard)
import Data.Bits ((.|.), (.&.), complement, shiftL, shiftR, zeroBits)
import Data.Maybe (listToMaybe)
import Data.Word (Word32, Word8)
import Text.ParserCombinators.ReadP (ReadP, char, readP_to_S)
import Text.Printf (printf)
import Text.Read.Lex (readDecP)
-- A 32-bit IPv4 address, with a netmask applied, and the number of leading bits
-- that are in the network portion of the address.
data CIDR = CIDR Word32 Word8
-- Convert a string to a CIDR, or nothing if it's invalid.
cidrRead :: String -> Maybe CIDR
cidrRead = listToMaybe . map fst . readP_to_S cidrP
-- Convert the CIDR to a string.
cidrShow :: CIDR -> String
cidrShow (CIDR addr n) = let (a, b, c, d) = octetsFrom addr
in printf "%u.%u.%u.%u/%u" a b c d n
-- Parser for the string representation of a CIDR. For a successful parse the
-- string must have the form a.b.c.d/n, where each of a, b, c and d are decimal
-- numbers in the range [0, 255] and n is a decimal number in the range [0, 32].
cidrP :: ReadP CIDR
cidrP = do a <- octetP <* char '.'
b <- octetP <* char '.'
c <- octetP <* char '.'
d <- octetP <* char '/'
n <- netBitsP
return $ CIDR (addrFrom a b c d .&. netmask n) n
where octetP = wordP 255
netBitsP = wordP 32
-- Parser for a decimal string, whose value is in the range [0, lim].
--
-- We want the limit argument to be an Integer, so that we can detect values
-- that are too large, rather than having them silently wrap.
wordP :: Integral a => Integer -> ReadP a
wordP lim = do n <- readDecP
guard $ n <= lim
return $ fi n
-- The octets of an IPv4 address.
octetsFrom :: Word32 -> (Word8, Word8, Word8, Word8)
octetsFrom addr = (oct addr 3, oct addr 2, oct addr 1, oct addr 0)
where oct w n = fi $ w `shiftR` (8*n) .&. 0xff
-- An IPv4 address from four octets. `ipAddr4 1 2 3 4' is the address 1.2.3.4.
addrFrom :: Word8 -> Word8 -> Word8 -> Word8 -> Word32
addrFrom a b c d = 0 <<+ a <<+ b <<+ c <<+ d
where w <<+ o = w `shiftL` 8 .|. fi o
-- The value `netmask n' is the netmask whose leftmost n bits are 1, and the
-- remainder are 0.
netmask :: Word8 -> Word32
netmask n = complement $ complement zeroBits `shiftR` fi n
fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
test :: String -> IO ()
test str = do
let cidrStr = maybe "invalid CIDR string" cidrShow (cidrRead str)
printf "%-18s -> %s\n" str cidrStr
main :: IO ()
main = do
test "87.70.141.1/22"
test "36.18.154.103/12"
test "62.62.197.11/29"
test "67.137.119.181/4"
test "161.214.74.21/24"
test "184.232.176.184/18"
test "184.256.176.184/12" -- octet value is too large
test "184.232.176.184/33" -- netmask size is too large
test "184.232.184/18" -- too few components |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #Haskell | Haskell | co9 n
| n <= 8 = n
| otherwise = co9 $ sum $ filter (/= 9) $ digits 10 n
task2 = filter (\n -> co9 n == co9 (n ^ 2)) [1 .. 100]
task3 k = filter (\n -> n `mod` k == n ^ 2 `mod` k) [1 .. 100] |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Rust | Rust |
pub struct Vector3 {pub x: f64, pub y: f64, pub z: f64, pub w: f64}
pub struct Triangle {pub r: [usize; 3], pub(crate) col: [f32; 4], pub(crate) p: [Vector3; 3], n: Vector3, pub t: [Vector2; 3]}
pub struct Mesh{pub v: Vec<Vector3>, pub f: Vec<Triangle>}
impl Triangle{
pub fn new() -> Triangle {return Triangle {r: [0, 0, 0], col: [0.0; 4], p: [Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0), Vector3::new(0.0, 0.0, 0.0)], n: Vector3::new(0.0, 0.0, 0.0), t: [Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0), Vector2::new(0.0, 0.0)]}}
pub fn copy(&self) -> Triangle {return Triangle {r: self.r.clone(), col: self.col, p: [self.p[0].copy(), self.p[1].copy(), self.p[2].copy()], n: self.n.copy(), t: [self.t[0].copy(), self.t[1].copy(), self.t[2].copy()]}}
}
impl Vector3 {
pub fn new(x: f64, y: f64, z: f64) -> Vector3 {return Vector3 {x, y, z, w: 1.0}}
pub fn normalize(&mut self) {
let l = (self.x * self.x + self.y * self.y + self.z * self.z).sqrt();
self.x /= l;
self.y /= l;
self.z /= l;
}
pub fn dot_product(v1: &Vector3, v2: &Vector3) -> f64 {return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z}
pub fn cross_product(v1: &Vector3, v2: &Vector3) -> Vector3 {return Vector3::new(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x)}
pub fn intersect_plane(plane_n: &Vector3, plane_p: &Vector3, line_start: &Vector3, line_end: &Vector3, mut t: f64) -> Vector3 {
let mut p_n = plane_n.copy();
p_n.normalize();
let plane_d = -Vector3::dot_product(&p_n, plane_p);
let ad = Vector3::dot_product(line_start, &p_n);
let bd = Vector3::dot_product(line_end, &p_n);
t = (-plane_d - ad) / (bd - ad);
let line = line_end.copy() - line_start;
let line_i = line * t;
return line_start.copy() + &line_i;
}
pub fn copy(&self) -> Vector3 {return Vector3 {x: self.x, y: self.y, z: self.z, w: self.w}}
}
impl Mesh {
pub fn get_face_points(&self) -> Vec<Vector3> {
let mut face_points: Vec<Vector3> = Vec::new();
for curr_face in &self.f {
let mut face_point = Vector3::new(0.0, 0.0, 0.0);
for curr_point_index in curr_face.r {
let curr_point = &self.v[curr_point_index];
face_point += &curr_point
}
face_point /= curr_face.r.len() as f64;
face_points.push(face_point.copy());
}
return face_points;
}
pub fn get_edges_faces(&self) -> Vec<[f64; 7]> {
let mut edges: Vec<[usize; 3]> = Vec::new();
for face_num in 0..self.f.len() {
let face: Triangle = self.f[face_num].copy();
let num_points = face.p.len();
for point_index in 0..num_points {
let mut point_num_1 = 0;
let mut point_num_2 = 0;
if point_index < num_points - 1 {
point_num_1 = face.r[point_index];
point_num_2 = face.r[point_index + 1];
} else {
point_num_1 = face.r[point_index];
point_num_2 = face.r[0];
}
if point_num_1 > point_num_2 {
let temp = point_num_1;
point_num_1 = point_num_2;
point_num_2 = temp;
}
edges.push([point_num_1, point_num_2, face_num]);
}
}
edges.sort();
let num_edges = edges.len();
let mut index = 0;
let mut merged_edges: Vec<[f64; 4]> = Vec::new();
while index < num_edges {
let e1 = edges[index];
if index < num_edges - 1 {
let e2 = edges[index + 1];
if e1[0] == e2[0] && e1[1] == e2[1] {
merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, e2[2] as f64]);
index += 2;
} else {
merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, -1.0]);
index += 1;
}
} else {
merged_edges.push([e1[0] as f64, e1[1] as f64, e1[2] as f64, -1.0]);
index += 1
}
}
let mut edges_centers = Vec::new();
for me in merged_edges {
let p1 = self.v[me[0] as usize].copy();
let p2 = self.v[me[1] as usize].copy();
let cp: Vector3 = Mesh::center_point(&p1, &p2);
edges_centers.push([me[0] as f64, me[1] as f64, me[2] as f64, me[3] as f64, cp.x, cp.y, cp.z]);
}
return edges_centers;
}
pub fn get_edge_points(&self, edges_faces: &Vec<[f64; 7]>, face_points: &Vec<Vector3>) -> Vec<Vector3> {
let mut edge_points = Vec::new();
for edge in edges_faces {
let cp = Vector3::new(edge[4], edge[5], edge[6]);
let fp1: Vector3 = face_points[edge[2] as usize].copy();
let mut fp2: Vector3 = fp1.copy();
if edge[3] != -1.0 { fp2 = face_points[edge[3] as usize].copy() };
let cfp = Mesh::center_point(&fp1, &fp2);
let edge_point = Mesh::center_point(&cp, &cfp);
edge_points.push(edge_point);
}
return edge_points
}
pub fn get_avg_face_points(&self, face_points: &Vec<Vector3>) -> Vec<Vector3> {
let num_points = self.v.len();
let mut temp_points = Vec::new();
let mut div: Vec<i32> = Vec::new();
for _ in 0..num_points {
temp_points.push(Vector3::new(0.0, 0.0, 0.0));
div.push(0)
};
for face_num in 0..self.f.len() {
let mut fp = face_points[face_num].copy();
for point_num in self.f[face_num].r {
let tp = temp_points[point_num].copy();
temp_points[point_num] = tp + &fp;
div[point_num] += 1;
}
}
let mut avg_face_points: Vec<Vector3> = Vec::new();
for i in 0..temp_points.len() {
let tp: Vector3 = temp_points[i].copy();
let t = tp / (div[i] as f64);
avg_face_points.push(t.copy());
}
return avg_face_points;
}
pub fn get_avg_mid_edges(&self, edges_faces: &Vec<[f64; 7]>) -> Vec<Vector3> {
let num_points = self.v.len();
let mut temp_points = Vec::new();
let mut div: Vec<i32> = Vec::new();
for point_num in 0..num_points{ temp_points.push(Vector3::new(0.0, 0.0, 0.0)); div.push(0)}
for edge in edges_faces {
let cp = Vector3::new(edge[4], edge[5], edge[6]);
for point_num in [edge[0] as usize, edge[1] as usize] {
let tp = temp_points[point_num].copy();
temp_points[point_num] = tp + &cp;
div[point_num] += 1
}
}
let mut avg_mid_edges: Vec<Vector3> = Vec::new();
for i in 0..temp_points.len(){
let ame: Vector3 = temp_points[i].copy() / (div[i] as f64);
avg_mid_edges.push(ame)}
return avg_mid_edges
}
pub fn get_points_faces(&self) -> Vec<i32> {
let num_points = self.v.len();
let mut points_faces: Vec<i32> = Vec::new();
for point_num in 0..num_points{points_faces.push(0)}
for face_num in 0..self.f.len() {
for point_num in self.f[face_num].r {
points_faces[point_num] += 1;
}
}
return points_faces
}
pub fn get_new_points(&self, points_faces: &Vec<i32>, avg_face_points: &Vec<Vector3>, avg_mid_edges: &Vec<Vector3>) -> Vec<Vector3> {
let mut new_points: Vec<Vector3> = Vec::new();
for point_num in 0..self.v.len() {
let n = points_faces[point_num] as f64;
let m1 = (n - 3.0) / n;
let m2 = 1.0 / n;
let m3 = 2.0 / n;
let old_coords = self.v[point_num].copy();
let p1 = old_coords * m1;
let afp = avg_face_points[point_num].copy();
let p2 = afp * m2;
let ame = avg_mid_edges[point_num].copy();
let p3 = ame * m3;
let p4 = p1 + &p2;
let new_coords = p4 + &p3;
new_points.push(new_coords);
}
return new_points;
}
pub fn switch_nums(point_nums: [f64; 2]) -> [f64; 2] {
return if point_nums[0] < point_nums[1] { point_nums } else {[point_nums[1], point_nums[0]]}
}
pub fn get_key(points: [f64; 2]) -> String {
return points[0].to_string() + ";" + &*points[1].to_string();
}
pub fn subdivide(&mut self) {
let face_points = self.get_face_points();
let edges_faces = self.get_edges_faces();
let edge_points = self.get_edge_points(&edges_faces, &face_points);
let avg_face_points = self.get_avg_face_points(&face_points);
let avg_mid_edges = self.get_avg_mid_edges(&edges_faces);
let points_faces = self.get_points_faces();
let mut new_points = self.get_new_points(&points_faces, &avg_face_points, &avg_mid_edges);
let mut face_point_nums = Vec::new();
let mut next_point_num = new_points.len();
for face_point in face_points {
new_points.push(face_point);
face_point_nums.push(next_point_num);
next_point_num += 1;
}
let mut edge_point_nums: HashMap<String, usize> = HashMap::new();
for edge_num in 0..edges_faces.len() {
let point_num_1 = edges_faces[edge_num][0];
let point_num_2 = edges_faces[edge_num][1];
let edge_point = edge_points[edge_num].copy();
new_points.push(edge_point);
edge_point_nums.insert(Mesh::get_key([point_num_1, point_num_2]), next_point_num);
next_point_num += 1;
}
let mut new_faces = Vec::new();
for old_face_num in 0..self.f.len() {
let old_face = self.f[old_face_num].copy();
let a = old_face.r[0] as f64;
let b = old_face.r[1] as f64;
let c = old_face.r[2] as f64;
let face_point_abc = face_point_nums[old_face_num];
let edge_point_ab = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([a, b]))).unwrap();
let edge_point_bc = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([b, c]))).unwrap();
let edge_point_ca = *edge_point_nums.get(&*Mesh::get_key(Mesh::switch_nums([c, a]))).unwrap();
new_faces.push([a, edge_point_ab as f64, face_point_abc as f64, edge_point_ca as f64]);
new_faces.push([b, edge_point_bc as f64, face_point_abc as f64, edge_point_ab as f64]);
new_faces.push([c, edge_point_ca as f64, face_point_abc as f64, edge_point_bc as f64]);
}
self.f = Vec::new();
for face_num in 0..new_faces.len() {
let curr_face = new_faces[face_num];
let mut t1: Triangle = Triangle::new();
let mut t2: Triangle = Triangle::new();
t1.p[0] = Vector3::new(new_points[curr_face[0] as usize].x, new_points[curr_face[0] as usize].y, new_points[curr_face[0] as usize].z);
t1.p[1] = Vector3::new(new_points[curr_face[1] as usize].x, new_points[curr_face[1] as usize].y, new_points[curr_face[1] as usize].z);
t1.p[2] = Vector3::new(new_points[curr_face[2] as usize].x, new_points[curr_face[2] as usize].y, new_points[curr_face[2] as usize].z);
t2.p[0] = Vector3::new(new_points[curr_face[2] as usize].x, new_points[curr_face[2] as usize].y, new_points[curr_face[2] as usize].z);
t2.p[1] = Vector3::new(new_points[curr_face[3] as usize].x, new_points[curr_face[3] as usize].y, new_points[curr_face[3] as usize].z);
t2.p[2] = Vector3::new(new_points[curr_face[0] as usize].x, new_points[curr_face[0] as usize].y, new_points[curr_face[0] as usize].z);
t1.r = [curr_face[0] as usize, curr_face[1] as usize, curr_face[2] as usize];
t2.r = [curr_face[2] as usize, curr_face[3] as usize, curr_face[0] as usize];
self.f.push(t1);
self.f.push(t2);
}
self.v = new_points;
}
}
|
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #F.23 | F# |
// Carmichael Number . Nigel Galloway: November 19th., 2017
let fN n = Seq.collect ((fun g->(Seq.map(fun e->(n,1+(n-1)*(n+g)/e,g,e))){1..(n+g-1)})){2..(n-1)}
let fG (P1,P2,h3,d) =
let mod' n g = (n%g+g)%g
let fN P3 = if isPrime P3 && (P2*P3)%(P1-1)=1 then Some (P1,P2,P3) else None
if isPrime P2 && ((h3+P1)*(P1-1))%d=0 && mod' (-P1*P1) h3=d%h3 then fN (1+P1*P2/h3) else None
let carms g = primes|>Seq.takeWhile(fun n->n<=g)|>Seq.collect fN|>Seq.choose fG
carms 61 |> Seq.iter (fun (P1,P2,P3)->printfn "%2d x %4d x %5d = %10d" P1 P2 P3 ((uint64 P3)*(uint64 (P1*P2))))
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #EchoLisp | EchoLisp |
;; rem : the foldX family always need an initial value
;; fold left a list
(foldl + 0 (iota 10)) ;; 0 + 1 + .. + 9
→ 45
;; fold left a sequence
(lib 'sequences)
(foldl * 1 [ 1 .. 10])
→ 362880 ;; 10!
;; folding left and right
(foldl / 1 ' ( 1 2 3 4))
→ 8/3
(foldr / 1 '(1 2 3 4))
→ 3/8
;;scanl gives the list (or sequence) of intermediate values :
(scanl * 1 '( 1 2 3 4 5))
→ (1 1 2 6 24 120)
|
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Rust | Rust | const LEFT_ALPHABET_CT: &str = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const RIGHT_ALPHABET_PT: &str = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
const ZENITH: usize = 0;
const NADIR: usize = 12;
const SEQUENCE: &str = "WELLDONEISBETTERTHANWELLSAID";
fn cipher(letter: &char, left: &String, right: &String) -> (usize, char) {
let pos = right.find(*letter).unwrap();
let cipher = left.chars().nth(pos).unwrap();
(pos, cipher)
}
fn main() {
let mut left = LEFT_ALPHABET_CT.to_string();
let mut right = RIGHT_ALPHABET_PT.to_string();
let ciphertext = SEQUENCE.chars()
.map(|letter| {
let (pos, cipher_char) = cipher(&letter, &left, &right);
left = format!("{}{}", &left[pos..], &left[..pos]);
left = format!("{}{}{}{}", &left[ZENITH..1], &left[2..NADIR+2], &left[1..2], &left[NADIR+2..]);
if pos != right.len() - 1 {
right = format!("{}{}", &right[pos + 1..], &right[..pos + 1]);
}
right = format!("{}{}{}{}", &right[ZENITH..2], &right[3..NADIR+2], &right[2..3], &right[NADIR+2..]);
cipher_char
})
.collect::<String>();
println!("Plaintext: {}", SEQUENCE);
println!("Ciphertext: {}", ciphertext);
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | nextrow[lastrow_] := Module[{output},
output = ConstantArray[1, Length[lastrow] + 1];
Do[
output[[i + 1]] = lastrow[[i]] + lastrow[[i + 1]];
, {i, 1, Length[lastrow] - 1}];
output
]
pascaltriangle[size_] := NestList[nextrow, {1}, size]
catalannumbers[length_] := Module[{output, basetriangle},
basetriangle = pascaltriangle[2 length];
list1 = basetriangle[[# *2 + 1, # + 1]] & /@ Range[length];
list2 = basetriangle[[# *2 + 1, # + 2]] & /@ Range[length];
list1 - list2
]
(* testing *)
catalannumbers[15] |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #MATLAB_.2F_Octave | MATLAB / Octave | n = 15;
p = pascal(n + 2);
p(n + 4 : n + 3 : end - 1)' - diag(p, 2) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Kotlin | Kotlin | fun main(args: Array<String>) {
val dog = "Benjamin"
val Dog = "Samba"
val DOG = "Bernie"
println("The three dogs are named $dog, $Dog and $DOG")
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Lasso | Lasso |
local(dog = 'Benjamin')
local(Dog = 'Samba')
local(DOG = 'Bernie')
stdoutnl('There is just one dog named ' + #dog)
|
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #FreeBASIC | FreeBASIC | #define MAXLEN 64
type listitem ' An item of a list may be a number
is_num as boolean ' or another list, so I have to account
union ' for both, implemented as a union.
list as any ptr ' FreeBASIC is twitchy about circularly
num as uinteger ' defined types, so one workaround is to
end union ' use a generic pointer that I will cast
end type ' later.
type list
length as uinteger 'simple, fixed storage length lists
item(1 to MAXLEN) as listitem 'are good enough for this example
end type
sub print_list( list as list )
print "{";
if list.length = 0 then print "}"; : return
for i as uinteger = 1 to list.length
if list.item(i).is_num then
print str(list.item(i).num);
else 'recursively print sublist
print_list( *cast(list ptr, list.item(i).list) )
end if
if i<list.length then print ", "; else print "}"; 'handle comma
next i 'gracefully
return
end sub
function cartprod( A as list, B as list ) as list
dim as uinteger i, j
dim as list C
dim as list ptr inner 'for brevity
C.length = 0
for i = 1 to A.length
for j = 1 to B.length
C.length += 1
C.item(C.length).is_num = false 'each item of the new list is a list itself
inner = allocate( sizeof(list) ) 'make space for it
C.item(C.length).list = inner
inner->length = 2 'each inner list contains two items
inner->item(1) = A.item(i) 'one from the first list
inner->item(2) = B.item(j) 'and one from the second
next j
next i
return C
end function
dim as list EMPTY, A, B, R
EMPTY.length = 0
A.length = 2
A.item(1).is_num = true : A.item(1).num = 1
A.item(2).is_num = true : A.item(2).num = 2
B.length = 2
B.item(1).is_num = true : B.item(1).num = 3
B.item(2).is_num = true : B.item(2).num = 4
R = cartprod(A, B)
print_list(R) : print 'print_list does not supply a final newline
R = cartprod(B, A) : print_list(R) : print
R = cartprod(A, EMPTY) : print_list(R) : print
R = cartprod(EMPTY, A) : print_list(R) : print |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.}
Or recursively:
C
0
=
1
and
C
n
+
1
=
∑
i
=
0
n
C
i
C
n
−
i
for
n
≥
0
;
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;}
Or alternatively (also recursive):
C
0
=
1
and
C
n
=
2
(
2
n
−
1
)
n
+
1
C
n
−
1
,
{\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},}
Task
Implement at least one of these algorithms and print out the first 15 Catalan numbers with each.
Memoization is not required, but may be worth the effort when using the second method above.
Related tasks
Catalan numbers/Pascal's triangle
Evaluate binomial coefficients
| #BBC_BASIC | BBC BASIC | 10 FOR i% = 1 TO 15
20 PRINT FNcatalan(i%)
30 NEXT
40 END
50 DEF FNcatalan(n%)
60 IF n% = 0 THEN = 1
70 = 2 * (2 * n% - 1) * FNcatalan(n% - 1) / (n% + 1) |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #ChucK | ChucK |
MyClass myClassObject;
myClassObject.myFunction(some parameter);
|
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance method of a class.
| #Clojure | Clojure | (Long/toHexString 15) ; use forward slash for static methods
(System/currentTimeMillis)
(.equals 1 2) ; use dot operator to call instance methods
(. 1 (equals 2)) ; alternative style |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #BaCon | BaCon | ' Call a dynamic library function
PROTO j0
bessel0 = j0(1.0)
PRINT bessel0
|
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level.
Related task
OpenGL -- OpenGL is usually maintained as a shared library.
| #BBC_BASIC | BBC BASIC | SYS "MessageBox", @hwnd%, "This is a test message", 0, 0
|
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #BASIC | BASIC | 10 DEFINT A-Z
20 N = 4
30 W = 3^(N-1)
40 S = W
50 L$ = STRING$(W, "#")
60 PRINT L$
70 IF S = 1 THEN END
80 S = S\3
90 P = 1
100 IF P >= W-S GOTO 60
110 P = P+S
120 MID$(L$,P,S) = SPACE$(S)
130 P = P+S
140 GOTO 100 |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to use a rational number data type.
It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.
It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:
[a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1]
Example
The fraction 9/4 has odd continued fraction representation 2; 3, 1, giving a binary representation of 100011,
which means 9/4 appears as the 35th term of the sequence.
Task part 2
Find the position of the number 83116/51639 in the Calkin-Wilf sequence.
See also
Wikipedia entry: Calkin-Wilf tree
Continued fraction
Continued fraction/Arithmetic/Construct from rational number
| #AppleScript | AppleScript | -- Return the first n terms of the sequence. Tree generation. Faster for this purpose.
on CalkinWilfSequence(n)
script o
property sequence : {{1, 1}} -- Initialised with the first term ({numerator, denominator}).
end script
-- Work through the growing sequence list, adding the two children of each term to the end and
-- converting each term to text representing the vulgar fraction. Stop adding children halfway through.
set halfway to n div 2
repeat with position from 1 to n
set {numerator, denominator} to item position of o's sequence
if (position ≤ halfway) then
tell numerator + denominator
set end of o's sequence to {numerator, it}
if ((position < halfway) or (position * 2 < n)) then set end of o's sequence to {it, denominator}
end tell
end if
set item position of o's sequence to (numerator as text) & "/" & denominator
end repeat
return o's sequence
end CalkinWilfSequence
-- Alternatively, return terms pos1 to pos2. Binary run-length encoding. Doesn't need to work from the beginning of the sequence.
on CalkinWilfSequence2(pos1, pos2)
script o
property sequence : {}
end script
repeat with position from pos1 to pos2
-- Build a continued fraction list from the binary run-length encoding of this position index.
-- There's no need to put the last value into the list as it's used immediately.
set continuedFraction to {}
set bitValue to 1
set runLength to 0
repeat until (position = 0)
if (position mod 2 = bitValue) then
set runLength to runLength + 1
else
set end of continuedFraction to runLength
set bitValue to (bitValue + 1) mod 2
set runLength to 1
end if
set position to position div 2
end repeat
-- Work out the numerator and denominator from the continued fraction and derive text representing the vulgar fraction.
set numerator to runLength
set denominator to 1
repeat with i from (count continuedFraction) to 1 by -1
tell numerator
set numerator to numerator * (item i of continuedFraction) + denominator
set denominator to it
end tell
end repeat
set end of o's sequence to (numerator as text) & "/" & denominator
end repeat
return o's sequence
end CalkinWilfSequence2
-- Return the sequence position of the term with the given numerator and denominator.
on CalkinWilfSequencePosition(numerator, denominator)
-- Build a continued fraction list from the input.
set continuedFraction to {}
repeat until (denominator is 0)
set end of continuedFraction to numerator div denominator
set {numerator, denominator} to {denominator, numerator mod denominator}
end repeat
-- If it has an even number of entries, convert to the equivalent odd number.
if ((count continuedFraction) mod 2 is 0) then
set last item of continuedFraction to (last item of continuedFraction) - 1
set end of continuedFraction to 1
end if
-- "Binary run-length decode" the entries to get the position index.
set position to 0
set bitValue to 1
repeat with i from (count continuedFraction) to 1 by -1
repeat (item i of continuedFraction) times
set position to position * 2 + bitValue
end repeat
set bitValue to (bitValue + 1) mod 2
end repeat
return position
end CalkinWilfSequencePosition
-- Task code:
local sequenceResult1, sequenceResult2, positionResult, output, astid
set sequenceResult1 to CalkinWilfSequence(20)
set sequenceResult2 to CalkinWilfSequence2(1, 20)
set positionResult to CalkinWilfSequencePosition(83116, 51639)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set output to "First twenty terms of sequence using tree generation:" & (linefeed & sequenceResult1)
set output to output & (linefeed & "Ditto using binary run-length encoding:") & (linefeed & sequenceResult1)
set AppleScript's text item delimiters to astid
set output to output & (linefeed & "83116/51639 is term number " & positionResult)
return output |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #MATLAB_.2F_Octave | MATLAB / Octave | BWImage = edge(GrayscaleImage,'canny'); |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) and its magnitude
G
{\displaystyle G}
:
G
=
G
x
2
+
G
y
2
{\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}}
May be performed by convolution of an image with Sobel operators.
Non-maximum suppression.
For each pixel compute the orientation of intensity gradient vector:
θ
=
a
t
a
n
2
(
G
y
,
G
x
)
{\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)}
.
Transform angle
θ
{\displaystyle \theta }
to one of four directions: 0, 45, 90, 135 degrees.
Compute new array
N
{\displaystyle N}
: if
G
(
p
a
)
<
G
(
p
)
<
G
(
p
b
)
{\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)}
where
p
{\displaystyle p}
is the current pixel,
p
a
{\displaystyle p_{a}}
and
p
b
{\displaystyle p_{b}}
are the two neighbour pixels in the direction of gradient,
then
N
(
p
)
=
G
(
p
)
{\displaystyle N(p)=G(p)}
, otherwise
N
(
p
)
=
0
{\displaystyle N(p)=0}
.
Nonzero pixels in resulting array correspond to local maxima of
G
{\displaystyle G}
in direction
θ
(
p
)
{\displaystyle \theta (p)}
.
Tracing edges with hysteresis.
At this stage two thresholds for the values of
G
{\displaystyle G}
are introduced:
T
m
i
n
{\displaystyle T_{min}}
and
T
m
a
x
{\displaystyle T_{max}}
.
Starting from pixels with
N
(
p
)
⩾
T
m
a
x
{\displaystyle N(p)\geqslant T_{max}}
,
find all paths of pixels with
N
(
p
)
⩾
T
m
i
n
{\displaystyle N(p)\geqslant T_{min}}
and put them to the resulting image.
| #Nim | Nim | import lenientops
import math
import nimPNG
const MaxBrightness = 255
type Pixel = int16 # Used instead of byte to be able to store negative values.
#---------------------------------------------------------------------------------------------------
func convolution*[normalize: static bool](input: seq[Pixel]; output: var seq[Pixel];
kernel: seq[float]; nx, ny, kn: int) =
## Do a convolution.
## If normalize is true, map pixels to range 0...maxBrightness.
doAssert kernel.len == kn * kn
doAssert (kn and 1) == 1
doAssert nx > kn and ny > kn
doAssert input.len == output.len
let khalf = kn div 2
when normalize:
var pMin = float.high
var pMax = -float.high
for m in khalf..<(nx - khalf):
for n in khalf..<(ny - khalf):
var pixel = 0.0
var c = 0
for j in -khalf..khalf:
for i in -khalf..khalf:
pixel += input[(n - j) * nx + m - i] * kernel[c]
inc c
if pixel < pMin:
pMin = pixel
if pixel > pMax:
pMax = pixel
for m in khalf..<(nx - khalf):
for n in khalf..<(ny - khalf):
var pixel = 0.0
var c = 0
for j in -khalf..khalf:
for i in -khalf..khalf:
pixel += input[(n - j) * nx + m - i] * kernel[c]
inc c
when normalize:
pixel = MaxBrightness * (pixel - pMin) / (pMax - pMin)
output[n * nx + m] = Pixel(pixel)
#---------------------------------------------------------------------------------------------------
func gaussianFilter(input: seq[Pixel]; output: var seq[Pixel]; nx, ny: int; sigma: float) =
## Apply a gaussian filter.
doAssert input.len == output.len
let n = 2 * (2 * sigma).toInt + 3
let mean = floor(n / 2)
var kernel = newSeq[float](n * n)
var c = 0
for i in 0..<n:
for j in 0..<n:
kernel[c] = exp(-0.5 * (((i - mean) / sigma) ^ 2 + ((j - mean) / sigma) ^ 2)) /
(2 * PI * sigma * sigma)
inc c
convolution[true](input, output, kernel, nx, ny, n)
#---------------------------------------------------------------------------------------------------
proc cannyEdgeDetection(input: seq[Pixel];
nx, ny: int;
tmin, tmax: int;
sigma: float): seq[byte] =
## Detect edges.
var output = newSeq[Pixel](input.len)
gaussianFilter(input, output, nx, ny, sigma)
const Gx = @[float -1, 0, 1,
-2, 0, 2,
-1, 0, 1]
var afterGx = newSeq[Pixel](input.len)
convolution[false](input, afterGx, Gx, nx, ny, 3)
const Gy = @[float 1, 2, 1,
0, 0, 0,
-1, -2, -1]
var afterGy = newSeq[Pixel](input.len)
convolution[false](input, afterGy, Gy, nx, ny, 3)
var g = newSeq[Pixel](input.len)
for i in 1..(nx - 2):
for j in 1..(ny - 2):
let c = i + nx * j
g[c] = hypot(afterGx[c].toFloat, afterGy[c].toFloat).Pixel
# Non-maximum suppression: straightforward implementation.
var nms = newSeq[Pixel](input.len)
for i in 1..(nx - 2):
for j in 1..(ny - 2):
let
c = i + nx * j
nn = c - nx
ss = c + nx
ww = c + 1
ee = c - 1
nw = nn + 1
ne = nn - 1
sw = ss + 1
se = ss - 1
let aux = arctan2(afterGy[c].toFloat, afterGx[c].toFloat) + PI
let dir = aux mod PI / PI * 8
if (((dir <= 1 or dir > 7) and g[c] > g[ee] and g[c] > g[ww]) or # O°.
((dir > 1 and dir <= 3) and g[c] > g[nw] and g[c] > g[se]) or # 45°.
((dir > 3 and dir <= 5) and g[c] > g[nn] and g[c] > g[ss]) or # 90°.
((dir > 5 and dir <= 7) and g[c] > g[ne] and g[c] > g[sw])): # 135°.
nms[c] = g[c]
else:
nms[c] = 0
# Tracing edges with hysteresis. Non-recursive implementation.
var edges = newSeq[int](input.len div 2)
for item in output.mitems: item = 0
var c = 0
for j in 1..(ny - 2):
for i in 1..(nx - 2):
inc c
if nms[c] >= tMax and output[c] == 0:
# Trace edges.
output[c] = MaxBrightness
var nedges = 1
edges[0] = c
while nedges > 0:
dec nedges
let t = edges[nedges]
let neighbors = [t - nx, # nn.
t + nx, # ss.
t + 1, # ww.
t - 1, # ee.
t - nx + 1, # nw.
t - nx - 1, # ne.
t + nx + 1, # sw.
t + nx - 1] # se.
for n in neighbors:
if nms[n] >= tMin and output[n] == 0:
output[n] = MaxBrightness
edges[nedges] = n
inc nedges
# Store the result as a sequence of bytes.
result = newSeqOfCap[byte](output.len)
for val in output:
result.add(byte(val))
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
const
Input = "Valve.png"
Output = "Valve_edges.png"
let pngImage = loadPNG24(seq[byte], Input).get()
# Convert to grayscale and store luminances as 16 bits signed integers.
var pixels = newSeq[Pixel](pngImage.width * pngImage.height)
for i in 0..pixels.high:
pixels[i] = Pixel(0.2126 * pngImage.data[3 * i] +
0.7152 * pngImage.data[3 * i + 1] +
0.0722 * pngImage.data[3 * i + 2] + 0.5)
# Find edges.
let data = cannyEdgeDetection(pixels, pngImage.width, pngImage.height, 45, 50, 1.0)
# Save result as a PNG image.
let status = savePNG(Output, data, LCT_GREY, 8, pngImage.width, pngImage.height)
if status.isOk:
echo "File ", Input, " processed. Result is available in file ", Output
else:
echo "Error: ", status.error |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #J | J | cidr=: {{
'a e'=. 0 ".each (y rplc'. ')-.&;:'/'
('/',":e),~rplc&' .'":_8#.\32{.e{.,(8#2)#:a
}} |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given 87.70.141.1/22, your code should output 87.70.140.0/22
Explanation
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization.
The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0.
More examples for testing
36.18.154.103/12 → 36.16.0.0/12
62.62.197.11/29 → 62.62.197.8/29
67.137.119.181/4 → 64.0.0.0/4
161.214.74.21/24 → 161.214.74.0/24
184.232.176.184/18 → 184.232.128.0/18
| #Java | Java | import java.text.MessageFormat;
import java.text.ParseException;
public class CanonicalizeCIDR {
public static void main(String[] args) {
for (String test : TESTS) {
try {
CIDR cidr = new CIDR(test);
System.out.printf("%-18s -> %s\n", test, cidr.toString());
} catch (Exception ex) {
System.err.printf("Error parsing '%s': %s\n", test, ex.getLocalizedMessage());
}
}
}
private static class CIDR {
private CIDR(int address, int maskLength) {
this.address = address;
this.maskLength = maskLength;
}
private CIDR(String str) throws Exception {
Object[] args = new MessageFormat(FORMAT).parse(str);
int address = 0;
for (int i = 0; i < 4; ++i) {
int a = ((Number)args[i]).intValue();
if (a < 0 || a > 255)
throw new Exception("Invalid IP address");
address <<= 8;
address += a;
}
int maskLength = ((Number)args[4]).intValue();
if (maskLength < 1 || maskLength > 32)
throw new Exception("Invalid mask length");
int mask = ~((1 << (32 - maskLength)) - 1);
this.address = address & mask;
this.maskLength = maskLength;
}
public String toString() {
int address = this.address;
int d = address & 0xFF;
address >>= 8;
int c = address & 0xFF;
address >>= 8;
int b = address & 0xFF;
address >>= 8;
int a = address & 0xFF;
Object[] args = { a, b, c, d, maskLength };
return new MessageFormat(FORMAT).format(args);
}
private int address;
private int maskLength;
private static final String FORMAT = "{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}";
};
private static final String[] TESTS = {
"87.70.141.1/22",
"36.18.154.103/12",
"62.62.197.11/29",
"67.137.119.181/4",
"161.214.74.21/24",
"184.232.176.184/18"
};
} |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)).
note that
318682
{\displaystyle 318682}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
);
note that
101558217124
{\displaystyle 101558217124}
has the same checksum as (
101558
+
217124
{\displaystyle 101558+217124}
) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
note that this implies that for Kaprekar numbers the checksum of
k
{\displaystyle k}
equals the checksum of
k
2
{\displaystyle k^{2}}
.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property
c
o
9
(
k
)
=
c
o
9
(
k
2
)
{\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
is the residual of
x
{\displaystyle x}
mod
9
{\displaystyle 9}
;
the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property
k
%
(
B
a
s
e
−
1
)
==
(
k
2
)
%
(
B
a
s
e
−
1
)
{\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)}
and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
related tasks
First perfect square in base N with N unique digits
Kaprekar numbers
| #J | J | castout=: 1 :0
[: (#~ ] =&((m-1)&|) *:) <. + [: i. (+*)@-~
) |
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface | Catmull–Clark subdivision surface | Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals.
The process for computing the new locations of the points works as follows when the surface is free of holes:
Starting cubic mesh; the meshes below are derived from this.
After one round of the Catmull-Clark algorithm applied to a cubic mesh.
After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical.
for each face, a face point is created which is the average of all the points of the face.
for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces.
for each vertex point, its coordinates are updated from (new_coords):
the old coordinates (old_coords),
the average of the face points of the faces the point belongs to (avg_face_points),
the average of the centers of edges the point belongs to (avg_mid_edges),
how many faces a point belongs to (n), then use this formula:
m1 = (n - 3) / n
m2 = 1 / n
m3 = 2 / n
new_coords = (m1 * old_coords)
+ (m2 * avg_face_points)
+ (m3 * avg_mid_edges)
Then each face is replaced by new faces made with the new points,
for a triangle face (a,b,c):
(a, edge_pointab, face_pointabc, edge_pointca)
(b, edge_pointbc, face_pointabc, edge_pointab)
(c, edge_pointca, face_pointabc, edge_pointbc)
for a quad face (a,b,c,d):
(a, edge_pointab, face_pointabcd, edge_pointda)
(b, edge_pointbc, face_pointabcd, edge_pointab)
(c, edge_pointcd, face_pointabcd, edge_pointbc)
(d, edge_pointda, face_pointabcd, edge_pointcd)
When there is a hole, we can detect it as follows:
an edge is the border of a hole if it belongs to only one face,
a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to.
On the border of a hole the subdivision occurs as follows:
for the edges that are on the border of a hole, the edge point is just the middle of the edge.
for the vertex points that are on the border of a hole, the new coordinates are calculated as follows:
in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole
calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary).
For edges and vertices not next to a hole, the standard algorithm from above is used.
| #Tcl | Tcl | package require Tcl 8.5
# Use math functions and operators as commands (Lisp-like).
namespace path {tcl::mathfunc tcl::mathop}
# Add 3 points.
proc add3 {A B C} {
lassign $A Ax Ay Az
lassign $B Bx By Bz
lassign $C Cx Cy Cz
list [+ $Ax $Bx $Cx] [+ $Ay $By $Cy] [+ $Az $Bz $Cz]
}
# Multiply a point by a constant.
proc mulC {m A} {
lassign $A x y z
list [* $m $x] [* $m $y] [* $m $z]
}
# Take the centroid of a set of points.
# Note that each of the arguments is a *list* of coordinate triples
# This makes things easier later.
proc centroid args {
set x [set y [set z 0.0]]
foreach plist $args {
incr n [llength $plist]
foreach p $plist {
lassign $p px py pz
set x [+ $x $px]
set y [+ $y $py]
set z [+ $z $pz]
}
}
set n [double $n]
list [/ $x $n] [/ $y $n] [/ $z $n]
}
# Select from the list the value from each of the indices in the *lists*
# in the trailing arguments.
proc selectFrom {list args} {
foreach is $args {foreach i $is {lappend r [lindex $list $i]}}
return $r
}
# Rotate a list.
proc lrot {list {n 1}} {
set n [% $n [llength $list]]
list {*}[lrange $list $n end] {*}[lrange $list 0 [incr n -1]]
}
# Generate an edge by putting the smaller coordinate index first.
proc edge {a b} {
list [min $a $b] [max $a $b]
}
# Perform one step of Catmull-Clark subdivision of a surface.
proc CatmullClark {points faces} {
# Generate the new face-points and list of edges, plus some lookup tables.
set edges {}
foreach f $faces {
set ps [selectFrom $points $f]
set fp [centroid $ps]
lappend facepoints $fp
foreach p $ps {
lappend fp4p($p) $fp
}
foreach p1 $f p2 [lrot $f] {
set e [edge $p1 $p2]
if {$e ni $edges} {
lappend edges $e
}
lappend fp4e($e) $fp
}
}
# Generate the new edge-points and mid-points of edges, and a few more
# lookup tables.
set i [+ [llength $points] [llength $faces]]
foreach e $edges {
set ep [selectFrom $points $e]
if {[llength $fp4e($e)] > 1} {
set mid [centroid $ep $fp4e($e)]
} else {
set mid [centroid $ep]
foreach p $ep {
lappend ep_heavy($p) $mid
}
}
lappend edgepoints $mid
set en4e($e) $i
foreach p $ep {
lappend ep4p($p) $mid
}
incr i
}
# Generate the new vertex points with our lookup tables.
foreach p $points {
if {[llength $fp4p($p)] >= 4} {
set n [llength $fp4p($p)]
lappend newPoints [add3 [mulC [/ [- $n 3.0] $n] $p] \
[mulC [/ 1.0 $n] [centroid $fp4p($p)]] \
[mulC [/ 2.0 $n] [centroid $ep4p($p)]]]
} else {
# Update a point on the edge of a hole. This formula is not
# described on the WP page, but produces a nice result.
lappend newPoints [centroid $ep_heavy($p) [list $p $p]]
}
}
# Now compute the new set of quadrilateral faces.
set i [llength $points]
foreach f $faces {
foreach a $f b [lrot $f] c [lrot $f -1] {
lappend newFaces [list \
$a $en4e([edge $a $b]) $i $en4e([edge $c $a])]
}
incr i
}
list [concat $newPoints $facepoints $edgepoints] $newFaces
} |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #Factor | Factor | USING: formatting kernel locals math math.primes math.ranges
sequences ;
IN: rosetta-code.carmichael
:: carmichael ( p1 -- )
1 p1 (a,b) [| h3 |
h3 p1 + [1,b) [| d |
h3 p1 + p1 1 - * d mod zero?
p1 neg p1 * h3 rem d h3 mod = and
[
p1 1 - h3 p1 + * d /i 1 + :> p2
p1 p2 * h3 /i 1 + :> p3
p2 p3 [ prime? ] both?
p2 p3 * p1 1 - mod 1 = and
[ p1 p2 p3 "%d %d %d\n" printf ] when
] when
] each
] each
;
: carmichael-demo ( -- ) 61 primes-upto [ carmichael ] each ;
MAIN: carmichael-demo |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a method based on Carmichael numbers, as suggested in Notes by G.J.O Jameson March 2010.
Task
Find Carmichael numbers of the form:
Prime1 × Prime2 × Prime3
where (Prime1 < Prime2 < Prime3) for all Prime1 up to 61.
(See page 7 of Notes by G.J.O Jameson March 2010 for solutions.)
Pseudocode
For a given
P
r
i
m
e
1
{\displaystyle Prime_{1}}
for 1 < h3 < Prime1
for 0 < d < h3+Prime1
if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3
then
Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d)
next d if Prime2 is not prime
Prime3 = 1 + (Prime1*Prime2/h3)
next d if Prime3 is not prime
next d if (Prime2*Prime3) mod (Prime1-1) not equal 1
Prime1 * Prime2 * Prime3 is a Carmichael Number
related task
Chernick's Carmichael numbers
| #Fortran | Fortran | LOGICAL FUNCTION ISPRIME(N) !Ad-hoc, since N is not going to be big...
INTEGER N !Despite this intimidating allowance of 32 bits...
INTEGER F !A possible factor.
ISPRIME = .FALSE. !Most numbers aren't prime.
DO F = 2,SQRT(DFLOAT(N)) !Wince...
IF (MOD(N,F).EQ.0) RETURN !Not even avoiding even numbers beyond two.
END DO !Nice and brief, though.
ISPRIME = .TRUE. !No factor found.
END FUNCTION ISPRIME !So, done. Hopefully, not often.
PROGRAM CHASE
INTEGER P1,P2,P3 !The three primes to be tested.
INTEGER H3,D !Assistants.
INTEGER MSG !File unit number.
MSG = 6 !Standard output.
WRITE (MSG,1) !A heading would be good.
1 FORMAT ("Carmichael numbers that are the product of three primes:"
& /" P1 x P2 x P3 =",9X,"C")
DO P1 = 2,61 !Step through the specified range.
IF (ISPRIME(P1)) THEN !Selecting only the primes.
DO H3 = 2,P1 - 1 !For 1 < H3 < P1.
DO D = 1,H3 + P1 - 1 !For 0 < D < H3 + P1.
IF (MOD((H3 + P1)*(P1 - 1),D).EQ.0 !Filter.
& .AND. (MOD(H3 + MOD(-P1**2,H3),H3) .EQ. MOD(D,H3))) THEN !Beware MOD for negative numbers! MOD(-P1**2, may surprise...
P2 = 1 + (P1 - 1)*(H3 + P1)/D !Candidate for the second prime.
IF (ISPRIME(P2)) THEN !Is it prime?
P3 = 1 + P1*P2/H3 !Yes. Candidate for the third prime.
IF (ISPRIME(P3)) THEN !Is it prime?
IF (MOD(P2*P3,P1 - 1).EQ.1) THEN !Yes! Final test.
WRITE (MSG,2) P1,P2,P3, INT8(P1)*P2*P3 !Result!
2 FORMAT (3I6,I12)
END IF
END IF
END IF
END IF
END DO
END DO
END IF
END DO
END |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.