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/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Stretch_2 | Stretch 2 |
ListPlot[MarblePositions[#][Transpose[{dxs,dys}]]&/@Range[4],PlotLegends->PointLegend[{1,2,3,4}],AspectRatio->Automatic,ImageSize->600]
|
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Nim | Nim | import stats, strformat
type Rule = proc(x, y: float): float
const Dxs = [-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087]
const Dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032]
func funnel(a: openArray[float]; rule: Rule): seq[float] =
var x = 0.0
result.setlen(a.len)
for i, val in a:
result[i] = x + val
x = rule(x, val)
proc experiment(label: string; r: Rule) =
let rxs = funnel(Dxs, r)
let rys = funnel(Dys, r)
echo label
echo fmt"Mean x, y : {rxs.mean:7.4f} {rys.mean:7.4f}"
echo fmt"Std dev x, y : {rxs.standardDeviation:7.4f} {rys.standardDeviation:7.4f}"
echo ""
experiment("Rule 1", proc(z, dz: float): float = 0.0)
experiment("Rule 2", proc(z, dz: float): float = -dz)
experiment("Rule 3", proc(z, dz: float): float = -(z + dz))
experiment("Rule 4", proc(z, dz: float): float = z + dz) |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Arturo | Arturo | loop 1..7 'x [
loop 1..7 'y [
loop 1..7 'z [
if all? @[
even? x
12 = sum @[x y z]
3 = size unique @[x y z]
] -> print [x y z]
]
]
] |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Dart | Dart | class Delegator {
var delegate;
String operation() {
if (delegate == null)
return "default implementation";
else
return delegate.thing();
}
}
class Delegate {
String thing() => "delegate implementation";
}
main() {
// Without a delegate:
Delegator a = new Delegator();
Expect.equals("default implementation",a.operation());
// any object doesn't work unless we can check for existing methods
// a.delegate=new Object();
// Expect.equals("default implementation",a.operation());
// With a delegate:
Delegate d = new Delegate();
a.delegate = d;
Expect.equals("delegate implementation",a.operation());
} |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Delphi | Delphi | unit Printer;
interface
type
// the "delegate"
TRealPrinter = class
public
procedure Print;
end;
// the "delegator"
TPrinter = class
private
FPrinter: TRealPrinter;
public
constructor Create;
destructor Destroy; override;
procedure Print;
end;
implementation
{ TRealPrinter }
procedure TRealPrinter.Print;
begin
Writeln('Something...');
end;
{ TPrinter }
constructor TPrinter.Create;
begin
inherited Create;
FPrinter:= TRealPrinter.Create;
end;
destructor TPrinter.Destroy;
begin
FPrinter.Free;
inherited;
end;
procedure TPrinter.Print;
begin
FPrinter.Print;
end;
end. |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #Java | Java | import java.util.function.BiFunction;
public class TriangleOverlap {
private static class Pair {
double first;
double second;
Pair(double first, double second) {
this.first = first;
this.second = second;
}
@Override
public String toString() {
return String.format("(%s, %s)", first, second);
}
}
private static class Triangle {
Pair p1, p2, p3;
Triangle(Pair p1, Pair p2, Pair p3) {
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
@Override
public String toString() {
return String.format("Triangle: %s, %s, %s", p1, p2, p3);
}
}
private static double det2D(Triangle t) {
Pair p1 = t.p1;
Pair p2 = t.p2;
Pair p3 = t.p3;
return p1.first * (p2.second - p3.second)
+ p2.first * (p3.second - p1.second)
+ p3.first * (p1.second - p2.second);
}
private static void checkTriWinding(Triangle t, boolean allowReversed) {
double detTri = det2D(t);
if (detTri < 0.0) {
if (allowReversed) {
Pair a = t.p3;
t.p3 = t.p2;
t.p2 = a;
} else throw new RuntimeException("Triangle has wrong winding direction");
}
}
private static boolean boundaryCollideChk(Triangle t, double eps) {
return det2D(t) < eps;
}
private static boolean boundaryDoesntCollideChk(Triangle t, double eps) {
return det2D(t) <= eps;
}
private static boolean triTri2D(Triangle t1, Triangle t2) {
return triTri2D(t1, t2, 0.0, false, true);
}
private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed) {
return triTri2D(t1, t2, eps, allowedReversed, true);
}
private static boolean triTri2D(Triangle t1, Triangle t2, double eps, boolean allowedReversed, boolean onBoundary) {
// Triangles must be expressed anti-clockwise
checkTriWinding(t1, allowedReversed);
checkTriWinding(t2, allowedReversed);
// 'onBoundary' determines whether points on boundary are considered as colliding or not
BiFunction<Triangle, Double, Boolean> chkEdge = onBoundary ? TriangleOverlap::boundaryCollideChk : TriangleOverlap::boundaryDoesntCollideChk;
Pair[] lp1 = new Pair[]{t1.p1, t1.p2, t1.p3};
Pair[] lp2 = new Pair[]{t2.p1, t2.p2, t2.p3};
// for each edge E of t1
for (int i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
// Check all points of t2 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[0]), eps) &&
chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[1]), eps) &&
chkEdge.apply(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false;
}
// for each edge E of t2
for (int i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
// Check all points of t1 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[0]), eps) &&
chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[1]), eps) &&
chkEdge.apply(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false;
}
// The triangles overlap
return true;
}
public static void main(String[] args) {
Triangle t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));
Triangle t2 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 6.0));
System.out.printf("%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
// need to allow reversed for this pair to avoid exception
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(0.0, 5.0), new Pair(5.0, 0.0));
t2 = t1;
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2, 0.0, true)) {
System.out.println("overlap (reversed)");
} else {
System.out.println("do not overlap");
}
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(5.0, 0.0), new Pair(0.0, 5.0));
t2 = new Triangle(new Pair(-10.0, 0.0), new Pair(-5.0, 0.0), new Pair(-1.0, 6.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t1.p3 = new Pair(2.5, 5.0);
t2 = new Triangle(new Pair(0.0, 4.0), new Pair(2.5, -1.0), new Pair(5.0, 4.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 1.0), new Pair(0.0, 2.0));
t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, 0.0), new Pair(3.0, 2.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t2 = new Triangle(new Pair(2.0, 1.0), new Pair(3.0, -2.0), new Pair(3.0, 4.0));
System.out.printf("\n%s and\n%s\n", t1, t2);
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
t1 = new Triangle(new Pair(0.0, 0.0), new Pair(1.0, 0.0), new Pair(0.0, 1.0));
t2 = new Triangle(new Pair(1.0, 0.0), new Pair(2.0, 0.0), new Pair(1.0, 1.1));
System.out.printf("\n%s and\n%s\n", t1, t2);
System.out.println("which have only a single corner in contact, if boundary points collide");
if (triTri2D(t1, t2)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
System.out.printf("\n%s and\n%s\n", t1, t2);
System.out.println("which have only a single corner in contact, if boundary points do not collide");
if (triTri2D(t1, t2, 0.0, false, false)) {
System.out.println("overlap");
} else {
System.out.println("do not overlap");
}
}
} |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #C.2B.2B | C++ | #include <cstdio>
#include <direct.h>
int main() {
remove( "input.txt" );
remove( "/input.txt" );
_rmdir( "docs" );
_rmdir( "/docs" );
return 0;
} |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Clojure | Clojure | (import '(java.io File))
(.delete (File. "output.txt"))
(.delete (File. "docs"))
(.delete (new File (str (File/separator) "output.txt")))
(.delete (new File (str (File/separator) "docs"))) |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #J | J | i. 5 5
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24 |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #Java | Java | import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && j<y){
result[i][j] = a[i+1][j];
}else if(i<x && j>=y){
result[i][j] = a[i][j+1];
}else{ //i>x && j>y
result[i][j] = a[i+1][j+1];
}
}
return result;
}
public static double det(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
int sign = 1;
double sum = 0;
for(int i=0;i<a.length;i++){
sum += sign * a[0][i] * det(minor(a,0,i));
sign *= -1;
}
return sum;
}
}
public static double perm(double[][] a){
if(a.length == 1){
return a[0][0];
}else{
double sum = 0;
for(int i=0;i<a.length;i++){
sum += a[0][i] * perm(minor(a,0,i));
}
return sum;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
double[][] a = new double[size][size];
for(int i=0;i<size;i++) for(int j=0;j<size;j++){
a[i][j] = sc.nextDouble();
}
sc.close();
System.out.println("Determinant: "+det(a));
System.out.println("Permanent: "+perm(a));
}
} |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Eiffel | Eiffel | class MAIN
creation main
feature main is
local
x, y: INTEGER;
retried: BOOLEAN;
do
x := 42;
y := 0;
if not retried then
io.put_real(x / y);
else
print("NaN%N");
end
rescue
print("Caught division by zero!%N");
retried := True;
retry
end
end |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Ela | Ela | open core number
x /. y = try Some (x `div` y) with
_ = None
(12 /. 2, 12 /. 0) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #COBOL | COBOL | program-id. is-numeric.
procedure division.
display function test-numval-f("abc") end-display
display function test-numval-f("-123.01E+3") end-display
if function test-numval-f("+123.123") equal zero then
display "is numeric" end-display
else
display "failed numval-f test" end-display
end-if
goback. |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #CoffeeScript | CoffeeScript |
console.log (isFinite(s) for s in [5, "5", "-5", "5", "5e5", 0]) # all true
console.log (isFinite(s) for s in [NaN, "fred", "###"]) # all false
|
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: formatting fry generalizations io kernel math.parser
sequences sets ;
: repeated ( elt seq -- )
[ dup >hex over ] dip indices first2
" '%c' (0x%s) at indices %d and %d.\n" printf ;
: uniqueness-report ( str -- )
dup dup length "%u — length %d — contains " printf
[ duplicates ] keep over empty?
[ 2drop "all unique characters." print ]
[ "repeated characters:" print '[ _ repeated ] each ] if ;
""
"."
"abcABC"
"XYZ ZYX"
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"
[ uniqueness-report nl ] 5 napply |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fortran | Fortran |
program demo_verify
implicit none
call nodup('')
call nodup('.')
call nodup('abcABC')
call nodup('XYZ ZYX')
call nodup('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')
contains
subroutine nodup(str)
character(len=*),intent(in) :: str
character(len=*),parameter :: g='(*(g0))'
character(len=:),allocatable :: ch
integer :: where
integer :: i
where=0
ch=''
do i=1,len(str)-1
ch=str(i:i)
where=index(str(i+1:),ch)
if(where.ne.0)then
where=where+i
exit
endif
enddo
if(where.eq.0)then
write(*,g)'STR: "',str,'"',new_line('a'),'LEN: ',len(str),'. No duplicate characters found'
else
write(*,g)'STR: "',str,'"'
write(*,'(a,a,t1,a,a)')repeat(' ',where+5),'^',repeat(' ',i+5),'^'
write(*,g)'LEN: ',len(str), &
& '. Duplicate chars. First duplicate at positions ',i,' and ',where, &
& ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
endif
write(*,*)
end subroutine nodup
function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
hexstr=repeat(' ',100)
write(hexstr,'(Z0)')ch
hexstr=trim(hexstr)
end function hex
end program demo_verify
|
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ksh | Ksh |
#!/bin/ksh
# Determine if a string is collapsible (repeated letters)
# # Variables:
#
typeset -a strings
strings[0]=""
strings[1]='"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln'
strings[2]="..1111111111111111111111111111111111111111111111111111111111111117777888"
strings[3]="I never give 'em hell, I just tell the truth, and they think it's hell."
strings[4]=" --- Harry S Truman"
typeset -a Guillemet=( "«««" "»»»" )
# # Functions:
#
# # Function _collapse(str) - return colapsed version of str
#
function _collapse {
typeset _str ; _str="$1"
typeset _i _buff ; integer _i
for ((_i=1; _i<${#_str}; _i++)); do
if [[ "${_str:$((_i-1)):1}" == "${_str:${_i}:1}" ]]; then
continue
else
_buff+=${_str:$((_i-1)):1}
fi
done
[[ "${_str:$((_i-1)):1}" != "${_str:${_i}:1}" ]] && _buff+=${_str:$((_i-1)):1}
echo "${_buff}"
}
######
# main #
######
for ((i=0; i<${#strings[*]}; i++)); do
str=$(_collapse "${strings[i]}")
print ${#strings[i]} "${Guillemet[0]}${strings[i]}${Guillemet[1]}"
print ${#str} "${Guillemet[0]}${str}${Guillemet[1]}\n"
done |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lua | Lua | function collapse(s)
local ns = ""
local last = nil
for c in s:gmatch"." do
if last then
if last ~= c then
ns = ns .. c
end
last = c
else
ns = ns .. c
last = c
end
end
return ns
end
function test(s)
print("old: " .. s:len() .. " <<<" .. s .. ">>>")
local a = collapse(s)
print("new: " .. a:len() .. " <<<" .. a .. ">>>")
end
function main()
test("")
test("The better the 4-wheel drive, the further you'll be from help when ya get stuck!")
test("headmistressship")
test("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ")
test("..1111111111111111111111111111111111111111111111111111111111111117777888")
test("I never give 'em hell, I just tell the truth, and they think it's hell. ")
test(" --- Harry S Truman ")
end
main() |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #J | J |
Doc=: 2 : 'u :: (n"_)'
task=: monad define
common=. (; #) y NB. the string and its length
if. same y do.
common , <'same'
else.
i =. differ y
c =. i { y
common , <((, (' (' , ') ' ,~ hex))c),'differs at index ',":i
end.
)
hex=: ((Num_j_,26}.Alpha_j_) {~ 16 16 #: a.&i.)&> Doc 'convert ASCII literals to hex representation'
assert '61' -: hex 'a'
|
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Java | Java | public class Main{
public static void main(String[] args){
String[] tests = {"", " ", "2", "333", ".55", "tttTTT", "4444 444k"};
for(String s:tests)
analyze(s);
}
public static void analyze(String s){
System.out.printf("Examining [%s] which has a length of %d:\n", s, s.length());
if(s.length() > 1){
char firstChar = s.charAt(0);
int lastIndex = s.lastIndexOf(firstChar);
if(lastIndex != 0){
System.out.println("\tNot all characters in the string are the same.");
System.out.printf("\t'%c' (0x%x) is different at position %d\n", firstChar, (int) firstChar, lastIndex);
return;
}
}
System.out.println("\tAll characters in the string are the same.");
}
} |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Oz | Oz | declare
Philosophers = [aristotle kant spinoza marx russell]
proc {Start}
Forks = {MakeList {Length Philosophers}}
in
{ForAll Forks NewFork}
for
Name in Philosophers
LeftFork in Forks
RightFork in {RightShift Forks}
do
thread
{Philosopher Name LeftFork RightFork}
end
end
end
proc {Philosopher Name LeftFork RightFork}
for do
{ShowInfo Name#" is hungry."}
{TakeForks [LeftFork RightFork]}
{ShowInfo Name#" got forks."}
{WaitRandom}
{ReleaseFork LeftFork}
{ReleaseFork RightFork}
{ShowInfo Name#" is thinking."}
{WaitRandom}
end
end
proc {WaitRandom}
{Delay 1000 + {OS.rand} mod 4000} %% 1-5 seconds
end
proc {TakeForks Forks}
{ForAll Forks WaitForFork}
case {TryAtomically proc {$}
{ForAll Forks TakeFork}
end}
of true then
{ForAll Forks InitForkNotifier}
[] false then
{TakeForks Forks}
end
end
%%
%% Fork type
%%
%% A fork is a mutable reference to a pair
fun {NewFork}
{NewCell
unit(taken:_ %% a fork is taken by setting this value to a unique value
notify:unit %% to wait for a taken fork
)}
end
proc {TakeFork F}
(@F).taken = {NewName}
end
proc {InitForkNotifier F}
%% we cannot do this in TakeFork
%% because side effect are not allowed in subordinate spaces
New Old
in
{Exchange F Old New}
New = unit(taken:Old.taken notify:_)
end
proc {ReleaseFork F}
New Old
in
{Exchange F Old New}
New = unit(taken:_ notify:unit)
Old.notify = unit %% notify waiters
end
proc {WaitForFork F}
{Wait (@F).notify} %% returns immediatly if fork is free, otherwise blocks
end
%%
%% Helpers
%%
%% Implements transactions on data flow variables
%% with computation spaces. Returns success.
fun {TryAtomically P}
try
S = {Space.new
proc {$ Sync}
{P}
Sync = unit
end}
in
{Space.askVerbose S} \= failed = true
{Wait {Space.merge S}}
true
catch _ then
false
end
end
fun {RightShift Xs} %% circular
case Xs of nil then nil
else {Append Xs.2 [Xs.1]}
end
end
ShowInfo = System.showInfo
in
{Start} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Pascal | Pascal |
program ddate;
{
This program is free software, it's done it's time
and paid for it's crime. You can copy, edit and use this
software under the terms of the GNU GPL v3 or later.
Copyright Pope Englebert Finklestien,
On this day Boomtime, the 71st day of Confusion in the YOLD 3183
This program will print out the current date in Erisian format as specified in
P R I N C I P I A D I S C O R D I A
If you run it with a date it the command line in european format (dd mm yy) it
will print the equvolent Discordian date. If you omit the year and month the
current Anerisiean month and year as assumed.
POPE Englebert Finklestien.
}
uses Sysutils;
var
YY,MM,DD : word;
YOLD : Boolean;
Hedgehog: integer;
Eris: string;
snub: string;
chaotica: string;
midget: string;
bob: string;
Anerisiandaysinmonth: array[1..12] of integer = (31,28,31,30,31,30,31,31,30,31,30,31);
procedure anerisiandate;
{ tHIS JUST GETS THE DATE INTO THE DD,MM,YY VARIABLES }
begin
DeCodeDate(date,yy,mm,dd);
end;
procedure BORIS;
{ This just tests to see if we are in a leap year }
var
snafu : boolean;
begin
snafu := False;
if (yy mod 4 = 0) then snafu := True;
if ((yy mod 100 = 0) and (yy mod 400 <> 0)) then snafu := False;
if ((snafu) and (mm = 2 ) and (dd=29)) then YOLD := True;
end;
function hodgepodge: integer;
{ This returns the total number of days since the year began.
It doesn't bother with leap years at all.
I get a wierd optical illusion looking at the until in this }
var
fnord : integer;
begin
Hedgehog := 1;
hodgepodge := 0;
fnord :=0;
if (mm > 1) then repeat
fnord := fnord + Anerisiandaysinmonth[Hedgehog];
Hedgehog := Hedgehog +1;
until Hedgehog = mm;
fnord := fnord + dd;
hodgepodge := fnord;
end;
function treesaregreen(): string;
{Returns the YOLD as a string}
begin
treesaregreen := IntTOStr(yy+1166);
end;
procedure GRAYFACE;
{This calculates everything, but does not bother much about leap years}
var
wrestle: integer;
Thwack: string;
begin
Hedgehog := hodgepodge;
wrestle := 0;
Thwack := 'th';
{set bob to the name of the holyday or St. Tibs day }
bob := 'St. Tibs Day';
if (Hedgehog = 5 ) then bob := 'Mungday';
if (Hedgehog = 50 ) then bob := 'Chaoflux';
if (Hedgehog = 78 ) then bob := 'Mojoday';
if (Hedgehog = 123) then bob := 'Discoflux';
if (Hedgehog = 151) then bob := 'Syaday';
if (Hedgehog = 196) then bob := 'Confuflux';
if (Hedgehog = 224) then bob := 'Zaraday';
if (Hedgehog = 269) then bob := 'Bureflux';
if (Hedgehog = 297) then bob := 'Maladay';
if (Hedgehog = 342) then bob := 'Afflux';
{Not doing things the usual way
Lets find the week day and count the number of
5 day weeks all at the same time}
while (Hedgehog > 5) do begin
Hedgehog := Hedgehog -5;
wrestle := Wrestle + 1;
end;
if (Hedgehog = 1) then snub := 'Sweetmorn' ;
if (Hedgehog = 2) then snub := 'BoomTime';
if (Hedgehog = 3) then snub := 'Pungenday';
if (Hedgehog = 4) then snub := 'Prickle-Prickle';
if (Hedgehog = 5) then snub := 'Setting Orange';
{Now to set the Season name}
chaotica:='The Aftermath';
if (wrestle <=57) then chaotica := 'Bureaucracy';
if ((wrestle = 58) and (Hedgehog < 3)) then chaotica := 'Bureaucracy';
if (wrestle <= 42) then chaotica := 'Confusion';
if ((wrestle = 43) and (Hedgehog < 5)) then chaotica := 'Confusion';
if (wrestle <=28) then chaotica := 'Discord';
if ((wrestle = 29) and (Hedgehog < 2)) then chaotica := 'Discord';
if (wrestle <=13) then chaotica := 'Chaos';
if ((wrestle = 14) and (Hedgehog < 4)) then chaotica := 'Chaos';
{Now all we need the day of the season}
wrestle := (wrestle*5)+Hedgehog;
while (wrestle >73) do wrestle := wrestle -73;
{pick the appropriate day postfix, allready set to th}
if (wrestle in [1,21,31,41,51,61,71]) then Thwack:='st';
if (wrestle in [2,22,32,42,52,62,72]) then Thwack:='nd';
if (wrestle in [3,23,33,43,53,63,73]) then Thwack:='rd';
{Check to see if it is a holy day, if so bob will have
the right holyday name already, including St Tibs Day}
if (wrestle in [5,50]) then YOLD := True;
{I love this line of code}
midget := IntToStr(wrestle) + Thwack;
end;
{The main program starts here}
begin
anerisiandate;
if (ParamCount >=1) then dd := StrTOInt(ParamStr(1));
if (ParamCount >=2) then mm := StrToInt(ParamStr(2));
if (ParamCount =3) then yy := StrToInt(ParamStr(3));
BORIS;
GRAYFACE;
{ The only thing to bother about is holy days and St Tibs day }
Eris := 'Today is: ' + snub +' the ' + midget +' day of the season of ' + chaotica;
if (YOLD) then begin
Eris := 'Celebrate for today, ' + snub + ' the ' + midget + ' day of ' +chaotica + ' is the holy day of ' + bob;
end;
{The only place we deal with St. Tibs Day}
if ((YOLD) and ((mm=2) and (dd=29))) then Eris := 'Celebrate ' + bob + ' Chaos';
{This next line applies to all possibilities}
Eris := Eris + ' YOLD ' + treesaregreen;
WriteLn(Eris);
end.
|
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #Pascal | Pascal | program dijkstra(output);
type
{ We dynamically build the list of vertices from the edge list,
just to avoid repeating ourselves in the graph input. Vertices are linked
together via their `next` pointers to form a list of all vertices (sorted by
name), while the `previous` pointer indicates the previous vertex along the
shortest path to this one. }
vertex = record
name: char;
visited: boolean;
distance: integer;
previous: ^vertex;
next: ^vertex;
end;
vptr = ^vertex;
{ The graph is specified as an array of these }
edge_desc = record
source: char;
dest: char;
weight: integer;
end;
const
{ the input graph }
edges: array of edge_desc = (
(source:'a'; dest:'b'; weight:7),
(source:'a'; dest:'c'; weight:9),
(source:'a'; dest:'f'; weight:14),
(source:'b'; dest:'c'; weight:10),
(source:'b'; dest:'d'; weight:15),
(source:'c'; dest:'d'; weight:11),
(source:'c'; dest:'f'; weight:2),
(source:'d'; dest:'e'; weight:6),
(source:'e'; dest:'f'; weight:9)
);
{ find the shortest path to all nodes starting from this one }
origin: char = 'a';
var
head_vertex: vptr = nil;
curr, next, closest: vptr;
vtx: vptr;
dist: integer;
edge: edge_desc;
done: boolean = false;
{ allocate a new vertex node with the given name and `next` pointer }
function new_vertex(key: char; next: vptr): vptr;
var
vtx: vptr;
begin
new(vtx);
vtx^.name := key;
vtx^.visited := false;
vtx^.distance := maxint;
vtx^.previous := nil;
vtx^.next := next;
new_vertex := vtx;
end;
{ look up a vertex by name; create it if needed }
function find_or_make_vertex(key: char): vptr; var
vtx, prev, found: vptr;
done: boolean;
begin
found := nil;
if head_vertex = nil then
head_vertex := new_vertex(key, nil)
else if head_vertex^.name > key then
head_vertex := new_vertex(key, head_vertex);
if head_vertex^.name = key then
found := head_vertex
else begin
prev := head_vertex;
vtx := head_vertex^.next;
done := false;
while not done do
if vtx = nil then
done := true
else if vtx^.name >= key then
done := true
else begin
prev := vtx;
vtx := vtx^.next
end;
if vtx <> nil then
if vtx^.name = key then
found := vtx;
if found = nil then begin
prev^.next := new_vertex(key, vtx);
found := prev^.next;
end
end;
find_or_make_vertex := found
end;
{ display the path to a vertex indicated by its `previous` pointer chain }
procedure write_path(vtx: vptr);
begin
if vtx <> nil then begin
if vtx^.previous <> nil then begin
write_path(vtx^.previous);
write('→');
end;
write(vtx^.name);
end;
end;
begin
curr := find_or_make_vertex(origin);
curr^.distance := 0;
curr^.previous := nil;
while not done do begin
for edge in edges do begin
if edge.source = curr^.name then begin
next := find_or_make_vertex(edge.dest);
dist := curr^.distance + edge.weight;
if dist < next^.distance then begin
next^.distance := dist;
next^.previous := curr;
end
end
end;
curr^.visited := true;
closest := nil;
vtx := head_vertex;
while vtx <> nil do begin
if not vtx^.visited then
if closest = nil then
closest := vtx
else if vtx^.distance < closest^.distance then
closest := vtx;
vtx := vtx^.next;
end;
if closest = nil then
done := true
else if closest^.distance = maxint then
done := true;
curr := closest;
end;
writeln('Shortest path to each vertex from ', origin, ':');
vtx := head_vertex;
while vtx <> nil do begin
write(vtx^.name, ':', vtx^.distance);
if vtx^.distance > 0 then begin
write(' (');
write_path(vtx);
write(')');
end;
writeln();
vtx := vtx^.next;
end
end. |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #JavaScript | JavaScript | /// Digital root of 'x' in base 'b'.
/// @return {addpers, digrt}
function digitalRootBase(x,b) {
if (x < b)
return {addpers:0, digrt:x};
var fauxroot = 0;
while (b <= x) {
x = (x / b) | 0;
fauxroot += x % b;
}
var rootobj = digitalRootBase(fauxroot,b);
rootobj.addpers += 1;
return rootobj;
} |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Tcl | Tcl | proc mdr {n} {
if {$n < 0 || ![string is integer $n]} {
error "must be an integer"
}
for {set i 0} {$n > 9} {incr i} {
set n [tcl::mathop::* {*}[split $n ""]]
}
return [list $i $n]
} |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #PicoLisp | PicoLisp | # Problem statement
(be dwelling (@Tenants)
(permute (Baker Cooper Fletcher Miller Smith) @Tenants)
(not (topFloor Baker @Tenants))
(not (bottomFloor Cooper @Tenants))
(not (or ((topFloor Fletcher @Tenants)) ((bottomFloor Fletcher @Tenants))))
(higherFloor Miller Cooper @Tenants)
(not (adjacentFloor Smith Fletcher @Tenants))
(not (adjacentFloor Fletcher Cooper @Tenants)) )
# Utility rules
(be topFloor (@Tenant @Lst)
(equal (@ @ @ @ @Tenant) @Lst) )
(be bottomFloor (@Tenant @Lst)
(equal (@Tenant @ @ @ @) @Lst) )
(be higherFloor (@Tenant1 @Tenant2 @Lst)
(append @ @Rest @Lst)
(equal (@Tenant2 . @Higher) @Rest)
(member @Tenant1 @Higher) )
(be adjacentFloor (@Tenant1 @Tenant2 @Lst)
(append @ @Rest @Lst)
(or
((equal (@Tenant1 @Tenant2 . @) @Rest))
((equal (@Tenant2 @Tenant1 . @) @Rest)) ) ) |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #IDL | IDL |
a = [1, 3, -5]
b = [4, -2, -1]
c = a#TRANSPOSE(b)
c = TOTAL(a*b,/PRESERVE_TYPE)
|
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MATLAB_.2F_Octave | MATLAB / Octave |
function r = squeezee(s,c)
ix = [];
c = unique(c);
for k=1:length(c)
ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1];
end
r=s;
r(ix)=[];
fprintf(1,'Character to be squeezed: "%s"\n',c);
fprintf(1,'Input: <<<%s>>> length: %d\n',s,length(s));
fprintf(1,'Output: <<<%s>>> length: %d\n',r,length(r));
fprintf(1,'Character to be squeezed: "%s"\n',c);
end
squeezee('', ' ')
squeezee('║╚═══════════════════════════════════════════════════════════════════════╗', '-')
squeezee('║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║', '7')
squeezee('║..1111111111111111111111111111111111111111111111111111111111111117777888║', '.')
squeezee('║I never give ''em hell, I just tell the truth, and they think it''s hell. ║', '.')
squeezee('║ --- Harry S Truman ║', '.')
squeezee('║ --- Harry S Truman ║', '-')
squeezee('║ --- Harry S Truman ║', 'r')
|
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #NetLogo | NetLogo |
to-report split [ string ]
;; utility reporter to split a string into a list
report n-values length string [ [ n ] -> item n string ]
end
to-report squeeze [ character string ]
;; reporter that actually does the squeeze function
;; remote immeadiately repeating instances of character from string
ifelse ( string = "" )
[ report "" ] ;; empty input, report empty output
[ report
reduce
[ [ a b ] ->
( word a
ifelse-value b = character and b = last a
[ "" ]
[ b ]
)
]
split string
]
end
to-report bracket [ string ]
;; utility reporter to enclose a string in brackets
report ( word "<<<" string ">>>" )
end
to-report format [ string ]
;; utility reporter to format the output as required
report ( word bracket string " " length string )
end
to demo-squeeze [ character string ]
;; procedure to display the required output
output-print bracket character
output-print format string
output-print format squeeze character string
end
to demo
;; procedure to perform the test cases
demo-squeeze " " ""
demo-squeeze "-" "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
demo-squeeze "7" "..1111111111111111111111111111111111111111111111111111111111111117777888"
demo-squeeze "." "I never give 'em hell, I just tell the truth, and they think it's hell. "
demo-squeeze " " " --- Harry S Truman "
demo-squeeze "-" " --- Harry S Truman "
demo-squeeze "r" " --- Harry S Truman "
end
|
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #PARI.2FGP | PARI/GP | drop(drops, rule, rnd)={
my(v=vector(drops),target=0);
v[1]=rule(target, 0);
for(i=2,drops,
target=rule(target, v[i-1]);
v[i]=rnd(n)+target
);
v
};
R=[-.533-.136*I,.27-.717*I,.859-.459*I,-.043+.225*I,-.205-1.39*I,-.127-.385*I,-.071-.121*I,.275+.395*I,1.25-.490*I,-.231+.682*I,-.401+.0650*I,.269-.242*I,.491+.288*I,.951-.658*I,1.15-.459*I,.001,-.382-.426*I,.161-.205*I,.915+.765*I,2.08+2.19*I,-2.34+.742*I,.034+.0100*I,-.126-.0890*I,.014-.208*I,.709-.585*I,.129-.633*I,-1.09+.444*I,-.483+.351*I,-1.19+1.09*I,.02-.199*I,-.051-.701*I,.047-.0960*I,-.095+.0250*I,.695+.868*I,.34-1.05*I,-.182-.157*I,.287-.216*I,.213-.162*I,-.423-.249*I,-.021+.00700*I,-0.134-.00900*I,1.8-.508*I,.021+.790*I,-1.1-.723*I,-.361-.881*I,1.64+.508*I,-1.13-.393*I,1.32+.226*I,.201-.710*I,.034-.0380*I,.097+.217*I,-.17-.831*I,.054-.480*I,-.553-.407*I,-.024-.447*I,-.181+.295*I,-.7-1.13*I,-.361-.380*I,-.789-.549*I,.279+.445*I,-.174+.0460*I,-.009-.428*I,-.323+.0740*I,-.658-.217*I,.348+.822*I,-.528-.491*I,.881-1.35*I,.021+.141*I,-.853-1.23*I,.157+.0440*I,.648-.0790*I,1.77-.219*I,-1.04-.698*I,.051-.275*I,.021-.0560*I,.247-.0310*I,-.31-.421*I,.171-.0640*I,-.721*I,.106-.104*I,.024+.729*I,-.386-.650*I,.962+1.10*I,.765-.154*I,-.125+1.72*I,-.289-.0510*I,.521+.385*I,.017-.477*I,.281-1.54*I,-.749+.901*I,-.149-.939*I,-2.44+.411*I,-.909-.341*I,.394+.411*I,-.113-.106*I,-.598-.224*I,.443+.947*I,-.521+1.42*I,-.799+.542*I,.087+1.03*I];
rule1(target, result)=0;
rule2(target, result)=target-result;
rule3(target, result)=-result;
rule4(target, result)=result;
mean(v)=sum(i=1,#v,v[i])/#v;
stdev(v,mu=mean(v))=sqrt(sum(i=1,#v,(v[i]-mu)^2)/#v);
main()={
my(V);
V=apply(f->drop(100,f,n->R[n]), [rule1, rule2, rule3, rule4]);
for(i=1,4,
print("Method #"i);
print("Means: ", mean(real(V[i])), "\t", mean(imag(V[i])));
print("StDev: ", stdev(real(V[i])), "\t", stdev(imag(V[i])));
print()
)
} |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Asymptote | Asymptote | write("--police-- --sanitation-- --fire--");
for(int police = 2; police < 6; police += 2) {
for(int sanitation = 1; sanitation < 7; ++sanitation) {
for(int fire = 1; fire < 7; ++fire) {
if(police != sanitation && sanitation != fire && fire != police && police+fire+sanitation == 12){
write(" ", police, suffix=none);
write(" ", sanitation, suffix=none);
write(" ", fire);
}
}
}
} |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #E | E | def makeDelegator {
/** construct without an explicit delegate */
to run() {
return makeDelegator(null)
}
/** construct with a delegate */
to run(delegateO) { # suffix because "delegate" is a reserved keyword
def delegator {
to operation() {
return if (delegateO.__respondsTo("thing", 0)) {
delegateO.thing()
} else {
"default implementation"
}
}
}
return delegator
}
}
? def delegator := makeDelegator()
> delegator.operation()
# value: "default implementation"
? def delegator := makeDelegator(def doesNotImplement {})
> delegator.operation()
# value: "default implementation"
? def delegator := makeDelegator(def doesImplement {
> to thing() { return "delegate implementation" }
> })
> delegator.operation()
# value: "default implementation" |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Elena | Elena | import extensions;
import system'routines;
interface IOperable
{
abstract operate() {}
}
class Operable : IOperable
{
constructor() {}
operate()
= "delegate implementation";
}
class Delegator
{
object theDelegate;
set Delegate(object)
{
theDelegate := object
}
internal operate(operable)
= "default implementation";
internal operate(IOperable operable)
= operable.operate();
operate()
<= operate(theDelegate);
}
public program()
{
var delegator := new Delegator();
new object[]{nil, new Object(), new Operable()}.forEach:(o)
{
delegator.Delegate := o;
console.printLine(delegator.operate())
}
} |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #jq | jq | # Points are realized as arrays of two numbers [x, y]
# Triangles are realized as triples of Points [p1, p2, p3]
# Input: a Triangle
def det2D:
. as [ [$p1x, $p1y], [$p2x, $p2y], [$p3x, $p3y]]
| $p1x * ($p2y - $p3y) +
$p2x * ($p3y - $p1y) +
$p3x * ($p1y - $p2y) ;
# Input: a Triangle
def checkTriWinding(allowReversed):
if det2D < 0
then if allowReversed
then . as [$p1, $p2, $p3]
| [$p1, $p3, $p2 ]
else "Triangle has wrong winding direction" | error
end
else .
end;
def boundaryCollideChk(eps): det2D < eps;
def boundaryDoesntCollideChk(eps): det2D <= eps;
def triTri2D($t1; $t2; $eps; $allowReversed; $onBoundary):
def chkEdge:
if $onBoundary then boundaryCollideChk($eps)
else boundaryDoesntCollideChk($eps)
end;
# Triangles must be expressed anti-clockwise
($t1|checkTriWinding($allowReversed))
| ($t2|checkTriWinding($allowReversed))
# 'onBoundary' determines whether points on boundary are considered as colliding or not
# for each edge E of t1
| first( range(0;3) as $i
| (($i + 1) % 3) as $j
# Check all points of t2 lie on the external side of edge E.
# If they do, the triangles do not overlap.
| if ([$t1[$i], $t1[$j], $t2[0]]| chkEdge) and
([$t1[$i], $t1[$j], $t2[1]]| chkEdge) and
([$t1[$i], $t1[$j], $t2[2]]| chkEdge)
then 0
else empty
end) // true
| if . == 0 then false
else
# for each edge E of t2
first( range(0;3) as $i
| (($i + 1) % 3) as $j
# Check all points of t1 lie on the external side of edge E.
# If they do, the triangles do not overlap.
| if ([$t2[$i], $t2[$j], $t1[0]] | chkEdge) and
([$t2[$i], $t2[$j], $t1[1]] | chkEdge) and
([$t2[$i], $t2[$j], $t1[2]] | chkEdge)
then 0
else empty
end) // true
| if . == 0 then false
else true # The triangles overlap
end
end ; |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Delete-Files.
PROCEDURE DIVISION.
CALL "CBL_DELETE_FILE" USING "input.txt"
CALL "CBL_DELETE_DIR" USING "docs"
CALL "CBL_DELETE_FILE" USING "/input.txt"
CALL "CBL_DELETE_DIR" USING "/docs"
GOBACK
. |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Common_Lisp | Common Lisp | (delete-file (make-pathname :name "input.txt"))
(delete-file (make-pathname :directory '(:absolute "") :name "input.txt")) |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #JavaScript | JavaScript | const determinant = arr =>
arr.length === 1 ? (
arr[0][0]
) : arr[0].reduce(
(sum, v, i) => sum + v * (-1) ** i * determinant(
arr.slice(1)
.map(x => x.filter((_, j) => i !== j))
), 0
);
const permanent = arr =>
arr.length === 1 ? (
arr[0][0]
) : arr[0].reduce(
(sum, v, i) => sum + v * permanent(
arr.slice(1)
.map(x => x.filter((_, j) => i !== j))
), 0
);
const M = [
[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]
];
console.log(determinant(M));
console.log(permanent(M)); |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Elixir | Elixir | defmodule Division do
def by_zero?(x,y) do
try do
_ = x / y
false
rescue
ArithmeticError -> true
end
end
end
[{2, 3}, {3, 0}, {0, 5}, {0, 0}, {2.0, 3.0}, {3.0, 0.0}, {0.0, 5.0}, {0.0, 0.0}]
|> Enum.each(fn {x,y} ->
IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}"
end) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Emacs_Lisp | Emacs Lisp | (condition-case nil
(/ 1 0)
(arith-error
(message "Divide by zero (either integer or float)"))) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Erlang | Erlang | div_check(X,Y) ->
case catch X/Y of
{'EXIT',_} -> true;
_ -> false
end. |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ColdFusion | ColdFusion | <cfset TestValue=34>
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif>
<cfset TestValue="NAS">
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif> |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | Sub CaracteresUnicos (cad As String)
Dim As Integer lngt = Len(cad)
Print "Cadena = """; cad; """, longitud = "; lngt
For i As Integer = 1 To lngt
For j As Integer = i + 1 To lngt
If Mid(cad,i,1) = Mid(cad,j,1) Then
Print " Primer duplicado en las posiciones " & i & _
" y " & j & ", caracter = '" & Mid(cad,i,1) & _
"', valor hex = " & Hex(Asc(Mid(cad,i,1)))
Print
Exit Sub
End If
Next j
Next i
Print " Todos los caracteres son unicos." & Chr(10)
End Sub
CaracteresUnicos ("")
CaracteresUnicos (".")
CaracteresUnicos ("abcABC")
CaracteresUnicos ("XYZ ZYX")
CaracteresUnicos ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
Sleep |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[StringCollapse]
StringCollapse[s_String] := FixedPoint[StringReplace[y_ ~~ y_ :> y], s]
strings = {"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman "};
Do[
Print["«««" <> s <> "»»»"];
Print["Length = ", StringLength[s]];
Print["«««" <> StringCollapse[s] <> "»»»"];
Print["Length = ", StringLength[StringCollapse[s]]]
,
{s, strings}
] |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MATLAB_.2F_Octave | MATLAB / Octave |
function r = collapse(s)
ix=find((s(1:end-1)==s(2:end))+1;
r=s;
r(ix)=[];
fprintf(1,'Input: <<<%s>>> length: %d\n',s,length(s));
fprintf(1,'Output: <<<%s>>> length: %d\n',r,length(r));
fprintf(1,'Character to be squeezed: "%s"\n',c);
end
collapse('', ' ')
collapse('║╚═══════════════════════════════════════════════════════════════════════╗', '-')
collapse('║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║', '7')
collapse('║..1111111111111111111111111111111111111111111111111111111111111117777888║', '.')
collapse('║I never give ''em hell, I just tell the truth, and they think it''s hell. ║', '.')
collapse('║ --- Harry S Truman ║', '.')
collapse('║ --- Harry S Truman ║', '-')
collapse('║ --- Harry S Truman ║', 'r')
|
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #JavaScript | JavaScript | const check = s => {
const arr = [...s];
const at = arr.findIndex(
(v, i) => i === 0 ? false : v !== arr[i - 1]
)
const l = arr.length;
const ok = at === -1;
const p = ok ? "" : at + 1;
const v = ok ? "" : arr[at];
const vs = v === "" ? v : `"${v}"`
const h = ok ? "" : `0x${v.codePointAt(0).toString(16)}`;
console.log(`"${s}" => Length:${l}\tSame:${ok}\tPos:${p}\tChar:${vs}\tHex:${h}`)
}
['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '🐶🐶🐺🐶', '🎄🎄🎄🎄'].forEach(check) |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Pascal | Pascal |
program dining_philosophers;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, SyncObjs;
const
PHIL_COUNT = 5;
LIFESPAN = 7;
DELAY_RANGE = 950;
DELAY_LOW = 50;
PHIL_NAMES: array[1..PHIL_COUNT] of string = ('Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell');
type
TFork = TCriticalSection;
TPhilosopher = class;
var
Forks: array[1..PHIL_COUNT] of TFork;
Philosophers: array[1..PHIL_COUNT] of TPhilosopher;
type
TPhilosopher = class(TThread)
private
FName: string;
FFirstFork, FSecondFork: TFork;
protected
procedure Execute; override;
public
constructor Create(const aName: string; aForkIdx1, aForkIdx2: Integer);
end;
procedure TPhilosopher.Execute;
var
LfSpan: Integer = LIFESPAN;
begin
while LfSpan > 0 do
begin
Dec(LfSpan);
WriteLn(FName, ' sits down at the table');
FFirstFork.Acquire;
FSecondFork.Acquire;
WriteLn(FName, ' eating');
Sleep(Random(DELAY_RANGE) + DELAY_LOW);
FSecondFork.Release;
FFirstFork.Release;
WriteLn(FName, ' is full and leaves the table');
if LfSpan = 0 then
continue;
WriteLn(FName, ' thinking');
Sleep(Random(DELAY_RANGE) + DELAY_LOW);
WriteLn(FName, ' is hungry');
end;
end;
constructor TPhilosopher.Create(const aName: string; aForkIdx1, aForkIdx2: Integer);
begin
inherited Create(True);
FName := aName;
if aForkIdx1 < aForkIdx2 then
begin
FFirstFork := Forks[aForkIdx1];
FSecondFork := Forks[aForkIdx2];
end
else
begin
FFirstFork := Forks[aForkIdx2];
FSecondFork := Forks[aForkIdx1];
end;
end;
procedure DinnerBegin;
var
I: Integer;
Phil: TPhilosopher;
begin
for I := 1 to PHIL_COUNT do
Forks[I] := TFork.Create;
for I := 1 to PHIL_COUNT do
Philosophers[I] := TPhilosopher.Create(PHIL_NAMES[I], I, Succ(I mod PHIL_COUNT));
for Phil in Philosophers do
Phil.Start;
end;
procedure WaitForDinnerOver;
var
Phil: TPhilosopher;
Fork: TFork;
begin
for Phil in Philosophers do
begin
Phil.WaitFor;
Phil.Free;
end;
for Fork in Forks do
Fork.Free;
end;
begin
Randomize;
DinnerBegin;
WaitForDinnerOver;
end.
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Perl | Perl | use 5.010;
use strict;
use warnings;
use Time::Piece ();
my @seasons = (qw< Chaos Discord Confusion Bureaucracy >, 'The Aftermath');
my @week_days = (qw< Sweetmorn Boomtime Pungenday Prickle-Prickle >, 'Setting Orange');
sub ordinal {
my ($n) = @_;
return $n . "th" if int($n/10) == 1;
return $n . ((qw< th st nd rd th th th th th th>)[$n % 10]);
}
sub ddate {
my $d = Time::Piece->strptime( $_[0], '%Y-%m-%d' );
my $yold = 'in the YOLD ' . ($d->year + 1166);
my $day_of_year0 = $d->day_of_year;
if( $d->is_leap_year ) {
return "St. Tib's Day, $yold" if $d->mon == 2 and $d->mday == 29;
$day_of_year0-- if $day_of_year0 >= 60; # Compensate for St. Tib's Day
}
my $weekday = $week_days[ $day_of_year0 % @week_days ];
my $season = $seasons[ $day_of_year0 / 73 ];
my $season_day = ordinal( $day_of_year0 % 73 + 1 );
return "$weekday, the $season_day day of $season $yold";
}
say "$_ is " . ddate($_) for qw< 2010-07-22 2012-02-28 2012-02-29 2012-03-01 >;
|
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #Perl | Perl | use strict;
use warnings;
use constant True => 1;
sub add_edge {
my ($g, $a, $b, $weight) = @_;
$g->{$a} ||= {name => $a};
$g->{$b} ||= {name => $b};
push @{$g->{$a}{edges}}, {weight => $weight, vertex => $g->{$b}};
}
sub push_priority {
my ($a, $v) = @_;
my $i = 0;
my $j = $#{$a};
while ($i <= $j) {
my $k = int(($i + $j) / 2);
if ($a->[$k]{dist} >= $v->{dist}) { $j = $k - 1 }
else { $i = $k + 1 }
}
splice @$a, $i, 0, $v;
}
sub dijkstra {
my ($g, $a, $b) = @_;
for my $v (values %$g) {
$v->{dist} = 10e7; # arbitrary large value
delete @$v{'prev', 'visited'}
}
$g->{$a}{dist} = 0;
my $h = [];
push_priority($h, $g->{$a});
while () {
my $v = shift @$h;
last if !$v or $v->{name} eq $b;
$v->{visited} = True;
for my $e (@{$v->{edges}}) {
my $u = $e->{vertex};
if (!$u->{visited} && $v->{dist} + $e->{weight} <= $u->{dist}) {
$u->{prev} = $v;
$u->{dist} = $v->{dist} + $e->{weight};
push_priority($h, $u);
}
}
}
}
my $g = {};
add_edge($g, @$_) for
(['a', 'b', 7], ['a', 'c', 9], ['a', 'f', 14],
['b', 'c', 10], ['b', 'd', 15], ['c', 'd', 11],
['c', 'f', 2], ['d', 'e', 6], ['e', 'f', 9]);
dijkstra($g, 'a', 'e');
my $v = $g->{e};
my @a;
while ($v) {
push @a, $v->{name};
$v = $v->{prev};
}
my $path = join '', reverse @a;
print "$g->{e}{dist} $path\n"; |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #jq | jq | def do_until(condition; next):
def u: if condition then . else (next|u) end;
u;
# n may be a decimal number or a string representing a decimal number
def digital_root(n):
# string-only version
def dr:
# state: [mdr, persist]
do_until( .[0] | length == 1;
[ (.[0] | explode | map(.-48) | add | tostring), .[1] + 1 ]
);
[n|tostring, 0] | dr | .[0] |= tonumber;
def neatly:
. as $in
| range(0;length)
| "\(.): \($in[.])";
def rjust(n): tostring | (n-length)*" " + .; |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Julia | Julia | function digitalroot(n::Integer, bs::Integer=10)
if n < 0 || bs < 2 throw(DomainError()) end
ds, pers = n, 0
while bs ≤ ds
ds = sum(digits(ds, bs))
pers += 1
end
return pers, ds
end
for i in [627615, 39390, 588225, 393900588225, big(2) ^ 100]
pers, ds = digitalroot(i)
println(i, " has persistence ", pers, " and digital root ", ds)
end |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Vlang | Vlang | // Only valid for n > 0 && base >= 2
fn mult(nn u64, base int) u64 {
mut n := nn
mut mult := u64(0)
for mult = 1; mult > 0 && n > 0; n /= u64(base) {
mult *= n % u64(base)
}
return mult
}
// Only valid for n >= 0 && base >= 2
fn multi_digital_root(n u64, base int) (int, int) {
mut m := u64(0)
mut mp := 0
for m = n; m >= u64(base); mp++ {
m = mult(m, base)
}
return mp, int(m)
}
const base = 10
fn main() {
size := 5
println("${'Number':20} ${'MDR':3} ${'MP':3}")
for n in [
u64(123321), 7739, 893, 899998,
18446743999999999999,
// From http://mathworld.wolfram.com/MultiplicativePersistence.html
3778888999, 277777788888899,
] {
mp, mdr := multi_digital_root(n, base)
println("${n:20} ${mdr:3} ${mp:3}")
}
println('')
mut list := [base][]u64{init: []u64{len: 0, cap:size}}
for cnt, n := size*base, u64(0); cnt > 0; n++ {
_, mdr := multi_digital_root(n, base)
if list[mdr].len < size {
list[mdr] << n
cnt--
}
}
println("${'MDR':3}: First")
for i, l in list {
println("${i:3}: $l")
}
} |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
// Only valid for n > 0 && base >= 2
var mult = Fn.new { |n, base|
var m = BigInt.one
while (m > BigInt.zero && n > BigInt.zero) {
var dm = n.divMod(base)
m = m * dm[1]
n = dm[0]
}
return m
}
// Only valid for n >= 0 && base >= 2
var multDigitalRoot = Fn.new { |n, base|
base = BigInt.new(base)
var m = n.copy()
var mp = BigInt.zero
while (m >= base) {
m = mult.call(m, base)
mp = mp.inc
}
return [mp, m.toSmall]
}
var base = 10
var size = 5
var tests = [
123321, 7739, 893, 899998,"18446743999999999999", 3778888999, "277777788888899"
]
var testFmt = "$20s $3s $3s"
Fmt.print(testFmt, "Number", "MDR", "MP")
for (test in tests) {
var n = BigInt.new(test)
var mpdr = multDigitalRoot.call(n, base)
Fmt.print(testFmt, n, mpdr[1], mpdr[0])
}
System.print()
var list = List.filled(base, null)
for (i in 0...base) list[i] = []
var cnt = size * base
var n = BigInt.zero
while (cnt > 0) {
var mpdr = multDigitalRoot.call(n, base)
var mdr = mpdr[1]
if (list[mdr].count < size) {
list[mdr].add(n)
cnt = cnt - 1
}
n = n.inc
}
Fmt.print("$3s: $s", "MDR", "First")
var i = 0
for (l in list) {
Fmt.print("$3d: $s", i, l.toString)
i = i + 1
} |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #PowerShell | PowerShell |
# Floors are numbered 1 (ground) to 5 (top)
# Baker, Cooper, Fletcher, Miller, and Smith live on different floors:
$statement1 = '$baker -ne $cooper -and $baker -ne $fletcher -and $baker -ne $miller -and
$baker -ne $smith -and $cooper -ne $fletcher -and $cooper -ne $miller -and
$cooper -ne $smith -and $fletcher -ne $miller -and $fletcher -ne $smith -and
$miller -ne $smith'
# Baker does not live on the top floor:
$statement2 = '$baker -ne 5'
# Cooper does not live on the bottom floor:
$statement3 = '$cooper -ne 1'
# Fletcher does not live on either the top or the bottom floor:
$statement4 = '$fletcher -ne 1 -and $fletcher -ne 5'
# Miller lives on a higher floor than does Cooper:
$statement5 = '$miller -gt $cooper'
# Smith does not live on a floor adjacent to Fletcher's:
$statement6 = '[Math]::Abs($smith - $fletcher) -ne 1'
# Fletcher does not live on a floor adjacent to Cooper's:
$statement7 = '[Math]::Abs($fletcher - $cooper) -ne 1'
for ($baker = 1; $baker -lt 6; $baker++)
{
for ($cooper = 1; $cooper -lt 6; $cooper++)
{
for ($fletcher = 1; $fletcher -lt 6; $fletcher++)
{
for ($miller = 1; $miller -lt 6; $miller++)
{
for ($smith = 1; $smith -lt 6; $smith++)
{
if (Invoke-Expression $statement2)
{
if (Invoke-Expression $statement3)
{
if (Invoke-Expression $statement5)
{
if (Invoke-Expression $statement4)
{
if (Invoke-Expression $statement6)
{
if (Invoke-Expression $statement7)
{
if (Invoke-Expression $statement1)
{
$multipleDwellings = @()
$multipleDwellings+= [PSCustomObject]@{Name = "Baker" ; Floor = $baker}
$multipleDwellings+= [PSCustomObject]@{Name = "Cooper" ; Floor = $cooper}
$multipleDwellings+= [PSCustomObject]@{Name = "Fletcher"; Floor = $fletcher}
$multipleDwellings+= [PSCustomObject]@{Name = "Miller" ; Floor = $miller}
$multipleDwellings+= [PSCustomObject]@{Name = "Smith" ; Floor = $smith}
}
}
}
}
}
}
}
}
}
}
}
}
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Idris | Idris | module Main
import Data.Vect
dotProduct : (Num a) => Vect n a -> Vect n a -> a
dotProduct = (sum .) . zipWith (*)
main : IO ()
main = printLn $ dotProduct [1,2,3] [1,2,3]
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #J | J | 1 3 _5 +/ . * 4 _2 _1
3
dotp=: +/ . * NB. Or defined as a verb (function)
1 3 _5 dotp 4 _2 _1
3 |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune)
previous = rune
elif rune != ch:
squeezed.add(rune)
echo fmt"Squeezed: length = {squeezed.len}, string = «««{squeezed}»»»"
echo ""
const Strings = ["",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",]
const Chars = [@[Rune(' ')], @[Rune('-')], @[Rune('7')], @[Rune('.')],
@[Rune(' '), Rune('-'), Rune('r')],
@[Rune('e')], @[Rune('s')], @[Rune('a')], "😍".toRunes]
for i, s in Strings:
for ch in Chars[i]:
s.squeeze(ch) |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '-'],
['..1111111111111111111111111111111111111111111111111111111111111117777888', '7'],
["I never give 'em hell, I just tell the truth, and they think it's hell. ", '.'],
[' --- Harry S Truman ', ' '],
[' --- Harry S Truman ', '-'],
[' --- Harry S Truman ', 'r']
) {
my($phrase,$char) = @$_;
(my $squeeze = $phrase) =~ s/([$char])\1+/$1/g;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
length($phrase), $phrase,
charinfo(ord $char)->{'name'},
$phrase ne $squeeze ? 'True' : 'False',
length($squeeze), $squeeze
} |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Perl | Perl | @dx = qw<
-0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275
1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001
-0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014
0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047
-0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021
-0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315
0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024 -0.181
-0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658
0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774
-1.043 0.051 0.021 0.247 -0.310 0.171 0.000 0.106
0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017
0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598
0.443 -0.521 -0.799 0.087>;
@dy = qw<
0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395
0.490 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.000
0.426 0.205 -0.765 -2.188 -0.742 -0.010 0.089 0.208
0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096
-0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007
0.009 0.508 -0.790 0.723 0.881 -0.508 0.393 -0.226
0.710 0.038 -0.217 0.831 0.480 0.407 0.447 -0.295
1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217
-0.822 0.491 1.347 -0.141 1.230 -0.044 0.079 0.219
0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104
-0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477
1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224
-0.947 -1.424 -0.542 -1.032>;
sub mean { my $s; $s += $_ for @_; $s / @_ }
sub stddev { sqrt( mean(map { $_**2 } @_) - mean(@_)**2) }
@rules = (
sub { 0 },
sub { -$_[1] },
sub { -$_[0] - $_[1] },
sub { $_[0] + $_[1] }
);
for (@rules) {
print "Rule " . ++$cnt . "\n";
my @ddx; my $tx = 0;
for my $x (@dx) { push @ddx, $tx + $x; $tx = &$_($tx, $x) }
my @ddy; my $ty = 0;
for my $y (@dy) { push @ddy, $ty + $y; $ty = &$_($ty, $y) }
printf "Mean x, y : %7.4f %7.4f\n", mean(@ddx), mean(@ddy);
printf "Std dev x, y : %7.4f %7.4f\n", stddev(@ddx), stddev(@ddy);
} |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #AutoHotkey | AutoHotkey | perm(elements, n, opt:="", Delim:="", str:="", res:="", j:=0, dup:="") {
res := IsObject(res) ? res : [], dup := IsObject(dup) ? dup : []
if (n > j)
Loop, parse, elements, % Delim
res := !(InStr(str, A_LoopField) && !(InStr(opt, "rep"))) ? perm(elements, n, opt, Delim, trim(str Delim A_LoopField, Delim), res, j+1, dup) : res
else if !(dup[x := perm_sort(str, Delim)] && (InStr(opt, "comb")))
dup[x] := 1, res.Insert(str)
return res, j++
}
perm_sort(str, Delim){
Loop, Parse, str, % Delim
res .= A_LoopField "`n"
Sort, res, D`n
return StrReplace(res, "`n", Delim)
} |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #F.23 | F# | type Delegator() =
let defaultOperation() = "default implementation"
let mutable del = null
// write-only property "Delegate"
member x.Delegate with set(d:obj) = del <- d
member x.operation() =
if del = null then
defaultOperation()
else
match del.GetType().GetMethod("thing", [||]) with
| null -> defaultOperation()
| thing -> thing.Invoke(del, [||]) :?> string
type Delegate() =
member x.thing() = "delegate implementation"
let d = new Delegator()
assert (d.operation() = "default implementation")
d.Delegate <- "A delegate may be any object"
assert (d.operation() = "default implementation")
d.Delegate <- new Delegate()
assert (d.operation() = "delegate implementation") |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Forth | Forth | include FMS-SI.f
:class delegate
:m thing ." delegate implementation" ;m
;class
delegate slave
:class delegator
ivar del \ object container
:m !: ( n -- ) del ! ;m
:m init: 0 del ! ;m
:m default ." default implementation" ;m
:m operation
del @ 0= if self default exit then
del @ has-meth thing
if del @ thing
else self default
then ;m
;class
delegator master
\ First, without a delegate
master operation \ => default implementation
\ then with a delegate that does not implement "thing"
object o
o master !:
master operation \ => default implementation
\ and last with a delegate that implements "thing"
slave master !:
master operation \ => delegate implementation
|
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #Julia | Julia | module Triangles
using LinearAlgebra
export AntiClockwise, Both, StrictCheck, MildCheck
abstract type Widing end
struct AntiClockwise <: Widing end
struct Both <: Widing end
function _check_triangle_winding(t, widing::AntiClockwise)
trisq = fill!(Matrix{eltype(t)}(undef, 3, 3), 1)
trisq[:, 1:2] .= t
det(trisq) < 0 && throw(ArgumentError("triangle has wrong winding direction"))
return trisq
end
function _check_triangle_winding(t, widing::Both)
trisq = fill!(Matrix{eltype(t)}(undef, 3, 3), 1)
trisq[:, 1:2] .= t
if det(trisq) < 0
tmp = trisq[2, :]
trisq[2, :] .= trisq[1, :]
trisq[1, :] .= tmp
end
return trisq
end
abstract type OnBoundaryCheck end
struct StrictCheck <: OnBoundaryCheck end
struct MildCheck <: OnBoundaryCheck end
_checkedge(::StrictCheck, x, ϵ) = det(x) < ϵ
_checkedge(::MildCheck, x, ϵ) = det(x) ≤ ϵ
function overlap(T₁, T₂, onboundary::OnBoundaryCheck=MildCheck(),; ϵ=0.0, widing::Widing=AntiClockwise())
# Trangles must be expressed anti-clockwise
T₁ = _check_triangle_winding(T₁, widing)
T₂ = _check_triangle_winding(T₂, widing)
edge = similar(T₁)
for (A, B) in ((T₁, T₂), (T₂, T₁)), i in 1:3
circshift!(edge, A, (i, 0))
@views if all(_checkedge(onboundary, vcat(edge[1:2, :], B[r, :]'), ϵ) for r in 1:3)
return false
end
end
return true
end
end # module Triangles |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Component_Pascal | Component Pascal |
VAR
l: Files.Locator;
BEGIN
(* Locator is the directory *)
l := Files.dir.This("proof");
(* delete 'xx.txt' file, in directory 'proof' *)
Files.dir.Delete(l,"xx.txt");
END ...
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #D | D | import std.file: remove;
void main() {
remove("data.txt");
} |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #jq | jq | # Eliminate row i and row j
def except(i;j):
reduce del(.[i])[] as $row ([]; . + [$row | del(.[j]) ] );
def det:
def parity(i): if i % 2 == 0 then 1 else -1 end;
if length == 1 and (.[0] | length) == 1 then .[0][0]
else . as $m
| reduce range(0; length) as $i
(0; . + parity($i) * $m[0][$i] * ( $m | except(0;$i) | det) )
end ;
def perm:
if length == 1 and (.[0] | length) == 1 then .[0][0]
else . as $m
| reduce range(0; length) as $i
(0; . + $m[0][$i] * ( $m | except(0;$i) | perm) )
end ; |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #Julia | Julia | using LinearAlgebra |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #ERRE | ERRE |
PROGRAM DIV_BY_ZERO
EXCEPTION
IF ERR=11 THEN PRINT("Division by Zero") END IF
END EXCEPTION
BEGIN
PRINT(0/3)
PRINT(3/0)
END PROGRAM
|
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #F.23 | F# | let detectDivideZero (x : int) (y : int):int option =
try
Some(x / y)
with
| :? System.ArithmeticException -> None
printfn "12 divided by 3 is %A" (detectDivideZero 12 3)
printfn "1 divided by 0 is %A" (detectDivideZero 1 0) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Common_Lisp | Common Lisp | (defun numeric-string-p (string)
(let ((*read-eval* nil))
(ignore-errors (numberp (read-from-string string))))) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #D | D | import std.stdio, std.string, std.array;
void main() {
foreach (const s; ["12", " 12\t", "hello12", "-12", "02",
"0-12", "+12", "1.5", "1,000", "1_000",
"0x10", "0b10101111_11110000_11110000_00110011",
"-0b10101", "0x10.5"])
writefln(`isNumeric("%s"): %s`, s, s.strip().isNumeric(true));
} |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import "fmt"
func analyze(s string) {
chars := []rune(s)
le := len(chars)
fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
if le > 1 {
for i := 0; i < le-1; i++ {
for j := i + 1; j < le; j++ {
if chars[j] == chars[i] {
fmt.Println(" Not all characters in the string are unique.")
fmt.Printf(" %q (%#[1]x) is duplicated at positions %d and %d.\n\n", chars[i], i+1, j+1)
return
}
}
}
}
fmt.Println(" All characters in the string are unique.\n")
}
func main() {
strings := []string{
"",
".",
"abcABC",
"XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"hétérogénéité",
"🎆🎃🎇🎈",
"😍😀🙌💃😍🙌",
"🐠🐟🐡🦈🐬🐳🐋🐡",
}
for _, s := range strings {
analyze(s)
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Modula-2 | Modula-2 | MODULE StrCollapse;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
(* Collapse a string *)
PROCEDURE Collapse(in: ARRAY OF CHAR; VAR out: ARRAY OF CHAR);
VAR i, o: CARDINAL;
BEGIN
i := 0;
o := 0;
WHILE (i < HIGH(in)) AND (in[i] # CHR(0)) DO
IF (o = 0) OR (out[o-1] # in[i]) THEN
out[o] := in[i];
INC(o);
END;
INC(i);
END;
out[o] := CHR(0);
END Collapse;
(* Display a string and collapse it as stated in the task *)
PROCEDURE Task(s: ARRAY OF CHAR);
VAR buf: ARRAY [0..127] OF CHAR;
PROCEDURE LengthAndBrackets(s: ARRAY OF CHAR);
BEGIN
WriteCard(Length(s), 2);
WriteString(" <<<");
WriteString(s);
WriteString(">>>");
WriteLn();
END LengthAndBrackets;
BEGIN
LengthAndBrackets(s);
Collapse(s, buf);
LengthAndBrackets(buf);
WriteLn();
END Task;
BEGIN
Task("");
Task('"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ');
Task("..1111111111111111111111111111111111111111111111111111111111111117777888");
Task("I never give 'em hell, I just tell the truth, and they think it's hell. ");
Task(" --- Harry S Truman ");
END StrCollapse. |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #jq | jq | jq -rn '
def firstdifferent:
label $out
| foreach explode[] as $i ({index:-1};
.prev = .i | .i = $i | .index +=1;
if .prev and $i != .prev then .index, break $out else empty end)
// null ;
def lpad($n): " "*($n-length) + "\"\(.)\"" ;
[" "*10, "length", "same", "index", "char"],
(inputs
| firstdifferent as $d
| [lpad(10), length, ($d == null)] + (if $d then [$d, .[$d:$d+1]] else null end) )
| @tsv
' |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia | firstdifferent(s) = isempty(s) ? nothing : findfirst(x -> x != s[1], s)
function testfunction(strings)
println("String | Length | All Same | First Different(Hex) | Position\n" *
"-----------------------------------------------------------------------------")
for s in strings
n = firstdifferent(s)
println(rpad(s, 27), rpad(length(s), 9), n == nothing ? "yes" :
rpad("no $(s[n]) ($(string(Int(s[n]), base=16)))", 36) * string(n))
end
end
testfunction([
"",
" ",
"2",
"333",
".55",
"tttTTT",
"4444 444k",
"pépé",
"🐶🐶🐺🐶",
"🎄🎄🎄🎄",
])
|
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Perl | Perl |
use threads;
use threads::shared;
my @names = qw(Aristotle Kant Spinoza Marx Russell);
my @forks = ('On Table') x @names;
share $forks[$_] for 0 .. $#forks;
sub pick_up_forks {
my $philosopher = shift;
my ($first, $second) = ($philosopher, $philosopher-1);
($first, $second) = ($second, $first) if $philosopher % 2;
for my $fork ( @forks[ $first, $second ] ) {
lock $fork;
cond_wait($fork) while $fork ne 'On Table';
$fork = 'In Hand';
}
}
sub drop_forks {
my $philosopher = shift;
for my $fork ( @forks[$philosopher, $philosopher-1] ) {
lock $fork;
die unless $fork eq 'In Hand';
$fork = 'On Table';
cond_signal($fork);
}
}
sub philosopher {
my $philosopher = shift;
my $name = $names[$philosopher];
for my $meal ( 1..5 ) {
print $name, " is pondering\n";
sleep 1 + rand 8;
print $name, " is hungry\n";
pick_up_forks( $philosopher );
print $name, " is eating\n";
sleep 1 + rand 8;
drop_forks( $philosopher );
}
print $name, " is done\n";
}
my @t = map { threads->new(\&philosopher, $_) } 0 .. $#names;
for my $thread ( @t ) {
$thread->join;
}
print "Done\n";
__END__
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Phix | Phix | with javascript_semantics
constant seasons = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"},
weekday = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"},
apostle = {"Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"},
holiday = {"Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"}
function discordianDate(sequence dt)
integer {y,m,d} = dt,
leap = is_leap_year(y),
doy = day_of_year(y,m,d)-1
string dyear = sprintf("%d",y+1166)
if leap and m=2 and d=29 then
return "St. Tib's Day, in the YOLD " & dyear
end if
if leap and doy>=60 then
doy -= 1
end if
integer dsday = remainder(doy,73)+1,
dseason = floor(doy/73+1)
if dsday=5 then
return apostle[dseason] & ", in the YOLD " & dyear
elsif dsday=50 then
return holiday[dseason] & ", in the YOLD " & dyear
end if
string dseas = seasons[dseason],
dwday = weekday[remainder(doy,5)+1]
return sprintf("%s, day %d of %s in the YOLD %s", {dwday, dsday, dseas, dyear})
end function
-- test code
sequence dt = {2015,1,1,0,0,0,0,0}
include timedate.e
atom oneday = timedelta(days:=1)
set_timedate_formats({"DD/MM/YYYY"})
for i=1 to 5 do
printf(1,"%s: %s\n",{format_timedate(dt),discordianDate(dt)})
dt = adjust_timedate(dt,oneday*72)
printf(1,"%s: %s\n",{format_timedate(dt),discordianDate(dt)})
dt = adjust_timedate(dt,oneday)
end for
|
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #Phix | Phix | with javascript_semantics
--requires("1.0.2") -- (builtin E renamed as EULER)
--enum A,B,C,D,E,F
constant A=1, B=2, C=3, D=4, E=5, F=6 -- (or use this)
constant edges = {{A,B,7},
{A,C,9},
{A,F,14},
{B,C,10},
{B,D,15},
{C,D,11},
{C,F,2},
{D,E,6},
{E,F,9}}
sequence visited,
cost,
from
procedure reset()
visited = repeat(0,6)
cost = repeat(0,6)
from = repeat(0,6)
end procedure
function backtrack(integer finish,start)
sequence res = {finish}
while finish!=start do
finish = from[finish]
res = prepend(res,finish)
end while
return res
end function
function shortest_path(integer start, integer finish)
integer estart, eend, ecost, ncost, mincost
while 1 do
visited[start] = 1
for i=1 to length(edges) do
{estart,eend,ecost} = edges[i]
if estart=start then
ncost = cost[start]+ecost
if visited[eend]=0 then
if from[eend]=0
or cost[eend]>ncost then
cost[eend] = ncost
from[eend] = start
end if
elsif cost[eend]>ncost then
?9/0 -- sanity check
end if
end if
end for
mincost = 0
for i=1 to length(visited) do
if visited[i]=0
and from[i]!=0 then
if mincost=0
or cost[i]<mincost then
start = i
mincost = cost[start]
end if
end if
end for
if visited[start] then return -1 end if
if start=finish then return cost[finish] end if
end while
end function
function AFi(integer i) -- output helper
return 'A'+i-1
end function
procedure test(sequence testset)
integer start, finish, ecost, len
string epath, path
for i=1 to length(testset) do
{start,finish,ecost,epath} = testset[i]
reset()
len = shortest_path(start,finish)
path = iff(len=-1?"no path found":join(apply(backtrack(finish,start),AFi),""))
printf(1,"%c->%c: length %d:%s (expected %d:%s)\n",{AFi(start),AFi(finish),len,path,ecost,epath})
end for
end procedure
test({{A,E,26,"ACDE"},{A,F,11,"ACF"},{F,A,-1,"none"}})
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #K | K |
/ print digital root and additive persistence
prt: {`"Digital root = ", x, `"Additive persistence = ",y}
/ sum of digits of an integer
sumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d}
/ compute digital root and additive persistence
digroot: {sm::sumdig x; ap::0; (9<){sm::sumdig x;ap::ap+1; x:sm}/x; prt[sm;ap]}
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Kotlin | Kotlin | // version 1.0.6
fun sumDigits(n: Long): Int = when {
n < 0L -> throw IllegalArgumentException("Negative numbers not allowed")
else -> {
var sum = 0
var nn = n
while (nn > 0L) {
sum += (nn % 10).toInt()
nn /= 10
}
sum
}
}
fun digitalRoot(n: Long): Pair<Int, Int> = when {
n < 0L -> throw IllegalArgumentException("Negative numbers not allowed")
n < 10L -> Pair(n.toInt(), 0)
else -> {
var dr = n
var ap = 0
while (dr > 9L) {
dr = sumDigits(dr).toLong()
ap++
}
Pair(dr.toInt(), ap)
}
}
fun main(args: Array<String>) {
val a = longArrayOf(1, 14, 267, 8128, 627615, 39390, 588225, 393900588225)
for (n in a) {
val(dr, ap) = digitalRoot(n)
println("${n.toString().padEnd(12)} has additive persistence $ap and digital root of $dr")
}
} |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #zkl | zkl | fcn mdroot(n){ // Multiplicative digital root
mdr := List(n);
while (mdr[-1] > 9){
mdr.append(mdr[-1].split().reduce('*,1));
}
return(mdr.len() - 1, mdr[-1]);
} |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #Prolog | Prolog | :- use_module(library(clpfd)).
:- dynamic top/1, bottom/1.
% Baker does not live on the top floor
rule1(L) :-
member((baker, F), L),
top(Top),
F #\= Top.
% Cooper does not live on the bottom floor.
rule2(L) :-
member((cooper, F), L),
bottom(Bottom),
F #\= Bottom.
% Fletcher does not live on either the top or the bottom floor.
rule3(L) :-
member((fletcher, F), L),
top(Top),
bottom(Bottom),
F #\= Top,
F #\= Bottom.
% Miller lives on a higher floor than does Cooper.
rule4(L) :-
member((miller, Fm), L),
member((cooper, Fc), L),
Fm #> Fc.
% Smith does not live on a floor adjacent to Fletcher's.
rule5(L) :-
member((smith, Fs), L),
member((fletcher, Ff), L),
abs(Fs-Ff) #> 1.
% Fletcher does not live on a floor adjacent to Cooper's.
rule6(L) :-
member((cooper, Fc), L),
member((fletcher, Ff), L),
abs(Fc-Ff) #> 1.
init(L) :-
% we need to define top and bottom
assert(bottom(1)),
length(L, Top),
assert(top(Top)),
% we say that they are all in differents floors
bagof(F, X^member((X, F), L), LF),
LF ins 1..Top,
all_different(LF),
% Baker does not live on the top floor
rule1(L),
% Cooper does not live on the bottom floor.
rule2(L),
% Fletcher does not live on either the top or the bottom floor.
rule3(L),
% Miller lives on a higher floor than does Cooper.
rule4(L),
% Smith does not live on a floor adjacent to Fletcher's.
rule5(L),
% Fletcher does not live on a floor adjacent to Cooper's.
rule6(L).
solve(L) :-
bagof(F, X^member((X, F), L), LF),
label(LF).
dinners :-
retractall(top(_)), retractall(bottom(_)),
L = [(baker, _Fb), (cooper, _Fc), (fletcher, _Ff), (miller, _Fm), (smith, _Fs)],
init(L),
solve(L),
maplist(writeln, L).
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Java | Java | public class DotProduct {
public static void main(String[] args) {
double[] a = {1, 3, -5};
double[] b = {4, -2, -1};
System.out.println(dotProd(a,b));
}
public static double dotProd(double[] a, double[] b){
if(a.length != b.length){
throw new IllegalArgumentException("The dimensions have to be equal!");
}
double sum = 0;
for(int i = 0; i < a.length; i++){
sum += a[i] * b[i];
}
return sum;
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phix | Phix | with javascript_semantics
constant tests = {"", " ",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,"-",
"..1111111111111111111111111111111111111111111111111111111111111117777888","7",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",".",
" --- Harry S Truman "," -r"},
fmt = """
length %2d input: <<<%s>>>
length %2d squeeze(%c): <<<%s>>>
"""
function squeeze(sequence s, integer ch)
if length(s)>1 then
integer outdx = 1
object prev = s[1]
for i=2 to length(s) do
if s[i]!=prev or prev!=ch then
prev = s[i]
outdx += 1
s[outdx] = prev
end if
end for
s = s[1..outdx]
end if
return s
end function
for i=1 to length(tests) by 2 do
string ti = tests[i], chars = tests[i+1]
for j=1 to length(chars) do
string si = squeeze(ti,chars[j])
printf(1,fmt,{length(ti),ti,length(si),chars[j],si})
end for
end for
|
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Phix | Phix | with javascript_semantics
function funnel(sequence dxs, integer rule)
atom x = 0.0
sequence rxs = {}
for i=1 to length(dxs) do
atom dx = dxs[i]
rxs = append(rxs,x + dx)
switch rule
case 2: x = -dx
case 3: x = -(x+dx)
case 4: x = x+dx
end switch
end for
return rxs
end function
function mean(sequence xs)
return sum(xs)/length(xs)
end function
function stddev(sequence xs)
atom m = mean(xs)
return sqrt(sum(sq_power(sq_sub(xs,m),2))/length(xs))
end function
procedure experiment(integer n, sequence dxs, dys)
sequence rxs = funnel(dxs,n),
rys = funnel(dys,n)
printf(1,"Mean x, y : %7.4f, %7.4f\n",{mean(rxs), mean(rys)})
printf(1,"Std dev x, y : %7.4f, %7.4f\n",{stddev(rxs), stddev(rys)})
end procedure
constant dxs = {-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087}
constant dys = { 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032}
for i=1 to 4 do
experiment(i, dxs, dys)
end for
|
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #AWK | AWK |
# syntax: GAWK -f DEPARTMENT_NUMBERS.AWK
BEGIN {
print(" # FD PD SD")
for (fire=1; fire<=7; fire++) {
for (police=1; police<=7; police++) {
for (sanitation=1; sanitation<=7; sanitation++) {
if (rules() ~ /^1+$/) {
printf("%2d %2d %2d %2d\n",++count,fire,police,sanitation)
}
}
}
}
exit(0)
}
function rules( stmt1,stmt2,stmt3) {
stmt1 = fire != police && fire != sanitation && police != sanitation
stmt2 = fire + police + sanitation == 12
stmt3 = police % 2 == 0
return(stmt1 stmt2 stmt3)
}
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Go | Go | package main
import "fmt"
type Delegator struct {
delegate interface{} // the delegate may be any type
}
// interface that represents anything that supports thing()
type Thingable interface {
thing() string
}
func (self Delegator) operation() string {
if v, ok := self.delegate.(Thingable); ok {
return v.thing()
}
return "default implementation"
}
type Delegate int // any dummy type
func (Delegate) thing() string {
return "delegate implementation"
}
func main() {
// Without a delegate:
a := Delegator{}
fmt.Println(a.operation()) // prints "default implementation"
// With a delegate that does not implement "thing"
a.delegate = "A delegate may be any object"
fmt.Println(a.operation()) // prints "default implementation"
// With a delegate:
var d Delegate
a.delegate = d
fmt.Println(a.operation()) // prints "delegate implementation"
} |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Io | Io | Delegator := Object clone do(
delegate ::= nil
operation := method(
if((delegate != nil) and (delegate hasSlot("thing")),
delegate thing,
"default implementation"
)
)
)
Delegate := Object clone do(
thing := method("delegate implementation")
)
a := clone Delegator
a operation println
a setDelegate("A delegate may be any object")
a operation println
a setDelegate(Delegate clone)
a operation println |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #Kotlin | Kotlin | // version 1.1.0
typealias Point = Pair<Double, Double>
data class Triangle(var p1: Point, var p2: Point, var p3: Point) {
override fun toString() = "Triangle: $p1, $p2, $p3"
}
fun det2D(t: Triangle): Double {
val (p1, p2, p3) = t
return p1.first * (p2.second - p3.second) +
p2.first * (p3.second - p1.second) +
p3.first * (p1.second - p2.second)
}
fun checkTriWinding(t: Triangle, allowReversed: Boolean) {
val detTri = det2D(t)
if (detTri < 0.0) {
if (allowReversed) {
val a = t.p3
t.p3 = t.p2
t.p2 = a
}
else throw RuntimeException("Triangle has wrong winding direction")
}
}
fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps
fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps
fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0,
allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean {
// Triangles must be expressed anti-clockwise
checkTriWinding(t1, allowReversed)
checkTriWinding(t2, allowReversed)
// 'onBoundary' determines whether points on boundary are considered as colliding or not
val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk
val lp1 = listOf(t1.p1, t1.p2, t1.p3)
val lp2 = listOf(t2.p1, t2.p2, t2.p3)
// for each edge E of t1
for (i in 0 until 3) {
val j = (i + 1) % 3
// Check all points of t2 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &&
chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &&
chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false
}
// for each edge E of t2
for (i in 0 until 3) {
val j = (i + 1) % 3
// Check all points of t1 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &&
chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &&
chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false
}
// The triangles overlap
return true
}
fun main(args: Array<String>) {
var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)
var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0)
println("$t1 and\n$t2")
println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")
// need to allow reversed for this pair to avoid exception
t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0)
t2 = t1
println("\n$t1 and\n$t2")
println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap")
t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)
t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0)
println("\n$t1 and\n$t2")
println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")
t1.p3 = 2.5 to 5.0
t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0)
println("\n$t1 and\n$t2")
println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")
t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0)
t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0)
println("\n$t1 and\n$t2")
println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")
t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0)
println("\n$t1 and\n$t2")
println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")
t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0)
t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1)
println("\n$t1 and\n$t2")
println("which have only a single corner in contact, if boundary points collide")
println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")
println("\n$t1 and\n$t2")
println("which have only a single corner in contact, if boundary points do not collide")
println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap")
} |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Delphi | Delphi | procedure TMain.btnDeleteClick(Sender: TObject);
var
CurrentDirectory : String;
begin
CurrentDirectory := GetCurrentDir;
DeleteFile(CurrentDirectory + '\input.txt');
RmDir(PChar(CurrentDirectory + '\docs'));
DeleteFile('c:\input.txt');
RmDir(PChar('c:\docs'));
end;
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #E | E | <file:input.txt>.delete(null)
<file:docs>.delete(null)
<file:///input.txt>.delete(null)
<file:///docs>.delete(null) |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #Kotlin | Kotlin | // version 1.1.2
typealias Matrix = Array<DoubleArray>
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
val p = IntArray(n) { it } // permutation
val q = IntArray(n) { it } // inverse permutation
val d = IntArray(n) { -1 } // direction = 1 or -1
var sign = 1
val perms = mutableListOf<IntArray>()
val signs = mutableListOf<Int>()
fun permute(k: Int) {
if (k >= n) {
perms.add(p.copyOf())
signs.add(sign)
sign *= -1
return
}
permute(k + 1)
for (i in 0 until k) {
val z = p[q[k] + d[k]]
p[q[k]] = z
p[q[k] + d[k]] = k
q[z] = q[k]
q[k] += d[k]
permute(k + 1)
}
d[k] *= -1
}
permute(0)
return perms to signs
}
fun determinant(m: Matrix): Double {
val (sigmas, signs) = johnsonTrotter(m.size)
var sum = 0.0
for ((i, sigma) in sigmas.withIndex()) {
var prod = 1.0
for ((j, s) in sigma.withIndex()) prod *= m[j][s]
sum += signs[i] * prod
}
return sum
}
fun permanent(m: Matrix) : Double {
val (sigmas, _) = johnsonTrotter(m.size)
var sum = 0.0
for (sigma in sigmas) {
var prod = 1.0
for ((i, s) in sigma.withIndex()) prod *= m[i][s]
sum += prod
}
return sum
}
fun main(args: Array<String>) {
val m1 = arrayOf(
doubleArrayOf(1.0)
)
val m2 = arrayOf(
doubleArrayOf(1.0, 2.0),
doubleArrayOf(3.0, 4.0)
)
val m3 = arrayOf(
doubleArrayOf(2.0, 9.0, 4.0),
doubleArrayOf(7.0, 5.0, 3.0),
doubleArrayOf(6.0, 1.0, 8.0)
)
val m4 = arrayOf(
doubleArrayOf( 1.0, 2.0, 3.0, 4.0),
doubleArrayOf( 4.0, 5.0, 6.0, 7.0),
doubleArrayOf( 7.0, 8.0, 9.0, 10.0),
doubleArrayOf(10.0, 11.0, 12.0, 13.0)
)
val matrices = arrayOf(m1, m2, m3, m4)
for (m in matrices) {
println("m${m.size} -> ")
println(" determinant = ${determinant(m)}")
println(" permanent = ${permanent(m)}\n")
}
} |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Factor | Factor | USE: math.floats.env
: try-div ( a b -- )
'[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ; |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Fancy | Fancy | def divide: x by: y {
try {
x / y
} catch DivisionByZeroError => e {
e message println # prints error message
}
}
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Delphi | Delphi |
function IsNumericString(const inStr: string): Boolean;
var
i: extended;
begin
Result := TryStrToFloat(inStr,i);
end;
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Dyalect | Dyalect | func String.IsNumeric() {
try {
parse(this) is Integer or Float
} catch _ {
false
}
}
var str = "1234567"
print(str.IsNumeric()) |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Groovy | Groovy | class StringUniqueCharacters {
static void main(String[] args) {
printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions")
printf("%-40s %2s %10s %8s %s %s%n", "------------------------", "------", "----------", "--------", "---", "---------")
for (String s : ["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]) {
processString(s)
}
}
private static void processString(String input) {
Map<Character, Integer> charMap = new HashMap<>()
char dup = 0
int index = 0
int pos1 = -1
int pos2 = -1
for (char key : input.toCharArray()) {
index++
if (charMap.containsKey(key)) {
dup = key
pos1 = charMap.get(key)
pos2 = index
break
}
charMap.put(key, index)
}
String unique = (int) dup == 0 ? "yes" : "no"
String diff = (int) dup == 0 ? "" : "'" + dup + "'"
String hex = (int) dup == 0 ? "" : Integer.toHexString((int) dup).toUpperCase()
String position = (int) dup == 0 ? "" : pos1 + " " + pos2
printf("%-40s %-6d %-10s %-8s %-3s %-5s%n", input, input.length(), unique, diff, hex, position)
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #NetLogo | NetLogo |
to-report split [ string ]
;; utility reporter to split a string into a list
report n-values length string [ [ n ] -> item n string ]
end
to-report collapse [ string ]
;; reporter that actually does the collapse function
ifelse ( string = "" )
[ report "" ]
[ report reduce [ [ a b ] -> (word a ifelse-value last a != b [ b ] [ "" ] ) ] split string ]
end
to-report format [ string ]
;; reporter to format the output as required
report ( word "<<<" string ">>> " length string )
end
to demo-collapse [ string ]
;; procedure to display the required output
output-print format string
output-print format collapse string
end
to demo
;; procedure to perform the test cases
foreach
[ ""
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
"..1111111111111111111111111111111111111111111111111111111111111117777888"
"I never give 'em hell, I just tell the truth, and they think it's hell. "
" --- Harry S Truman "
]
demo-collapse
end
|
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import unicode, strformat
proc collapse(s: string) =
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var collapsed: seq[Rune]
for rune in original:
if rune != previous:
collapsed.add(rune)
previous = rune
echo fmt"Collapsed: length = {collapsed.len}, string = «««{collapsed}»»»"
echo ""
const Strings = ["",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",]
for s in Strings:
s.collapse() |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | use strict;
use warnings;
use utf8;
binmode STDOUT, ":utf8";
my @lines = split "\n", <<~'STRINGS';
"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
..1111111111111111111111111111111111111111111111111111111111111117777888
I never give 'em hell, I just tell the truth, and they think it's hell.
--- Harry S Truman
The American people have a right to know if their president is a crook.
--- Richard Nixon
AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
STRINGS
for (@lines) {
my $squish = s/(.)\1+/$1/gr;
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
length($_), $_, $_ ne $squish ? 'True' : 'False', length($squish), $squish
} |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | fun analyze(s: String) {
println("Examining [$s] which has a length of ${s.length}:")
if (s.length > 1) {
val b = s[0]
for ((i, c) in s.withIndex()) {
if (c != b) {
println(" Not all characters in the string are the same.")
println(" '$c' (0x${Integer.toHexString(c.toInt())}) is different at position $i")
return
}
}
}
println(" All characters in the string are the same.")
}
fun main() {
val strs = listOf("", " ", "2", "333", ".55", "tttTTT", "4444 444k")
for (str in strs) {
analyze(str)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.