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/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
| #Clojure | Clojure |
(defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)" out (count out)))))
|
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
| #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
sub squeeze(ch: uint8, str: [uint8], buf: [uint8]): (r: [uint8]) is
r := buf;
var prev: uint8 := 0;
while [str] != 0 loop
if prev != ch or [str] != ch then
prev := [str];
[buf] := prev;
buf := @next buf;
end if;
str := @next str;
end loop;
[buf] := 0;
end sub;
sub squeezeAndPrint(ch: uint8, str: [uint8]) is
sub bracketLength(str: [uint8]) is
print_i32(StrLen(str) as uint32);
print(" <<<");
print(str);
print(">>>\n");
end sub;
var buf: uint8[256];
bracketLength(str);
bracketLength(squeeze(ch, str, &buf[0]));
print_nl();
end sub;
var strs: [uint8][] := {
"",
"\"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 "
};
squeezeAndPrint(' ', strs[0]);
squeezeAndPrint('-', strs[1]);
squeezeAndPrint('7', strs[2]);
squeezeAndPrint('.', strs[3]);
squeezeAndPrint(' ', strs[4]);
squeezeAndPrint('-', strs[4]);
squeezeAndPrint('r', strs[4]); |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Arturo | Arturo | descending: @[
loop 1..9 'a [
loop 1..dec a 'b [
loop 1..dec b 'c [
loop 1..dec c 'd [
loop 1..dec d 'e [
loop 1..dec e 'f [
loop 1..dec f 'g [
loop 1..dec g 'h [
loop 1..dec h 'i -> @[a b c d e f g h i]
@[a b c d e f g h]]
@[a b c d e f g]]
@[a b c d e f]]
@[a b c d e]]
@[a b c d]]
@[a b c]]
@[a b]]
@[a]]
]
descending: filter descending 'd -> some? d 'n [not? positive? n]
descending: filter descending 'd -> d <> unique d
descending: sort map descending 'd -> to :integer join to [:string] d
loop split.every:10 select descending => prime? 'row [
print map to [:string] row 'item -> pad item 8
] |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #AWK | AWK |
# syntax: GAWK -f DESCENDING_PRIMES.AWK
BEGIN {
start = 1
stop = 99999999
for (i=start; i<=stop; i++) {
leng = length(i)
flag = 1
for (j=1; j<leng; j++) {
if (substr(i,j,1) <= substr(i,j+1,1)) {
flag = 0
break
}
}
if (flag) {
if (is_prime(i)) {
printf("%9d%1s",i,++count%10?"":"\n")
}
}
}
printf("\n%d-%d: %d descending primes\n",start,stop,count)
exit(0)
}
function is_prime(n, d) {
d = 5
if (n < 2) { return(0) }
if (n % 2 == 0) { return(n == 2) }
if (n % 3 == 0) { return(n == 3) }
while (d*d <= n) {
if (n % d == 0) { return(0) }
d += 2
if (n % d == 0) { return(0) }
d += 4
}
return(1)
}
|
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)
| #AutoHotkey | AutoHotkey | TrianglesIntersect(T1, T2){ ; T1 := [[x1,y1],[x2,y2],[x3,y3]] , T2 :=[[x4,y4],[x5,y5],[x6,y6]]
counter := 0
for i, Pt in T1
counter += PointInTriangle(Pt, T2) ; check if any coordinate of triangle 1 is inside triangle 2
for i, Pt in T2
counter += PointInTriangle(Pt, T1) ; check if any coordinate of triangle 2 is inside triangle 1
; check if sides of triangle 1 intersect with sides of triangle 2
counter += LinesIntersect([t1.1,t1.2],[t2.1,t2.2]) ? 1 : 0
counter += LinesIntersect([t1.1,t1.3],[t2.1,t2.2]) ? 1 : 0
counter += LinesIntersect([t1.2,t1.3],[t2.1,t2.2]) ? 1 : 0
counter += LinesIntersect([t1.1,t1.2],[t2.1,t2.3]) ? 1 : 0
counter += LinesIntersect([t1.1,t1.3],[t2.1,t2.3]) ? 1 : 0
counter += LinesIntersect([t1.2,t1.3],[t2.1,t2.3]) ? 1 : 0
counter += LinesIntersect([t1.1,t1.2],[t2.2,t2.3]) ? 1 : 0
counter += LinesIntersect([t1.1,t1.3],[t2.2,t2.3]) ? 1 : 0
counter += LinesIntersect([t1.2,t1.3],[t2.2,t2.3]) ? 1 : 0
return (counter>3) ; 3 points inside or 1 point inside and 2 lines intersect or 3 lines intersect
}
PointInTriangle(pt, Tr){ ; pt:=[x,y] , Tr := [[x1,y1],[x2,y2],[x3,y3]]
v1 := Tr.1, v2 := Tr.2, v3 := Tr.3
d1 := sign(pt, v1, v2)
d2 := sign(pt, v2, v3)
d3 := sign(pt, v3, v1)
has_neg := (d1 < 0) || (d2 < 0) || (d3 < 0)
has_pos := (d1 > 0) || (d2 > 0) || (d3 > 0)
return !(has_neg && has_pos)
}
sign(p1, p2, p3){
return (p1.1 - p3.1) * (p2.2 - p3.2) - (p2.1 - p3.1) * (p1.2 - p3.2)
}
LinesIntersect(L1, L2){ ; L1 := [[x1,y1],[x2,y2]] , L2 := [[x3,y3],[x4,y4]]
x1 := L1[1,1], y1 := L1[1,2]
x2 := L1[2,1], y2 := L1[2,2]
x3 := L2[1,1], y3 := L2[1,2]
x4 := L2[2,1], y4 := L2[2,2]
x := ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))
y := ((x1*y2-y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)) / ((x1-x2)*(y3-y4) - (y1-y2)*(x3-x4))
if (x<>"" && y<>"") && isBetween(x, x1, x2) && isBetween(x, x3, x4) && isBetween(y, y1, y2) && isBetween(y, y3, y4)
return 1
}
isBetween(x, p1, p2){
return !((x>p1 && x>p2) || (x<p1 && x<p2))
} |
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
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
using Matrix = std::vector<std::vector<double>>;
Matrix squareMatrix(size_t n) {
Matrix m;
for (size_t i = 0; i < n; i++) {
std::vector<double> inner;
for (size_t j = 0; j < n; j++) {
inner.push_back(nan(""));
}
m.push_back(inner);
}
return m;
}
Matrix minor(const Matrix &a, int x, int y) {
auto length = a.size() - 1;
auto result = squareMatrix(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 {
result[i][j] = a[i + 1][j + 1];
}
}
}
return result;
}
double det(const Matrix &a) {
if (a.size() == 1) {
return a[0][0];
}
int sign = 1;
double sum = 0;
for (size_t i = 0; i < a.size(); i++) {
sum += sign * a[0][i] * det(minor(a, 0, i));
sign *= -1;
}
return sum;
}
double perm(const Matrix &a) {
if (a.size() == 1) {
return a[0][0];
}
double sum = 0;
for (size_t i = 0; i < a.size(); i++) {
sum += a[0][i] * perm(minor(a, 0, i));
}
return sum;
}
void test(const Matrix &m) {
auto p = perm(m);
auto d = det(m);
std::cout << m << '\n';
std::cout << "Permanent: " << p << ", determinant: " << d << "\n\n";
}
int main() {
test({ {1, 2}, {3, 4} });
test({ {1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13} });
test({ {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} });
return 0;
} |
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.
| #ALGOL_68 | ALGOL 68 | PROC raise exception= ([]STRING args)VOID: (
put(stand error, ("Exception: ",args, newline));
stop
);
PROC raise zero division error := VOID:
raise exception("integer division or modulo by zero");
PROC int div = (INT a,b)REAL: a/b;
PROC int over = (INT a,b)INT: a%b;
PROC int mod = (INT a,b)INT: a%*b;
BEGIN
OP / = (INT a,b)REAL: ( b = 0 | raise zero division error; SKIP | int div (a,b) );
OP % = (INT a,b)INT: ( b = 0 | raise zero division error; SKIP | int over(a,b) );
OP %* = (INT a,b)INT: ( b = 0 | raise zero division error; SKIP | int mod (a,b) );
PROC a different handler = VOID: (
put(stand error,("caught division by zero",new line));
stop
);
INT x:=1, y:=0;
raise zero division error := a different handler;
print(x/y)
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
| #ALGOL_W | ALGOL W | begin
% determnines whether the string contains an integer, real or imaginary %
% number. Returns true if it does, false otherwise %
logical procedure isNumeric( string(32) value text ) ;
begin
logical ok;
% the "number" cannot be blank %
ok := ( text not = " " );
if ok then begin
% there is at least one non-blank character %
% must have either an integer or real/immaginary number %
% integer: [+|-]digit-sequence %
% real: [+|-][digit-sequence].digit-sequence['integer][L] %
% or: [+|-]digit-sequence[.[digit-sequence]]'integer[L] %
% imaginary: %
% [+|-][digit-sequence].digit-sequence['integer][L]I%
% or: [+|-]digit-sequence[.[digit-sequence]]'integer[L]I%
% The "I" at the end of an imaginary number can appear %
% before or after the "L" (which indicates a long number) %
% the "I" and "L" can be in either case %
procedure nextChar ; charPos := charPos + 1;
logical procedure have( string(1) value ch ) ;
( charPos <= maxChar and text(charPos//1) = ch ) ;
logical procedure haveDigit ;
( charPos <= maxChar and text(charPos//1) >= "0" and text(charPos//1) <= "9" ) ;
integer charPos, maxChar;
logical hadDigits, isReal;
charPos := 0;
maxChar := 31;
hadDigits := false;
isReal := false;
% skip trailing spaces %
while maxChar > 0 and text(maxChar//1) = " " do maxChar := maxChar - 1;
% skip leading spacesx %
while have( " " ) do nextChar;
% skip optional sign %
if have( "+" ) or have( "-" ) then nextChar;
if haveDigit then begin
% have a digit sequence %
hadDigits := true;
while haveDigit do nextChar
end if_have_sign ;
if have( "." ) then begin
% real or imaginary number %
nextChar;
isReal := true;
hadDigits := hadDigits or haveDigit;
while haveDigit do nextChar
end if_have_point ;
% should have had some digits %
ok := hadDigits;
if ok and have( "'" ) then begin
% the number has an exponent %
isReal := true;
nextChar;
% skip optional sign %
if have( "+" ) or have( "-" ) then nextChar;
% must have a digit sequence %
ok := haveDigit;
while haveDigit do nextChar;
end if_ok_and_have_exponent ;
% if it is a real number, there could be L/I suffixes %
if ok and isReal then begin
integer LCount, ICount;
LCount := 0;
ICount := 0;
while have( "L" ) or have( "l" ) or have( "I" ) or have( "i" ) do begin
if have( "L" ) or have( "l" )
then LCount := LCount + 1
else ICount := ICount + 1;
nextChar
end while_have_L_or_I ;
% there can be at most one L and at most 1 I %
ok := ( LCount < 2 and ICount < 2 )
end if_ok_and_isReal ;
% must now be at the end if the number %
ok := ok and charPos >= maxChar
end if_ok ;
ok
end isNumeric ;
% test the isNumeric procedure %
procedure testIsNumeric( string(32) value n
; logical value expectedResult
) ;
begin
logical actualResult;
actualResult := isNumeric( n );
write( s_w := 0
, """", n, """ is "
, if actualResult then "" else "not "
, "numeric "
, if actualResult = expectedResult then "" else " NOT "
, "as expected"
)
end testIsNumeric ;
testIsNumeric( "", false );
testIsNumeric( "b", false );
testIsNumeric( ".", false );
testIsNumeric( ".'3", false );
testIsNumeric( "3.'", false );
testIsNumeric( "0.0z44", false );
testIsNumeric( "-1IL", false );
testIsNumeric( "4.5'23ILL", false );
write( "---------" );
testIsNumeric( "-1", true );
testIsNumeric( " +.345", true );
testIsNumeric( "4.5'23I", true );
testIsNumeric( "-5'+3i", true );
testIsNumeric( "-5'-3l", true );
testIsNumeric( " -.345LI", true );
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
| #Apex | Apex |
String numericString = '123456';
String partlyNumericString = '123DMS';
String decimalString = '123.456';
System.debug(numericString.isNumeric()); // this will be true
System.debug(partlyNumericString.isNumeric()); // this will be false
System.debug(decimalString.isNumeric()); // this will be false
System.debug(decimalString.remove('.').isNumeric()); // this will be 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
| #Arturo | Arturo | strings: [
"", ".", "abcABC", "XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"hétérogénéité",
"🎆🎃🎇🎈", "😍😀🙌💃😍🙌", "🐠🐟🐡🦈🐬🐳🐋🐡"
]
loop strings 'str [
chars: split str
prints ["\"" ++ str ++ "\"" ~"(size |size str|):"]
if? chars = unique chars ->
print "has no duplicates."
else [
seen: #[]
done: false
i: 0
while [and? i<size chars
not? done][
ch: chars\[i]
if? not? key? seen ch [
seen\[ch]: i
]
else [
print ~"has duplicate char `|ch|` on |get seen ch| and |i|"
done: true
]
i: i+1
]
]
] |
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
| #AutoHotkey | AutoHotkey | unique_characters(str){
arr := [], res := ""
for i, v in StrSplit(str)
arr[v] := arr[v] ? arr[v] "," i : i
for i, v in Arr
if InStr(v, ",")
res .= v "|" i " @ " v "`tHex = " format("{1:X}", Asc(i)) "`n"
Sort, res, N
res := RegExReplace(res, "`am)^[\d,]+\|")
res := StrSplit(res, "`n").1
return """" str """`tlength = " StrLen(str) "`n" (res ? "Duplicates Found:`n" res : "Unique Characters")
} |
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
| #C.23 | C# | using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
string[] input = {
"",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"\"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 "
};
foreach (string s in input) {
Console.WriteLine($"old: {s.Length} «««{s}»»»");
string c = Collapse(s);
Console.WriteLine($"new: {c.Length} «««{c}»»»");
}
}
static string Collapse(string s) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != s[i - 1]).Select(i => s[i]).ToArray());
} |
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
| #C.2B.2B | C++ | #include <string>
#include <iostream>
#include <algorithm>
template<typename char_type>
std::basic_string<char_type> collapse(std::basic_string<char_type> str) {
auto i = std::unique(str.begin(), str.end());
str.erase(i, str.end());
return str;
}
void test(const std::string& str) {
std::cout << "original string: <<<" << str << ">>>, length = " << str.length() << '\n';
std::string collapsed(collapse(str));
std::cout << "result string: <<<" << collapsed << ">>>, length = " << collapsed.length() << '\n';
std::cout << '\n';
}
int main(int argc, char** argv) {
test("");
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 ");
return 0;
} |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Ruby | Ruby | def roll_dice(n_dice, n_faces)
return [[0,1]] if n_dice.zero?
one = [1] * n_faces
zero = [0] * (n_faces-1)
(1...n_dice).inject(one){|ary,_|
(zero + ary + zero).each_cons(n_faces).map{|a| a.inject(:+)}
}.map.with_index(n_dice){|n,sum| [sum,n]} # sum: total of the faces
end
def game(dice1, faces1, dice2, faces2)
p1 = roll_dice(dice1, faces1)
p2 = roll_dice(dice2, faces2)
p1.product(p2).each_with_object([0,0,0]) do |((sum1, n1), (sum2, n2)), win|
win[sum1 <=> sum2] += n1 * n2 # [0]:draw, [1]:win, [-1]:lose
end
end
[[9, 4, 6, 6], [5, 10, 6, 7]].each do |d1, f1, d2, f2|
puts "player 1 has #{d1} dice with #{f1} faces each"
puts "player 2 has #{d2} dice with #{f2} faces each"
win = game(d1, f1, d2, f2)
sum = win.inject(:+)
puts "Probability for player 1 to win: #{win[1]} / #{sum}",
" -> #{win[1].fdiv(sum)}", ""
end |
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
| #C.23 | C# | using System;
namespace AllSame {
class Program {
static void Analyze(string s) {
Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length);
if (s.Length > 1) {
var b = s[0];
for (int i = 1; i < s.Length; i++) {
var c = s[i];
if (c != b) {
Console.WriteLine(" Not all characters in the string are the same.");
Console.WriteLine(" '{0}' (0x{1:X02}) is different at position {2}", c, (int)c, i);
return;
}
}
}
Console.WriteLine(" All characters in the string are the same.");
}
static void Main() {
var strs = new string[] { "", " ", "2", "333", ".55", "tttTTT", "4444 444k" };
foreach (var str in strs) {
Analyze(str);
}
}
}
} |
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.
| #J | J | ". noun define -. CRLF NB. Fixed tacit simulation code...
simulate=.
''"_@:((<@:(1 -~ 1&({::)) 1} ])@:(([ 0 0&$@(1!:2&2)@:(((6j3 ": 9&({::)) , ':
'"_) , ' starts waiting and thinking about hunger.' ,~ 8&({::) {:: 0&({::)))@
:(<@:(6&({::) , 8&({::)) 6} ])@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])}
])@:(3 8 2&{)) 2} ])@:(<@:2: 3} ]))@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {::
])} ])@:(5 8 4&{)) 4} ])@:(<@:_: 5} ]))`(([ 0 0&$@(1!:2&2)@:(((6j3 ": 9&({::
)) , ': '"_) , ' starts eating.' ,~ 8&({::) {:: 0&({::)))@:((<@:((0 (0 {:: ])
`(<@:(1 {:: ]))`(2 {:: ])} ])@:(3 8 2&{)) 2} ])@:(<@:1: 3} ]))@:((<@:((0 (0 {
:: ])`(<@:(1 {:: ]))`(2 {:: ])} ])@:(5 8 4&{)) 4} ])@:(<@:(_2 * ^.@:?@:0:) 5}
])))@.(7&({::) > 1 +/@:= 2&({::))`((<@:(}.@:(6&({::))) 6} ])@:(([ 0 0&$@(1!:
2&2)@:(((6j3 ": 9&({::)) , ': '"_) , ' starts eating.' ,~ 8&({::) {:: 0&({::)
))@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])} ])@:(3 8 2&{)) 2} ])@:(<@:1:
3} ]))@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])} ])@:(5 8 4&{)) 4} ])@:(
<@:(_2 * ^.@:?@:0:) 5} ])))@:(<@:({.@:(6&({::))) 8} ])^:(1 <: #@:(6&({::)))@:
([ 0 0&$@(1!:2&2)@:(((6j3 ": 9&({::)) , ': '"_) , ' starts thinking.' ,~ 8&({
::) {:: 0&({::)))@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])} ])@:(3 8 2&{)
) 2} ])@:(<@:0: 3} ]))@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])} ])@:(5 8
4&{)) 4} ])@:(<@:(_1 * ^.@:?@:0:) 5} ])))@.('' ($ ,) 8&({::) { 2&({::)))@:(<
@:(0 I.@:= 4&({::)) 8} ])@:(<@:((- <./)@:(4&({::))) 4} ])@:(<@:(9&({::) + <./
@:(4&({::))) 9} ])^:(0 < 1&({::))^:_)@:(([ 0 0&$@(1!:2&2)@:(((6j3 ": 9&({::))
, ': '"_) , 'All of them start thinking.'"_))@:((0 ; <.@:(2 %~ #@:(0&({::)))
) 9 7} ])@:((0:"_1 ,&< (_1 * ^.@:?@:0:)&>)@:(0&({::)) 2 4} ])@:((;:@:(0&({::)
) ,&< ''"_) 0 6} ]))@:(,&(;:8$','))@:;
) |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
Demo(2010,1,1)
Demo(2010,7,22)
Demo(2012,2,28)
Demo(2012,2,29)
Demo(2012,3,1)
Demo(2010,1,5)
Demo(2011,5,3)
Demo(2012,2,28)
Demo(2012,2,29)
Demo(2012,3,1)
Demo(2010,7,22)
Demo(2012,12,22)
end
procedure Demo(y,m,d) #: demo display
printf("%i-%i-%i = %s\n",y,m,d,DiscordianDateString(DiscordianDate(y,m,d)))
end
record DiscordianDateRecord(year,yday,season,sday,holiday)
procedure DiscordianDate(year,month,day) #: Convert normal date to Discordian
static cal
initial cal := [31,28,31,30,31,30,31,31,30,31,30,31]
ddate := DiscordianDateRecord(year+1166)
every (ddate.yday := day - 1) +:= cal[1 to month-1] # zero origin
ddate.sday := ddate.yday
if ddate.year % 4 = 2 & month = 2 & day = 29 then
ddate.holiday := 1 # Note: st tibs is outside of weekdays
else {
ddate.season := (ddate.yday / 73) + 1
ddate.sday := (ddate.yday % 73) + 1
ddate.holiday := 1 + ddate.season * case ddate.sday of { 5 : 1; 50 : 2}
}
return ddate
end
procedure DiscordianDateString(ddate) #: format a Discordian Date String
static days,seasons,holidays
initial {
days := ["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"]
seasons := ["Chaos","Discord","Confusion","Bureaucracy","The Aftermath"]
holidays := ["St. Tib's Day","Mungday","Chaoflux","Mojoday","Discoflux",
"Syaday","Confuflux","Zaraday","Bureflux","Maladay","Afflux"]
}
return (( holidays[\ddate.holiday] || "," ) |
( days[1+ddate.yday%5] || ", day " ||
ddate.sday || " of " || seasons[ddate.season])) ||
" in the YOLD " || ddate.year
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)
| #jq | jq | # (*) If using gojq, uncomment the following line:
# def keys_unsorted: keys;
# remove the first occurrence of $x from the input array
def rm($x):
index($x) as $ix
| if $ix then .[:$ix] + .[$ix+1:] else . end;
# Input: a Graph
# Output: a (possibly empty) stream of the neighbors of $node
# that are also in the array $ary
def neighbors($node; $ary:
.[$node]
| select(.)
| keys_unsorted[]
| . as $n
| select($ary | index($n));
# Input: a Graph
def vertices:
[keys_unsorted[], (.[] | keys_unsorted[])] | unique;
# Input: a Graph
# Output: the final version of the scratchpad
def dijkstra($startname):
. as $graph
| vertices as $Q
# scratchpad: { node: { prev, dist} }
| reduce $Q[] as $v ({};
. + { ($v): {prev: null, dist: infinite}} )
| .[$startname].dist = 0
| { scratchpad: ., $Q }
| until( .Q|length == 0;
.scratchpad as $scratchpad
| ( .Q | min_by($scratchpad[.].dist)) as $u
| .Q |= rm($u)
| .Q as $Q
# for each neighbor v of u still in Q:
| reduce ($graph|neighbors($u; $Q)) as $v (.;
(.scratchpad[$u].dist + $graph[$u][$v]) as $alt
| if $alt < .scratchpad[$v].dist
then .scratchpad[$v].dist = $alt
| .scratchpad[$v].prev = $u
else . end ) )
| .scratchpad ;
# Input: a Graph
# Output: the scratchpad
def Dijkstra($startname):
if .[$startname] == null then "The graph does not contain start vertex \(startname)"
else dijkstra($startname)
end;
# Input: scratchpad, i.e. a dictionary with key:value pairs of the form:
# node: {prev, dist}
# Output: an array, being
# [optimal path from $node to $n, optimal distance from $node to $n]
def readout($node):
. as $in
| $node
| [recurse($in[.].prev; .)]
| [reverse, $in[$node].dist] ;
# Input: a graph
# Output: [path, value]
def Dijkstra($startname; $endname):
Dijkstra($startname)
| readout($endname) ;
|
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
| #Elena | Elena | import extensions;
import system'routines;
import system'collections;
extension op
{
get DigitalRoot()
{
int additivepersistence := 0;
long num := self;
while (num > 9)
{
num := num.toPrintable().toArray().selectBy:(ch => ch.toInt() - 48).summarize(new LongInteger());
additivepersistence += 1
};
^ new Tuple<int,int>(additivepersistence, num.toInt())
}
}
public program()
{
new long[]{627615l, 39390l, 588225l, 393900588225l}.forEach:(num)
{
var t := num.DigitalRoot;
console.printLineFormatted("{0} has additive persistence {1} and digital root {2}", num, t.Item1, t.Item2)
}
} |
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
| #Elixir | Elixir | defmodule Digital do
def root(n, base\\10), do: root(n, base, 0)
defp root(n, base, ap) when n < base, do: {n, ap}
defp root(n, base, ap) do
Integer.digits(n, base) |> Enum.sum |> root(base, ap+1)
end
end
data = [627615, 39390, 588225, 393900588225]
Enum.each(data, fn n ->
{dr, ap} = Digital.root(n)
IO.puts "#{n} has additive persistence #{ap} and digital root of #{dr}"
end)
base = 16
IO.puts "\nBase = #{base}"
fmt = "~.#{base}B(#{base}) has additive persistence ~w and digital root of ~w~n"
Enum.each(data, fn n ->
{dr, ap} = Digital.root(n, base)
:io.format fmt, [n, ap, dr]
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
| #PicoLisp | PicoLisp | (de mdr-mp (N)
"Returns the solutions in a list, i.e., '(MDR MP)"
(let MP 0
(while (< 1 (length N))
(setq N (apply * (mapcar format (chop N))))
(inc 'MP) )
(list N MP) ) )
# Get the MDR/MP of these nums.
(setq Test-nums '(123321 7739 893 899998))
(let Fmt (6 5 5)
(tab Fmt "Values" "MDR" "MP")
(tab Fmt "======" "===" "==")
(for I Test-nums
(let MDR-MP (mdr-mp I)
(tab Fmt I (car MDR-MP) (cadr MDR-MP)) ) ) )
(prinl)
# Get the nums of these MDRs.
(setq *Want 5)
(setq *Solutions (make (for MDR (range 0 9)
(link (make (let N 0 (until (= *Want (length (made)))
(when (= MDR (car (mdr-mp N)))
(link N) )
(inc 'N) )))) )))
(let Fmt (3 1 -1)
(tab Fmt "MDR" ": " "Values")
(tab Fmt "===" " " "======")
(for (I . S) *Solutions
(tab Fmt (dec I) ": " (glue ", " S)) ) ) |
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
| #Phix | Phix | with javascript_semantics
function mdr_mp(integer m)
integer mp = 0
while m>9 do
integer newm = 1
while m do
newm *= remainder(m,10)
m = floor(m/10)
end while
m = newm
mp += 1
end while
return {m,mp}
end function
constant tests = {123321, 7739, 893, 899998}
printf(1,"Number MDR MP\n")
printf(1,"====== === ==\n")
for i=1 to length(tests) do
integer ti = tests[i]
printf(1,"%6d %6d %6d\n",ti&mdr_mp(ti))
end for
integer i=0, found = 0
sequence res = columnize({tagset(9,0)})
-- (ie {{0},{1},..,{9}})
while found<50 do -- (ie the full 10*5)
integer mdr1 = mdr_mp(i)[1]+1
sequence m1 = res[mdr1]
if length(m1)<6 then
res[mdr1] = 0 -- (avoid p2js violation)
m1 &= i
res[mdr1] = m1
found += 1
end if
i += 1
end while
printf(1,"\nMDR 1 2 3 4 5")
printf(1,"\n=== ===========================\n")
for i=1 to 10 do
printf(1,"%2d %5d %5d %5d %5d %5d\n",res[i])
end for
|
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?
| #jq | jq | # Input: an array representing the apartment house, with null at a
# particular position signifying that the identity of the occupant
# there has not yet been determined.
# Output: an elaboration of the input array but including person, and
# satisfying cond, where . in cond refers to the placement of person
def resides(person; cond):
range(0;5) as $n
| if (.[$n] == null or .[$n] == person) and ($n|cond) then .[$n] = person
else empty # no elaboration is possible
end ;
# English:
def top: 4;
def bottom: 0;
def higher(j): . > j;
def adjacent(j): (. - j) | (. == 1 or . == -1); |
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
| #Factor | Factor | USING: kernel math.vectors sequences ;
: dot-product ( u v -- w )
2dup [ length ] bi@ =
[ v. ] [ "Vector lengths must be equal" throw ] if ; |
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
| #FALSE | FALSE | [[\1-$0=~][$d;2*1+\-ø\$d;2+\-ø@*@+]#]p:
3d: {Vectors' length}
1 3 5_ 4 2_ 1_ d;$1+ø@*p;!%. {Output: 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
| #D | D | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
squeezable(``, ' ');
squeezable(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `, '-');
squeezable(`..1111111111111111111111111111111111111111111111111111111111111117777888`, '7');
squeezable(`I never give 'em hell, I just tell the truth, and they think it's hell. `, '.');
string s = ` --- Harry S Truman `;
squeezable(s, ' ');
squeezable(s, '-');
squeezable(s, '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
| #Delphi | Delphi |
program Determine_if_a_string_is_squeezable;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
TestStrings: TArray<string> = ['',
'''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 ',
'122333444455555666666777777788888888999999999',
'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!',
'headmistressship'];
TestChar: TArray<string> = [' ', '-', '7', '.', ' -r', '5', 'e', 's'];
function squeeze(s: string; include: char): string;
begin
var sb := TStringBuilder.Create;
for var i := 1 to s.Length do
begin
if (i = 1) or (s[i - 1] <> s[i]) or ((s[i - 1] = s[i]) and (s[i] <> include)) then
sb.Append(s[i]
end;
Result := sb.ToString;
sb.Free;
end;
begin
for var testNum := 0 to high(TestStrings) do
begin
var s := TestStrings[testNum];
for var c in TestChar[testNum] do
begin
var result: string := squeeze(s, c);
writeln(format('use: "%s"'#10'old: %2d <<<%s>>>'#10'new: %2d <<<%s>>>'#10, [c,
s.Length, s, result.length, result]));
end;
end;
readln;
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. | #11l | 11l | V dxs = [-0.533, 0.27, 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.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -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.17, 0.054, -0.553, -0.024, -0.181, -0.7, -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.31, 0.171, 0.0, 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]
V dys = [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682,
-0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188,
-0.742, -0.01, 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.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038,
-0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445,
-0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -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.65, -1.103, 0.154, -1.72, 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]
F funnel(dxs, rule)
V x = 0.0
[Float] rxs
L(dx) dxs
rxs.append(x + dx)
x = rule(x, dx)
R rxs
F mean(xs)
R sum(xs) / xs.len
F stddev(xs)
V m = mean(xs)
R sqrt(sum(xs.map(x -> (x - @m) ^ 2)) / xs.len)
F experiment(label, rule)
V (rxs, rys) = (funnel(:dxs, rule), funnel(:dys, rule))
print(label)
print(‘Mean x, y : #.4, #.4’.format(mean(rxs), mean(rys)))
print(‘Std dev x, y : #.4, #.4’.format(stddev(rxs), stddev(rys)))
print()
experiment(‘Rule 1:’, (z, dz) -> 0)
experiment(‘Rule 2:’, (z, dz) -> -dz)
experiment(‘Rule 3:’, (z, dz) -> -(z + dz))
experiment(‘Rule 4:’, (z, dz) -> z + dz) |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #F.23 | F# |
// Descending primes. Nigel Galloway: April 19th., 2022
[2;3;5;7]::List.unfold(fun(n,i)->match n with []->None |_->let n=n|>List.map(fun(n,g)->[for n in n..9->(n+1,i*n+g)])|>List.concat in Some(n|>List.choose(fun(_,n)->if isPrime n then Some n else None),(n|>List.filter(fst>>(>)10),i*10)))([(4,3);(2,1);(8,7)],10)
|>List.concat|>List.sort|>List.iter(printf "%d "); printfn ""
|
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Factor | Factor | USING: grouping grouping.extras math math.combinatorics
math.functions math.primes math.ranges prettyprint sequences
sequences.extras ;
9 1 [a,b] all-subsets [ reverse 0 [ 10^ * + ] reduce-index ]
[ prime? ] map-filter 10 "" pad-groups 10 group simple-table. |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #FreeBASIC | FreeBASIC | #include "isprime.bas"
#include "sort.bas"
Dim As Double t0 = Timer
Dim As Integer i, n, tmp, num, cant
Dim Shared As Integer matriz(512)
For i = 0 To 511
n = 0
tmp = i
num = 9
While tmp
If tmp And 1 Then n = n * 10 + num
tmp = tmp Shr 1
num -= 1
Wend
matriz(i) = n
Next i
Sort(matriz())
cant = 0
For i = 1 To Ubound(matriz)-1
n = matriz(i)
If IsPrime(n) Then
Print Using "#########"; n;
cant += 1
If cant Mod 10 = 0 Then Print
End If
Next i
Print Using !"\n\nThere are & descending primes."; cant
Sleep |
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)
| #C | C | #include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double x, y;
} Point;
double det2D(const Point * const p1, const Point * const p2, const Point * const p3) {
return p1->x * (p2->y - p3->y)
+ p2->x * (p3->y - p1->y)
+ p3->x * (p1->y - p2->y);
}
void checkTriWinding(Point * p1, Point * p2, Point * p3, bool allowReversed) {
double detTri = det2D(p1, p2, p3);
if (detTri < 0.0) {
if (allowReversed) {
double t = p3->x;
p3->x = p2->x;
p2->x = t;
t = p3->y;
p3->y = p2->y;
p2->y = t;
} else {
errno = 1;
}
}
}
bool boundaryCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {
return det2D(p1, p2, p3) < eps;
}
bool boundaryDoesntCollideChk(const Point *p1, const Point *p2, const Point *p3, double eps) {
return det2D(p1, p2, p3) <= eps;
}
bool triTri2D(Point t1[], Point t2[], double eps, bool allowReversed, bool onBoundary) {
bool(*chkEdge)(Point*, Point*, Point*, double);
int i;
// Triangles must be expressed anti-clockwise
checkTriWinding(&t1[0], &t1[1], &t1[2], allowReversed);
if (errno != 0) {
return false;
}
checkTriWinding(&t2[0], &t2[1], &t2[2], allowReversed);
if (errno != 0) {
return false;
}
if (onBoundary) {
// Points on the boundary are considered as colliding
chkEdge = boundaryCollideChk;
} else {
// Points on the boundary are not considered as colliding
chkEdge = boundaryDoesntCollideChk;
}
//For edge E of trangle 1,
for (i = 0; i < 3; ++i) {
int j = (i + 1) % 3;
//Check all points of trangle 2 lay on the external side of the edge E. If
//they do, the triangles do not collide.
if (chkEdge(&t1[i], &t1[j], &t2[0], eps) &&
chkEdge(&t1[i], &t1[j], &t2[1], eps) &&
chkEdge(&t1[i], &t1[j], &t2[2], eps)) {
return false;
}
}
//For edge E of trangle 2,
for (i = 0; i < 3; i++) {
int j = (i + 1) % 3;
//Check all points of trangle 1 lay on the external side of the edge E. If
//they do, the triangles do not collide.
if (chkEdge(&t2[i], &t2[j], &t1[0], eps) &&
chkEdge(&t2[i], &t2[j], &t1[1], eps) &&
chkEdge(&t2[i], &t2[j], &t1[2], eps))
return false;
}
//The triangles collide
return true;
}
int main() {
{
Point t1[] = { {0, 0}, {5, 0}, {0, 5} };
Point t2[] = { {0, 0}, {5, 0}, {0, 6} };
printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {0, 5}, {5, 0} };
Point t2[] = { {0, 0}, {0, 5}, {5, 0} };
printf("%d,true\n", triTri2D(t1, t2, 0.0, true, true));
}
{
Point t1[] = { {0, 0}, {5, 0}, {0, 5} };
Point t2[] = { {-10, 0}, {-5, 0}, {-1, 6} };
printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {5, 0}, {2.5, 5} };
Point t2[] = { {0, 4}, {2.5, -1}, {5, 4} };
printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {1, 1}, {0, 2} };
Point t2[] = { {2, 1}, {3, 0}, {3, 2} };
printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true));
}
{
Point t1[] = { {0, 0}, {1, 1}, {0, 2} };
Point t2[] = { {2, 1}, {3, -2}, {3, 4} };
printf("%d,false\n", triTri2D(t1, t2, 0.0, false, true));
}
//Barely touching
{
Point t1[] = { {0, 0}, {1, 0}, {0, 1} };
Point t2[] = { {1, 0}, {2, 0}, {1, 1} };
printf("%d,true\n", triTri2D(t1, t2, 0.0, false, true));
}
//Barely touching
{
Point t1[] = { {0, 0}, {1, 0}, {0, 1} };
Point t2[] = { {1, 0}, {2, 0}, {1, 1} };
printf("%d,false\n", triTri2D(t1, t2, 0.0, false, false));
}
return EXIT_SUCCESS;
} |
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
| #Common_Lisp | Common Lisp |
(defun determinant (rows &optional (skip-cols nil))
(let* ((result 0) (sgn -1))
(dotimes (col (length (car rows)) result)
(unless (member col skip-cols)
(if (null (cdr rows))
(return-from determinant (elt (car rows) col))
(incf result (* (setq sgn (- sgn)) (elt (car rows) col) (determinant (cdr rows) (cons col skip-cols)))) )))))
(defun permanent (rows &optional (skip-cols nil))
(let* ((result 0))
(dotimes (col (length (car rows)) result)
(unless (member col skip-cols)
(if (null (cdr rows))
(return-from permanent (elt (car rows) col))
(incf result (* (elt (car rows) col) (permanent (cdr rows) (cons col skip-cols)))) )))))
Test using the first set of definitions (from task description):
(setq m2
'((1 2)
(3 4)))
(setq m3
'((-2 2 -3)
(-1 1 3)
( 2 0 -1)))
(setq m4
'(( 1 2 3 4)
( 4 5 6 7)
( 7 8 9 10)
(10 11 12 13)))
(setq m5
'(( 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)))
(dolist (m (list m2 m3 m4 m5))
(format t "~a determinant: ~a, permanent: ~a~%" m (determinant m) (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.
| #ALGOL_W | ALGOL W | begin
% integer division procedure %
% sets c to a divided by b, returns true if the division was OK, %
% false if there was division by zero %
logical procedure divideI ( integer value a, b; integer result c ) ;
begin
% set exception handling to allow integer division by zero to occur once %
INTDIVZERO := EXCEPTION( false, 1, 0, false, "INTDIVZERO" );
c := a div b;
not XCPNOTED(INTDIVZERO)
end divideI ;
% real division procedure %
% sets c to a divided by b, returns true if the division was OK, %
% false if there was division by zero %
logical procedure divideR ( long real value a, b; long real result c ) ;
begin
% set exception handling to allow realdivision by zero to occur once %
DIVZERO := EXCEPTION( false, 1, 0, false, "DIVZERO" );
c := a / b;
not XCPNOTED(DIVZERO)
end divideR ;
integer c;
real d;
write( divideI( 4, 2, c ) ); % prints false as no exception %
write( divideI( 5, 0, c ) ); % prints true as division by zero was detected %
write( divideR( 4, 2, d ) ); % prints false as no exception %
write( divideR( 5, 0, d ) ) % prints true as division by zero was detected %
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.
| #Arturo | Arturo | try? -> 3/0
else -> print "division by zero" |
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
| #APL | APL | ⊃⎕VFI{w←⍵⋄((w='-')/w)←'¯'⋄w}'152 -3.1415926 Foo123'
1 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
| #AppleScript | AppleScript |
-- isNumString :: String -> Bool
on isNumString(s)
try
if class of s is string then
set c to class of (s as number)
c is real or c is integer
else
false
end if
on error
false
end try
end isNumString
-- TEST
on run
map(isNumString, {3, 3.0, 3.5, "3.5", "3E8", "-3.5", "30", "three", three, four})
--> {false, false, false, true, true, true, true, false, false, false}
end run
-- three :: () -> Int
script three
3
end script
-- four :: () -> Int
on four()
4
end four
-- GENERIC FUNCTIONS FOR TEST
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to lambda(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property lambda : f
end script
end if
end mReturn |
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
| #AWK | AWK |
# syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_UNIQUE_CHARACTERS.AWK
BEGIN {
for (i=0; i<=255; i++) { ord_arr[sprintf("%c",i)] = i } # build array[character]=ordinal_value
n = split(",.,abcABC,XYZ ZYX,1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",arr,",")
for (i in arr) {
width = max(width,length(arr[i]))
}
width += 2
fmt = "| %-*s | %-6s | %-10s | %-8s | %-3s | %-9s |\n"
head1 = head2 = sprintf(fmt,width,"string","length","all unique","1st diff","hex","positions")
gsub(/[^|\n]/,"-",head1)
printf(head1 head2 head1) # column headings
for (i=1; i<=n; i++) {
main(arr[i])
}
printf(head1) # column footing
exit(0)
}
function main(str, c,hex,i,leng,msg,position1,position2,tmp_arr) {
msg = "yes"
leng = length(str)
for (i=1; i<=leng; i++) {
c = substr(str,i,1)
if (c in tmp_arr) {
msg = "no"
first_diff = "'" c "'"
hex = sprintf("%2X",ord_arr[c])
position1 = index(str,c)
position2 = i
break
}
tmp_arr[c] = ""
}
printf(fmt,width,"'" str "'",leng,msg,first_diff,hex,position1 " " position2)
}
function max(x,y) { return((x > y) ? x : y) }
|
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
| #Clojure | Clojure |
(defn collapse [s]
(let [runs (partition-by identity s)]
(apply str (map first runs))))
(defn run-test [s]
(let [out (collapse s)]
(str (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)\n" out (count out)))))
|
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
| #CLU | CLU | % Collapse a string
collapse = proc (s: string) returns (string)
out: array[char] := array[char]$[]
last: char := '\000'
for c: char in string$chars(s) do
if c ~= last then
last := c
array[char]$addh(out,c)
end
end
return (string$ac2s(out))
end collapse
% Show a string in brackets, with its length
brackets = proc (s: string)
stream$putl(stream$primary_output(),
int$unparse(string$size(s))
|| " <<<"
|| s
|| ">>>")
end brackets
% Show a string and its collapsed version, and the corresponding lengths
show = proc (s: string)
brackets(s)
brackets(collapse(s))
stream$putl(stream$primary_output(), "")
end show
% Try the examples from the task description
start_up = proc ()
examples: array[string] := array[string]$[
"",
"\"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 "
]
for ex: string in array[string]$elements(examples) do
show(ex)
end
end start_up |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Rust | Rust | // Returns a vector containing the number of ways each possible sum of face
// values can occur.
fn get_totals(dice: usize, faces: usize) -> Vec<f64> {
let mut result = vec![1.0; faces + 1];
for d in 2..=dice {
let mut tmp = vec![0.0; d * faces + 1];
for i in d - 1..result.len() {
for j in 1..=faces {
tmp[i + j] += result[i];
}
}
result = tmp;
}
result
}
fn probability(dice1: usize, faces1: usize, dice2: usize, faces2: usize) -> f64 {
let totals1 = get_totals(dice1, faces1);
let totals2 = get_totals(dice2, faces2);
let mut wins = 0.0;
let mut total = 0.0;
for i in dice1..totals1.len() {
for j in dice2..totals2.len() {
let n = totals1[i] * totals2[j];
total += n;
if j < i {
wins += n;
}
}
}
wins / total
}
fn main() {
println!("{}", probability(9, 4, 6, 6));
println!("{}", probability(5, 10, 6, 7));
} |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Sidef | Sidef | func combos(sides, n) {
n || return [1]
var ret = ([0] * (n*sides.max + 1))
combos(sides, n-1).each_kv { |i,v|
v && for s in sides { ret[i + s] += v }
}
return ret
}
func winning(sides1, n1, sides2, n2) {
var (p1, p2) = (combos(sides1, n1), combos(sides2, n2))
var (win,loss,tie) = (0,0,0)
p1.each_kv { |i, x|
win += x*p2.ft(0,i-1).sum
tie += x*p2.ft(i, i).sum
loss += x*p2.ft(i+1).sum
}
[win, tie, loss] »/» p1.sum*p2.sum
}
func display_results(String title, Array res) {
say "=> #{title}"
for name, prob in (%w(p₁\ win tie p₂\ win) ~Z res) {
say "P(#{'%6s' % name}) =~ #{prob.round(-11)} (#{prob.as_frac})"
}
print "\n"
}
display_results('9D4 vs 6D6', winning(range(1, 4), 9, range(1,6), 6))
display_results('5D10 vs 6D7', winning(range(1,10), 5, range(1,7), 6)) |
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
| #C.2B.2B | C++ | #include <iostream>
#include <string>
void all_characters_are_the_same(const std::string& str) {
size_t len = str.length();
std::cout << "input: \"" << str << "\", length: " << len << '\n';
if (len > 0) {
char ch = str[0];
for (size_t i = 1; i < len; ++i) {
if (str[i] != ch) {
std::cout << "Not all characters are the same.\n";
std::cout << "Character '" << str[i]
<< "' (hex " << std::hex << static_cast<unsigned int>(str[i])
<< ") at position " << std::dec << i + 1
<< " is not the same as '" << ch << "'.\n\n";
return;
}
}
}
std::cout << "All characters are the same.\n\n";
}
int main() {
all_characters_are_the_same("");
all_characters_are_the_same(" ");
all_characters_are_the_same("2");
all_characters_are_the_same("333");
all_characters_are_the_same(".55");
all_characters_are_the_same("tttTTT");
all_characters_are_the_same("4444 444k");
return 0;
} |
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.
| #Java | Java |
package diningphilosophers;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
enum PhilosopherState { Get, Eat, Pon }
class Fork {
public static final int ON_TABLE = -1;
static int instances = 0;
public int id;
public AtomicInteger holder = new AtomicInteger(ON_TABLE);
Fork() { id = instances++; }
}
class Philosopher implements Runnable {
static final int maxWaitMs = 100; // must be > 0
static AtomicInteger token = new AtomicInteger(0);
static int instances = 0;
static Random rand = new Random();
AtomicBoolean end = new AtomicBoolean(false);
int id;
PhilosopherState state = PhilosopherState.Get;
Fork left;
Fork right;
int timesEaten = 0;
Philosopher() {
id = instances++;
left = Main.forks.get(id);
right = Main.forks.get((id+1)%Main.philosopherCount);
}
void sleep() { try { Thread.sleep(rand.nextInt(maxWaitMs)); }
catch (InterruptedException ex) {} }
void waitForFork(Fork fork) {
do {
if (fork.holder.get() == Fork.ON_TABLE) {
fork.holder.set(id); // my id shows I hold it
return;
} else { // someone still holds it
sleep(); // check again later
}
} while (true);
}
public void run() {
do {
if (state == PhilosopherState.Pon) { // all that pondering
state = PhilosopherState.Get; // made me hungry
} else { // ==PhilosopherState.Get
if (token.get() == id) { // my turn now
waitForFork(left);
waitForFork(right); // Ah needs me some foahks!
token.set((id+2)% Main.philosopherCount);
state = PhilosopherState.Eat;
timesEaten++;
sleep(); // eat for a while
left.holder.set(Fork.ON_TABLE);
right.holder.set(Fork.ON_TABLE);
state = PhilosopherState.Pon; // ponder for a while
sleep();
} else { // token.get() != id, so not my turn
sleep();
}
}
} while (!end.get());
}
}
public class Main {
static final int philosopherCount = 5; // token +2 behavior good for odd #s
static final int runSeconds = 15;
static ArrayList<Fork> forks = new ArrayList<Fork>();
static ArrayList<Philosopher> philosophers = new ArrayList<Philosopher>();
public static void main(String[] args) {
for (int i = 0 ; i < philosopherCount ; i++) forks.add(new Fork());
for (int i = 0 ; i < philosopherCount ; i++)
philosophers.add(new Philosopher());
for (Philosopher p : philosophers) new Thread(p).start();
long endTime = System.currentTimeMillis() + (runSeconds * 1000);
do { // print status
StringBuilder sb = new StringBuilder("|");
for (Philosopher p : philosophers) {
sb.append(p.state.toString());
sb.append("|"); // This is a snapshot at a particular
} // instant. Plenty happens between.
sb.append(" |");
for (Fork f : forks) {
int holder = f.holder.get();
sb.append(holder==-1?" ":String.format("P%02d",holder));
sb.append("|");
}
System.out.println(sb.toString());
try {Thread.sleep(1000);} catch (Exception ex) {}
} while (System.currentTimeMillis() < endTime);
for (Philosopher p : philosophers) p.end.set(true);
for (Philosopher p : philosophers)
System.out.printf("P%02d: ate %,d times, %,d/sec\n",
p.id, p.timesEaten, p.timesEaten/runSeconds);
}
}
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #J | J | require'dates'
leap=: _1j1 * 0 -/@:= 4 100 400 |/ {.@]
bs=: ((#:{.) + 0 j. *@[ * {:@]) +.
disc=: ((1+0 73 bs[ +^:(58<]) -/@todayno@(,: 1 1,~{.)@]) ,~1166+{.@])~ leap |
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)
| #Julia | Julia | struct Digraph{T <: Real,U}
edges::Dict{Tuple{U,U},T}
verts::Set{U}
end
function Digraph(edges::Vector{Tuple{U,U,T}}) where {T <: Real,U}
vnames = Set{U}(v for edge in edges for v in edge[1:2])
adjmat = Dict((edge[1], edge[2]) => edge[3] for edge in edges)
return Digraph(adjmat, vnames)
end
vertices(g::Digraph) = g.verts
edges(g::Digraph) = g.edges
neighbours(g::Digraph, v) = Set((b, c) for ((a, b), c) in edges(g) if a == v)
function dijkstrapath(g::Digraph{T,U}, source::U, dest::U) where {T, U}
@assert source ∈ vertices(g) "$source is not a vertex in the graph"
# Easy case
if source == dest return [source], 0 end
# Initialize variables
inf = typemax(T)
dist = Dict(v => inf for v in vertices(g))
prev = Dict(v => v for v in vertices(g))
dist[source] = 0
Q = copy(vertices(g))
neigh = Dict(v => neighbours(g, v) for v in vertices(g))
# Main loop
while !isempty(Q)
u = reduce((x, y) -> dist[x] < dist[y] ? x : y, Q)
pop!(Q, u)
if dist[u] == inf || u == dest break end
for (v, cost) in neigh[u]
alt = dist[u] + cost
if alt < dist[v]
dist[v] = alt
prev[v] = u
end
end
end
# Return path
rst, cost = U[], dist[dest]
if prev[dest] == dest
return rst, cost
else
while dest != source
unshift!(rst, dest)
dest = prev[dest]
end
unshift!(rst, dest)
return rst, cost
end
end
# testgraph = [("a", "b", 1), ("b", "e", 2), ("a", "e", 4)]
testgraph = [("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)]
g = Digraph(testgraph)
src, dst = "a", "e"
path, cost = dijkstrapath(g, src, dst)
println("Shortest path from $src to $dst: ", isempty(path) ? "no possible path" : join(path, " → "), " (cost $cost)")
# Print all possible paths
@printf("\n%4s | %3s | %s\n", "src", "dst", "path")
@printf("----------------\n")
for src in vertices(g), dst in vertices(g)
path, cost = dijkstrapath(g, src, dst)
@printf("%4s | %3s | %s\n", src, dst, isempty(path) ? "no possible path" : join(path, " → ") * " ($cost)")
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
| #Erlang | Erlang | -module( digital_root ).
-export( [task/0] ).
task() ->
Ns = [N || N <- [627615, 39390, 588225, 393900588225]],
Persistances = [persistance_root(X) || X <- Ns],
[io:fwrite("~p has additive persistence ~p and digital root of ~p~n", [X, Y, Z]) || {X, {Y, Z}} <- lists:zip(Ns, Persistances)].
persistance_root( X ) -> persistance_root( sum_digits:sum_digits(X), 1 ).
persistance_root( X, N ) when X < 10 -> {N, X};
persistance_root( X, N ) -> persistance_root( sum_digits:sum_digits(X), N + 1 ).
|
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
| #PL.2FI | PL/I | multiple: procedure options (main); /* 29 April 2014 */
declare n fixed binary (31);
find_mdr: procedure;
declare (mdr, mp, p) fixed binary (31);
mdr = n;
do mp = 1 by 1 until (p <= 9);
p = 1;
do until (mdr = 0); /* Form product of the digits in mdr. */
p = mod(mdr, 10) * p;
mdr= mdr/10;
end;
mdr = p;
end;
put skip data (n, mdr, mp);
end find_mdr;
do n = 123321, 7739, 893, 899998;
call find_mdr;
end;
end multiple; |
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?
| #Julia | Julia | using Combinatorics
function solve(n::Vector{<:AbstractString}, pred::Vector{<:Function})
rst = Vector{typeof(n)}(0)
for candidate in permutations(n)
if all(p(candidate) for p in predicates)
push!(rst, candidate)
end
end
return rst
end
Names = ["Baker", "Cooper", "Fletcher", "Miller", "Smith"]
predicates = [
(s) -> last(s) != "Baker",
(s) -> first(s) != "Cooper",
(s) -> first(s) != "Fletcher" && last(s) != "Fletcher",
(s) -> findfirst(s, "Miller") > findfirst(s, "Cooper"),
(s) -> abs(findfirst(s, "Smith") - findfirst(s, "Fletcher")) != 1,
(s) -> abs(findfirst(s, "Cooper") - findfirst(s, "Fletcher")) != 1]
solutions = solve(Names, predicates)
foreach(x -> println(join(x, ", ")), solutions) |
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
| #Fantom | Fantom | class DotProduct
{
static Int dotProduct (Int[] a, Int[] b)
{
Int result := 0
[a.size,b.size].min.times |i|
{
result += a[i] * b[i]
}
return result
}
public static Void main ()
{
Int[] x := [1,2,3,4]
Int[] y := [2,3,4]
echo ("Dot product of $x and $y is ${dotProduct(x, y)}")
}
} |
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
| #Forth | Forth | : vector create cells allot ;
: th cells + ;
3 constant /vector
/vector vector a
/vector vector b
: dotproduct ( a1 a2 -- n)
0 tuck ?do -rot over i th @ over i th @ * >r rot r> + loop nip nip
;
: vector! cells over + swap ?do i ! 1 cells +loop ;
-5 3 1 a /vector vector!
-1 -2 4 b /vector vector!
a b /vector dotproduct . 3 ok |
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
| #F.23 | F# |
// Determine if a string is squeezable. Nigel Galloway: June 9th., 2020
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
if fG.Length=n.Length then None else Some fG
let isSqueezable n g=match squeeze n g with
Some i->printfn "%A squeezes <<<%s>>> (length %d) to <<<%s>>> (length %d)" g n n.Length i i.Length
|_->printfn "%A does not squeeze <<<%s>>> (length %d)" g n n.Length
isSqueezable "" ' '
isSqueezable "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " '-'
isSqueezable "..1111111111111111111111111111111111111111111111111111111111111117777888" '7'
isSqueezable "I never give 'em hell, I just tell the truth, and they think it's hell. " '.'
let fN=isSqueezable " --- Harry S Truman " in fN ' '; fN '-'; fN '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
| #Factor | Factor | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix! ] if ]
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ] if ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-squeeze ( str c -- )
dup "Specified character: '%c'\n" printf
[ "Before squeeze: " write drop .str ]
[ "After squeeze: " write squeeze .str ] 2bi nl ;
: squeeze-demo ( -- )
{
""
"\"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. "
} "\0-7." [ show-squeeze ] 2each
" --- Harry S Truman "
[ CHAR: space ] [ CHAR: - ] [ CHAR: r ] tri
[ show-squeeze ] 2tri@ ;
MAIN: squeeze-demo |
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. | #Ada | Ada | with Ada.Numerics.Elementary_Functions;
with Ada.Text_IO;
procedure Demings_Funnel is
type Float_List is array (Positive range <>) of Float;
Dxs : constant Float_List :=
(-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);
Dys : constant Float_List :=
( 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);
type Rule_Access is access function (Z, Dz : Float) return Float;
function Funnel (List : in Float_List;
Rule : in Rule_Access)
return Float_List
is
Correc : Float := 0.0;
Result : Float_List (List'Range);
begin
for I in List'Range loop
Result (I) := Correc + List (I);
Correc := Rule (Correc, List (I));
end loop;
return Result;
end Funnel;
function Mean (List : in Float_List)
return Float
is
Sum : Float := 0.0;
begin
for Value of List loop
Sum := Sum + Value;
end loop;
return Sum / Float (List'Length);
end Mean;
function Stddev (List : in Float_List)
return Float
is
use Ada.Numerics.Elementary_Functions;
M : constant Float := Mean (List);
Sum : Float := 0.0;
begin
for F of List loop
Sum := Sum + (F - M) * (F - M);
end loop;
return Sqrt (Sum / Float (List'Length));
end Stddev;
procedure Experiment (Label : in String;
Rule : in Rule_Access)
is
package Float_IO is new Ada.Text_IO.Float_IO (Float);
use Ada.Text_IO;
use Float_IO;
Rxs : constant Float_List := Funnel (Dxs, Rule);
Rys : constant Float_List := Funnel (Dys, Rule);
begin
Default_Exp := 0;
Default_Fore := 4;
Default_Aft := 4;
Put_Line (Label & " : x y");
Put ("Mean: "); Put (Mean (Rxs)); Put (Mean (Rys)); New_Line;
Put ("StdDev: "); Put (Stddev (Rxs)); Put (Stddev (Rys)); New_Line;
New_Line;
end Experiment;
function Rule_1 (Z, Dz : Float) return Float is (0.0);
function Rule_2 (Z, Dz : Float) return Float is (-Dz);
function Rule_3 (Z, Dz : Float) return Float is (-Z - Dz);
function Rule_4 (Z, Dz : Float) return Float is (Z + Dz);
begin
Experiment ("Rule 1", Rule_1'Access);
Experiment ("Rule 2", Rule_2'Access);
Experiment ("Rule 3", Rule_3'Access);
Experiment ("Rule 4", Rule_4'Access);
end Demings_Funnel; |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Forth | Forth | : is-prime? \ n -- f ; \ Fast enough for this application
DUP 1 AND IF \ n is odd
DUP 3 DO
DUP I DUP * < IF DROP -1 LEAVE THEN \ Leave loop if I**2 > n
DUP I MOD 0= IF DROP 0 LEAVE THEN \ Leave loop if n%I is zero
2 +LOOP \ iterate over odd I only
ELSE \ n is even
2 = \ Returns true if n == 2.
THEN ;
: 1digit \ -- ; \ Select and print one digit numbers which are prime
10 2 ?DO
I is-prime? IF I 9 .r THEN
LOOP ;
: 2digit \ n-bfwd digit -- ;
\ Generate and print primes where least significant digit < digit
\ n-bfwd is the base number bought foward from calls to `digits` below.
SWAP 10 * SWAP 1 ?DO
DUP I + is-prime? IF DUP I + 9 .r THEN
2 I 3 = 2* - +LOOP DROP ; \ This generates the I sequence 1 3 7 9
: digits \ #digits n-bfwd max-digit -- ;
\ Print descendimg primes with #digits digits.
2 PICK 9 > IF ." #digits must be less than 10." 2DROP DROP EXIT THEN
2 PICK 1 = IF 2DROP DROP 1digit EXIT THEN \ One digit is special simple case
2 PICK 2 = IF \ Two digit special and
SWAP 10 * SWAP 2 DO \ I is 2 .. max-digit-1
DUP I + I 2digit
LOOP 2DROP
ELSE
SWAP 10 * SWAP 2 PICK ?DO \ I is #digits .. max-digit-1
DUP I + 2 PICK 1- SWAP I RECURSE \ Recurse with #digits reduced by 1.
LOOP 2DROP
THEN ;
: descending-primes
\ Print the descending primes. Call digits with increasing #digits
CR 9 1 DO I 0 10 digits LOOP ; |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Go | Go | package main
import (
"fmt"
"rcu"
"sort"
"strconv"
)
func combinations(a []int, k int) [][]int {
n := len(a)
c := make([]int, k)
var combs [][]int
var combine func(start, end, index int)
combine = func(start, end, index int) {
if index == k {
t := make([]int, len(c))
copy(t, c)
combs = append(combs, t)
return
}
for i := start; i <= end && end-i+1 >= k-index; i++ {
c[index] = a[i]
combine(i+1, end, index+1)
}
}
combine(0, n-1, 0)
return combs
}
func powerset(a []int) (res [][]int) {
if len(a) == 0 {
return
}
for i := 1; i <= len(a); i++ {
res = append(res, combinations(a, i)...)
}
return
}
func main() {
ps := powerset([]int{9, 8, 7, 6, 5, 4, 3, 2, 1})
var descPrimes []int
for i := 1; i < len(ps); i++ {
s := ""
for _, e := range ps[i] {
s += string(e + '0')
}
p, _ := strconv.Atoi(s)
if rcu.IsPrime(p) {
descPrimes = append(descPrimes, p)
}
}
sort.Ints(descPrimes)
fmt.Println("There are", len(descPrimes), "descending primes, namely:")
for i := 0; i < len(descPrimes); i++ {
fmt.Printf("%8d ", descPrimes[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.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)
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace TriangleOverlap {
class Triangle {
public Tuple<double, double> P1 { get; set; }
public Tuple<double, double> P2 { get; set; }
public Tuple<double, double> P3 { get; set; }
public Triangle(Tuple<double, double> p1, Tuple<double, double> p2, Tuple<double, double> p3) {
P1 = p1;
P2 = p2;
P3 = p3;
}
public double Det2D() {
return P1.Item1 * (P2.Item2 - P3.Item2)
+ P2.Item1 * (P3.Item2 - P1.Item2)
+ P3.Item1 * (P3.Item1 - P2.Item2);
}
public void CheckTriWinding(bool allowReversed) {
var detTri = Det2D();
if (detTri < 0.0) {
if (allowReversed) {
var a = P3;
P3 = P2;
P2 = a;
} else {
throw new Exception("Triangle has wrong winding direction");
}
}
}
public bool BoundaryCollideChk(double eps) {
return Det2D() < eps;
}
public bool BoundaryDoesntCollideChk(double eps) {
return Det2D() <= eps;
}
public override string ToString() {
return string.Format("Triangle: {0}, {1}, {2}", P1, P2, P3);
}
}
class Program {
static bool BoundaryCollideChk(Triangle t, double eps) {
return t.BoundaryCollideChk(eps);
}
static bool BoundaryDoesntCollideChk(Triangle t, double eps) {
return t.BoundaryDoesntCollideChk(eps);
}
static bool TriTri2D(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) {
// Triangles must be expressed anti-clockwise
t1.CheckTriWinding(allowReversed);
t2.CheckTriWinding(allowReversed);
// 'onBoundary' determines whether points on boundary are considered as colliding or not
var chkEdge = onBoundary
? (Func<Triangle, double, bool>)BoundaryCollideChk
: BoundaryDoesntCollideChk;
List<Tuple<double, double>> lp1 = new List<Tuple<double, double>>() { t1.P1, t1.P2, t1.P3 };
List<Tuple<double, double>> lp2 = new List<Tuple<double, double>>() { t2.P1, t2.P2, t2.P3 };
// for each edge E of t1
for (int i = 0; i < 3; i++) {
var 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(new Triangle(lp1[i], lp1[j], lp2[0]), eps) &&
chkEdge(new Triangle(lp1[i], lp1[j], lp2[1]), eps) &&
chkEdge(new Triangle(lp1[i], lp1[j], lp2[2]), eps)) {
return false;
}
}
// for each edge E of t2
for (int i = 0; i < 3; i++) {
var 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(new Triangle(lp2[i], lp2[j], lp1[0]), eps) &&
chkEdge(new Triangle(lp2[i], lp2[j], lp1[1]), eps) &&
chkEdge(new Triangle(lp2[i], lp2[j], lp1[2]), eps)) {
return false;
}
}
// The triangles overlap
return true;
}
static void Overlap(Triangle t1, Triangle t2, double eps = 0.0, bool allowReversed = false, bool onBoundary = true) {
if (TriTri2D(t1, t2, eps, allowReversed, onBoundary)) {
Console.WriteLine("overlap");
} else {
Console.WriteLine("do not overlap");
}
}
static void Main(string[] args) {
var t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0));
var t2 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 6.0));
Console.WriteLine("{0} and\n{1}", t1, t2);
Overlap(t1, t2);
Console.WriteLine();
// need to allow reversed for this pair to avoid exception
t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(0.0, 5.0), new Tuple<double, double>(5.0, 0.0));
t2 = t1;
Console.WriteLine("{0} and\n{1}", t1, t2);
Overlap(t1, t2, 0.0, true);
Console.WriteLine();
t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(5.0, 0.0), new Tuple<double, double>(0.0, 5.0));
t2 = new Triangle(new Tuple<double, double>(-10.0, 0.0), new Tuple<double, double>(-5.0, 0.0), new Tuple<double, double>(-1.0, 6.0));
Console.WriteLine("{0} and\n{1}", t1, t2);
Overlap(t1, t2);
Console.WriteLine();
t1.P3 = new Tuple<double, double>(2.5, 5.0);
t2 = new Triangle(new Tuple<double, double>(0.0, 4.0), new Tuple<double, double>(2.5, -1.0), new Tuple<double, double>(5.0, 4.0));
Console.WriteLine("{0} and\n{1}", t1, t2);
Overlap(t1, t2);
Console.WriteLine();
t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 1.0), new Tuple<double, double>(0.0, 2.0));
t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, 0.0), new Tuple<double, double>(3.0, 2.0));
Console.WriteLine("{0} and\n{1}", t1, t2);
Overlap(t1, t2);
Console.WriteLine();
t2 = new Triangle(new Tuple<double, double>(2.0, 1.0), new Tuple<double, double>(3.0, -2.0), new Tuple<double, double>(3.0, 4.0));
Console.WriteLine("{0} and\n{1}", t1, t2);
Overlap(t1, t2);
Console.WriteLine();
t1 = new Triangle(new Tuple<double, double>(0.0, 0.0), new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(0.0, 1.0));
t2 = new Triangle(new Tuple<double, double>(1.0, 0.0), new Tuple<double, double>(2.0, 0.0), new Tuple<double, double>(1.0, 1.1));
Console.WriteLine("{0} and\n{1}", t1, t2);
Console.WriteLine("which have only a single corner in contact, if boundary points collide");
Overlap(t1, t2);
Console.WriteLine();
Console.WriteLine("{0} and\n{1}", t1, t2);
Console.WriteLine("which have only a single corner in contact, if boundary points do not collide");
Overlap(t1, t2, 0.0, false, false);
}
}
} |
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.
| #11l | 11l | fs:remove_file(‘output.txt’)
fs:remove_dir(‘docs’)
fs:remove_file(‘/output.txt’)
fs:remove_dir(‘/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
| #D | D | import std.algorithm, std.range, std.traits, permutations2,
permutations_by_swapping1;
auto prod(Range)(Range r) nothrow @safe @nogc {
return reduce!q{a * b}(ForeachType!Range(1), r);
}
T permanent(T)(in T[][] a) nothrow @safe
in {
assert(a.all!(row => row.length == a[0].length));
} body {
auto r = a.length.iota;
T tot = 0;
foreach (const sigma; r.array.permutations)
tot += r.map!(i => a[i][sigma[i]]).prod;
return tot;
}
T determinant(T)(in T[][] a) nothrow
in {
assert(a.all!(row => row.length == a[0].length));
} body {
immutable n = a.length;
auto r = n.iota;
T tot = 0;
//foreach (sigma, sign; n.spermutations) {
foreach (const sigma_sign; n.spermutations) {
const sigma = sigma_sign[0];
immutable sign = sigma_sign[1];
tot += sign * r.map!(i => a[i][sigma[i]]).prod;
}
return tot;
}
void main() {
import std.stdio;
foreach (/*immutable*/ const a; [[[1, 2],
[3, 4]],
[[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10],
[10, 11, 12, 13]],
[[ 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]]]) {
writefln("[%([%(%2s, %)],\n %)]]", a);
writefln("Permanent: %s, determinant: %s\n",
a.permanent, a.determinant);
}
} |
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.
| #AutoHotkey | AutoHotkey | ZeroDiv(num1, num2) {
If ((num1/num2) != "")
MsgBox % num1/num2
Else
MsgBox, 48, Warning, The result is not valid (Divide By Zero).
}
ZeroDiv(0, 3) ; is ok
ZeroDiv(3, 0) ; divize by zero alert |
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.
| #BASIC | BASIC | 100 REM TRY
110 ONERR GOTO 200
120 D = - 44 / 0
190 END
200 REM CATCH
210 E = PEEK (222) < > 133
220 POKE 216,0: REM ONERR OFF
230 IF E THEN RESUME
240 CALL - 3288: REM RECOVER
250 PRINT "DIVISION BY ZERO"
|
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program strNumber.s */
/* Constantes */
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessNum: .asciz "Enter number : \n"
szMessError: .asciz "String is not a number !!!\n"
szMessInteger: .asciz "String is a integer.\n"
szMessFloat: .asciz "String is a float.\n"
szMessFloatExp: .asciz "String is a float with exposant.\n"
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
sBuffer: .skip BUFFERSIZE
/* code section */
.text
.global main
main:
loop:
ldr r0,iAdrszMessNum
bl affichageMess
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7, #READ @ request to read datas
swi 0 @ call system
ldr r1,iAdrsBuffer @ buffer address
mov r2,#0 @ end of string
sub r0,#1 @ replace character 0xA
strb r2,[r1,r0] @ store byte at the end of input string (r0 contains number of characters)
ldr r0,iAdrsBuffer
bl controlNumber @ call routine
cmp r0,#0
bne 1f
ldr r0,iAdrszMessError @ not a number
bl affichageMess
b 5f
1:
cmp r0,#1
bne 2f
ldr r0,iAdrszMessInteger @ integer
bl affichageMess
b 5f
2:
cmp r0,#2
bne 3f
ldr r0,iAdrszMessFloat @ float
bl affichageMess
b 5f
3:
cmp r0,#3
bne 5f
ldr r0,iAdrszMessFloatExp @ float with exposant
bl affichageMess
5:
b loop
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessNum: .int szMessNum
iAdrszMessError: .int szMessError
iAdrszMessInteger: .int szMessInteger
iAdrszMessFloat: .int szMessFloat
iAdrszMessFloatExp: .int szMessFloatExp
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsBuffer: .int sBuffer
/******************************************************************/
/* control if string is number */
/******************************************************************/
/* r0 contains the address of the string */
/* r0 return 0 if not a number */
/* r0 return 1 if integer eq 12345 or -12345 */
/* r0 return 2 if float eq 123.45 or 123,45 or -123,45 */
/* r0 return 3 if float with exposant eq 123.45E30 or -123,45E-30 */
controlNumber:
push {r1-r4,lr} @ save registers
mov r1,#0
mov r3,#0 @ point counter
1:
ldrb r2,[r0,r1]
cmp r2,#0
beq 5f
cmp r2,#' '
addeq r1,#1
beq 1b
cmp r2,#'-' @ negative ?
addeq r1,#1
beq 2f
cmp r2,#'+' @ positive ?
addeq r1,#1
2:
ldrb r2,[r0,r1] @ control space
cmp r2,#0 @ end ?
beq 5f
cmp r2,#' '
addeq r1,#1
beq 2b
3:
ldrb r2,[r0,r1]
cmp r2,#0 @ end ?
beq 10f
cmp r2,#'E' @ exposant ?
beq 6f
cmp r2,#'e' @ exposant ?
beq 6f
cmp r2,#'.' @ point ?
addeq r3,#1 @ yes increment counter
addeq r1,#1
beq 3b
cmp r2,#',' @ comma ?
addeq r3,#1 @ yes increment counter
addeq r1,#1
beq 3b
cmp r2,#'0' @ control digit < 0
blt 5f
cmp r2,#'9' @ control digit > 0
bgt 5f
add r1,#1 @ no error loop digit
b 3b
5: @ error detected
mov r0,#0
b 100f
6: @ float with exposant
add r1,#1
ldrb r2,[r0,r1]
cmp r2,#0 @ end ?
moveq r0,#0 @ error
beq 100f
cmp r2,#'-' @ negative exposant ?
addeq r1,#1
mov r4,#0 @ nombre de chiffres
7:
ldrb r2,[r0,r1]
cmp r2,#0 @ end ?
beq 9f
cmp r2,#'0' @ control digit < 0
blt 8f
cmp r2,#'9' @ control digit > 0
bgt 8f
add r1,#1
add r4,#1 @ counter digit
b 7b
8:
mov r0,#0
b 100f
9:
cmp r4,#0 @ number digit exposant = 0 -> error
moveq r0,#0 @ erreur
beq 100f
cmp r4,#2 @ number digit exposant > 2 -> error
movgt r0,#0 @ error
bgt 100f
mov r0,#3 @ valid float with exposant
b 100f
10:
cmp r3,#0
moveq r0,#1 @ valid integer
beq 100f
cmp r3,#1 @ number of point or comma = 1 ?
moveq r0,#2 @ valid float
movgt r0,#0 @ error
100:
pop {r1-r4,lr} @ restaur des 2 registres
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
|
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
| #C | C |
#include<stdbool.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct positionList{
int position;
struct positionList *next;
}positionList;
typedef struct letterList{
char letter;
int repititions;
positionList* positions;
struct letterList *next;
}letterList;
letterList* letterSet;
bool duplicatesFound = false;
void checkAndUpdateLetterList(char c,int pos){
bool letterOccurs = false;
letterList *letterIterator,*newLetter;
positionList *positionIterator,*newPosition;
if(letterSet==NULL){
letterSet = (letterList*)malloc(sizeof(letterList));
letterSet->letter = c;
letterSet->repititions = 0;
letterSet->positions = (positionList*)malloc(sizeof(positionList));
letterSet->positions->position = pos;
letterSet->positions->next = NULL;
letterSet->next = NULL;
}
else{
letterIterator = letterSet;
while(letterIterator!=NULL){
if(letterIterator->letter==c){
letterOccurs = true;
duplicatesFound = true;
letterIterator->repititions++;
positionIterator = letterIterator->positions;
while(positionIterator->next!=NULL)
positionIterator = positionIterator->next;
newPosition = (positionList*)malloc(sizeof(positionList));
newPosition->position = pos;
newPosition->next = NULL;
positionIterator->next = newPosition;
}
if(letterOccurs==false && letterIterator->next==NULL)
break;
else
letterIterator = letterIterator->next;
}
if(letterOccurs==false){
newLetter = (letterList*)malloc(sizeof(letterList));
newLetter->letter = c;
newLetter->repititions = 0;
newLetter->positions = (positionList*)malloc(sizeof(positionList));
newLetter->positions->position = pos;
newLetter->positions->next = NULL;
newLetter->next = NULL;
letterIterator->next = newLetter;
}
}
}
void printLetterList(){
positionList* positionIterator;
letterList* letterIterator = letterSet;
while(letterIterator!=NULL){
if(letterIterator->repititions>0){
printf("\n'%c' (0x%x) at positions :",letterIterator->letter,letterIterator->letter);
positionIterator = letterIterator->positions;
while(positionIterator!=NULL){
printf("%3d",positionIterator->position + 1);
positionIterator = positionIterator->next;
}
}
letterIterator = letterIterator->next;
}
printf("\n");
}
int main(int argc,char** argv)
{
int i,len;
if(argc>2){
printf("Usage : %s <Test string>\n",argv[0]);
return 0;
}
if(argc==1||strlen(argv[1])==1){
printf("\"%s\" - Length %d - Contains only unique characters.\n",argc==1?"":argv[1],argc==1?0:1);
return 0;
}
len = strlen(argv[1]);
for(i=0;i<len;i++){
checkAndUpdateLetterList(argv[1][i],i);
}
printf("\"%s\" - Length %d - %s",argv[1],len,duplicatesFound==false?"Contains only unique characters.\n":"Contains the following duplicate characters :");
if(duplicatesFound==true)
printLetterList();
return 0;
}
|
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
| #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
# Collapse the string at in, and store the result in the given buffer
sub collapse(in: [uint8], out: [uint8]) is
var ch := [in];
in := @next in;
loop
if ch == 0 then
[out] := 0;
return;
elseif [in] != ch then
[out] := ch;
out := @next out;
ch := [in];
end if;
in := @next in;
end loop;
end sub;
# Given a string, collapse it and print all required output
sub show(str: [uint8]) is
sub bracket_length(str: [uint8]) is
print_i32(StrLen(str) as uint32);
print(" <<<");
print(str);
print(">>>");
print_nl();
end sub;
var buf: uint8[256];
collapse(str, &buf[0]);
bracket_length(str);
bracket_length(&buf[0]);
print_nl();
end sub;
# Strings from the task
var strings: [uint8][] := {
"",
"\"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 "
};
# Collapse and print each string
var i: @indexof strings := 0;
while i < @sizeof strings loop
show(strings[i]);
i := i + 1;
end loop; |
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
| #D | D | import std.stdio;
void collapsible(string s) {
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", len);
writeln;
}
void main() {
collapsible(``);
collapsible(`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `);
collapsible(`..1111111111111111111111111111111111111111111111111111111111111117777888`);
collapsible(`I never give 'em hell, I just tell the truth, and they think it's hell. `);
collapsible(` --- Harry S Truman `);
} |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Tcl | Tcl | foreach d0 {1 2 3 4 5 6} {
foreach d1 {1 2 3 4 5 6} {
...
foreach dN {1 2 3 4 5 6} {
dict incr sum [::tcl::mathop::+ $n $d0 $d1 ... $DN]
}
...
}
} |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Vlang | Vlang | import math
fn min_of(x int, y int) int {
if x < y {
return x
}
return y
}
fn throw_die(n_sides int, n_dice int, s int, mut counts []int) {
if n_dice == 0 {
counts[s]++
return
}
for i := int(1); i <= n_sides; i++ {
throw_die(n_sides, n_dice - 1, s + i, mut counts)
}
}
fn beating_probability(n_sides1 int, n_dice1 int, n_sides2 int, n_dice2 int) f64 {
len1 := (n_sides1 + 1) * n_dice1
mut c1 := []int{len: len1} // all elements zero by default
throw_die(n_sides1, n_dice1, 0, mut c1)
len2 := (n_sides2 + 1) * n_dice2
mut c2 := []int{len: len2}
throw_die(n_sides2, n_dice2, 0, mut c2)
p12 := math.pow(f64(n_sides1), f64(n_dice1)) *
math.pow(f64(n_sides2), f64(n_dice2))
mut tot := 0.0
for i := int(0); i < len1; i++ {
for j := int(0); j < min_of(i, len2); j++ {
tot += f64(c1[i] * c2[j]) / p12
}
}
return tot
}
fn main() {
println(beating_probability(4, 9, 6, 6))
println(beating_probability(10, 5, 7, 6))
} |
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
| #Clojure | Clojure |
(defn check-all-chars-same [s]
(println (format "String (%s) of len: %d" s (count s)))
(let [num-same (-> (take-while #(= (first s) %) s)
count)]
(if (= num-same (count s))
(println "...all characters the same")
(println (format "...character %d differs - it is 0x%x"
num-same
(byte (nth s num-same)))))))
(map check-all-chars-same
[""
" "
"2"
"333"
".55"
"tttTTT"
"4444 444k"])
|
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
| #Common_Lisp | Common Lisp | (defun strequ (&rest str)
(if (not str) (setf str (list "" " " "2" "333" ".55" "tttTTT" "4444 444k")))
(dolist (s str)
(do ((i 0 (1+ i)))
((cond
((= i (length s))
(format t "\"~a\" [~d] : All characters are identical.~%" s (length s)) t)
((char/= (char s i) (char s 0))
(format t "\"~a\" [~d] : '~c' (0x~0x) at index ~d is different.~%" s (length s) (char s i) (char-int (char s i)) i) t)))))) |
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.
| #JoCaml | JoCaml | let random_wait n = Unix.sleep (Random.int n);;
let print s m = Printf.printf "philosopher %s is %s\n" s m; flush(stdout);;
let will_eat s = print s "eating"; random_wait 10;;
let will_think s = print s "thinking"; random_wait 20; print s "hungry";;
(* a,b,c,d,e are thinking philosophers; ah,bh,ch,dh,eh are the same philosophers when hungry;
fab is the fork located between philosophers a and b; similarly for fbc, fcd, ... *)
def ah() & fab() & fea() = will_eat "Aristotle"; a() & fab() & fea()
or bh() & fab() & fbc() = will_eat "Kant"; b() & fab() & fbc()
or ch() & fbc() & fcd() = will_eat "Spinoza"; c() & fbc() & fcd()
or dh() & fcd() & fde() = will_eat "Marx"; d() & fcd() & fde()
or eh() & fde() & fea() = will_eat "Russell"; e() & fde() & fea()
and a() = will_think "Aristotle"; ah()
and b() = will_think "Kant"; bh()
and c() = will_think "Spinoza"; ch()
and d() = will_think "Marx"; dh()
and e() = will_think "Russell"; eh()
;;
spawn fab() & fbc() & fcd() & fde() & fea() & a() & b() & c() & d() & e();; |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Java | Java | import java.util.Calendar;
import java.util.GregorianCalendar;
public class DiscordianDate {
final static String[] seasons = {"Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"};
final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"};
final static String[] apostle = {"Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"};
final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"};
public static String discordianDate(final GregorianCalendar date) {
int y = date.get(Calendar.YEAR);
int yold = y + 1166;
int dayOfYear = date.get(Calendar.DAY_OF_YEAR);
if (date.isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold;
else if (dayOfYear > 60)
dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
if (seasonDay == 5)
return apostle[dayOfYear / 73] + ", in the YOLD " + yold;
if (seasonDay == 50)
return holiday[dayOfYear / 73] + ", in the YOLD " + yold;
String season = seasons[dayOfYear / 73];
String dayOfWeek = weekday[dayOfYear % 5];
return String.format("%s, day %s of %s in the YOLD %s",
dayOfWeek, seasonDay, season, yold);
}
public static void main(String[] args) {
System.out.println(discordianDate(new GregorianCalendar()));
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176");
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178");
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178");
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178");
test(2010, 0, 5, "Mungday, in the YOLD 3176");
test(2011, 4, 3, "Discoflux, in the YOLD 3177");
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181");
}
private static void test(int y, int m, int d, final String result) {
assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result));
}
} |
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)
| #Kotlin | Kotlin | // version 1.1.51
import java.util.TreeSet
class Edge(val v1: String, val v2: String, val dist: Int)
/** One vertex of the graph, complete with mappings to neighbouring vertices */
class Vertex(val name: String) : Comparable<Vertex> {
var dist = Int.MAX_VALUE // MAX_VALUE assumed to be infinity
var previous: Vertex? = null
val neighbours = HashMap<Vertex, Int>()
fun printPath() {
if (this == previous) {
print(name)
}
else if (previous == null) {
print("$name(unreached)")
}
else {
previous!!.printPath()
print(" -> $name($dist)")
}
}
override fun compareTo(other: Vertex): Int {
if (dist == other.dist) return name.compareTo(other.name)
return dist.compareTo(other.dist)
}
override fun toString() = "($name, $dist)"
}
class Graph(
val edges: List<Edge>,
val directed: Boolean,
val showAllPaths: Boolean = false
) {
// mapping of vertex names to Vertex objects, built from a set of Edges
private val graph = HashMap<String, Vertex>(edges.size)
init {
// one pass to find all vertices
for (e in edges) {
if (!graph.containsKey(e.v1)) graph.put(e.v1, Vertex(e.v1))
if (!graph.containsKey(e.v2)) graph.put(e.v2, Vertex(e.v2))
}
// another pass to set neighbouring vertices
for (e in edges) {
graph[e.v1]!!.neighbours.put(graph[e.v2]!!, e.dist)
// also do this for an undirected graph if applicable
if (!directed) graph[e.v2]!!.neighbours.put(graph[e.v1]!!, e.dist)
}
}
/** Runs dijkstra using a specified source vertex */
fun dijkstra(startName: String) {
if (!graph.containsKey(startName)) {
println("Graph doesn't contain start vertex '$startName'")
return
}
val source = graph[startName]
val q = TreeSet<Vertex>()
// set-up vertices
for (v in graph.values) {
v.previous = if (v == source) source else null
v.dist = if (v == source) 0 else Int.MAX_VALUE
q.add(v)
}
dijkstra(q)
}
/** Implementation of dijkstra's algorithm using a binary heap */
private fun dijkstra(q: TreeSet<Vertex>) {
while (!q.isEmpty()) {
// vertex with shortest distance (first iteration will return source)
val u = q.pollFirst()
// if distance is infinite we can ignore 'u' (and any other remaining vertices)
// since they are unreachable
if (u.dist == Int.MAX_VALUE) break
//look at distances to each neighbour
for (a in u.neighbours) {
val v = a.key // the neighbour in this iteration
val alternateDist = u.dist + a.value
if (alternateDist < v.dist) { // shorter path to neighbour found
q.remove(v)
v.dist = alternateDist
v.previous = u
q.add(v)
}
}
}
}
/** Prints a path from the source to the specified vertex */
fun printPath(endName: String) {
if (!graph.containsKey(endName)) {
println("Graph doesn't contain end vertex '$endName'")
return
}
print(if (directed) "Directed : " else "Undirected : ")
graph[endName]!!.printPath()
println()
if (showAllPaths) printAllPaths() else println()
}
/** Prints the path from the source to every vertex (output order is not guaranteed) */
private fun printAllPaths() {
for (v in graph.values) {
v.printPath()
println()
}
println()
}
}
val GRAPH = listOf(
Edge("a", "b", 7),
Edge("a", "c", 9),
Edge("a", "f", 14),
Edge("b", "c", 10),
Edge("b", "d", 15),
Edge("c", "d", 11),
Edge("c", "f", 2),
Edge("d", "e", 6),
Edge("e", "f", 9)
)
const val START = "a"
const val END = "e"
fun main(args: Array<String>) {
with (Graph(GRAPH, true)) { // directed
dijkstra(START)
printPath(END)
}
with (Graph(GRAPH, false)) { // undirected
dijkstra(START)
printPath(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
| #F.23 | F# |
//Find the Digital Root of An Integer - Nigel Galloway: February 1st., 2015
//This code will work with any integer type
let inline digitalRoot N BASE =
let rec root(p,n) =
let s = sumDigits n BASE
if s < BASE then (s,p) else root(p+1, s)
root(LanguagePrimitives.GenericZero<_> + 1, 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
| #Factor | Factor | USING: arrays formatting kernel math math.text.utils sequences ;
IN: rosetta-code.digital-root
: digital-root ( n -- persistence root )
0 swap [ 1 digit-groups dup length 1 > ] [ sum [ 1 + ] dip ]
while first ;
: print-root ( n -- )
dup digital-root
"%-12d has additive persistence %d and digital root %d.\n"
printf ;
{ 627615 39390 588225 393900588225 } [ print-root ] each |
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
| #Python | Python | try:
from functools import reduce
except:
pass
def mdroot(n):
'Multiplicative digital root'
mdr = [n]
while mdr[-1] > 9:
mdr.append(reduce(int.__mul__, (int(dig) for dig in str(mdr[-1])), 1))
return len(mdr) - 1, mdr[-1]
if __name__ == '__main__':
print('Number: (MP, MDR)\n====== =========')
for n in (123321, 7739, 893, 899998):
print('%6i: %r' % (n, mdroot(n)))
table, n = {i: [] for i in range(10)}, 0
while min(len(row) for row in table.values()) < 5:
mpersistence, mdr = mdroot(n)
table[mdr].append(n)
n += 1
print('\nMP: [n0..n4]\n== ========')
for mp, val in sorted(table.items()):
print('%2i: %r' % (mp, val[:5])) |
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?
| #K | K |
perm: {x@m@&n=(#?:)'m:!n#n:#x}
filter: {y[& x'y]}
reject: {y[& ~x'y]}
adjacent: {1 = _abs (z?x) - (z?y)}
p: perm[`Baker `Cooper `Fletcher `Miller `Smith]
p: reject[{`Cooper=x[0]}; p]
p: reject[{`Baker=x[4]}; p]
p: filter[{(x ? `Miller) > (x ? `Cooper)}; p]
p: reject[{adjacent[`Smith; `Fletcher; x]}; p]
p: reject[{adjacent[`Cooper; `Fletcher; x]}; p]
p: reject[{(x ? `Fletcher)_in (0 4)}; p]
|
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
| #Fortran | Fortran | program test_dot_product
write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1])
end program test_dot_product |
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
| #Frink | Frink | dotProduct[v1, v2] :=
{
if length[v1] != length[v2]
{
println["dotProduct: vectors are of different lengths."]
return undef
}
return sum[map[{|c1,c2| c1 * c2}, zip[v1, v2]]]
} |
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
| #Fortran | Fortran |
program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"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' &
]
call printme( trim(strings(1)), ' ' )
call printme( strings(2:4), ['-','7','.'] )
call printme( strings(5), [' ','-','r'] )
contains
impure elemental subroutine printme(str,chr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: chr
character(len=:),allocatable :: answer
write(*,'(a)')repeat('=',9)
write(*,'("IN: <<<",g0,">>>")')str
answer=compact(str,chr)
write(*,'("OUT: <<<",g0,">>>")')answer
write(*,'("LENS: ",*(g0,1x))')"from",len(str),"to",len(answer),"for a change of",len(str)-len(answer)
write(*,'("CHAR: ",g0)')chr
end subroutine printme
elemental function compact(str,charp) result (outstr)
character(len=*),intent(in) :: str
character(len=1),intent(in) :: charp
character(len=:),allocatable :: outstr
character(len=1) :: ch, last_one
integer :: i, pio ! position in output
outstr=repeat(' ',len(str)) ! start with a string big enough to hold any output
if(len(outstr)==0)return ! handle edge condition
last_one=str(1:1) ! since at least this long start output with first character
outstr(1:1)=last_one
pio=1
do i=2,len(str)
ch=str(i:i)
pio=pio+merge(0,1, ch.eq.last_one.and.ch.eq.charp) ! decide whether to advance before saving
outstr(pio:pio)=ch ! store new one or overlay the duplcation
last_one=ch
enddo
outstr=outstr(:pio) ! trim the output string to just what was set
end function compact
end program main
} |
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. | #D | D | import std.stdio, std.math, std.algorithm, std.range, std.typecons;
auto mean(T)(in T[] xs) pure nothrow @nogc {
return xs.sum / xs.length;
}
auto stdDev(T)(in T[] xs) pure nothrow {
immutable m = xs.mean;
return sqrt(xs.map!(x => (x - m) ^^ 2).sum / xs.length);
}
alias TF = double function(in double, in double) pure nothrow @nogc;
auto funnel(T)(in T[] dxs, in T[] dys, in TF rule) {
T x = 0, y = 0;
immutable(T)[] rxs, rys;
foreach (const dx, const dy; zip(dxs, dys)) {
immutable rx = x + dx;
immutable ry = y + dy;
x = rule(x, dx);
y = rule(y, dy);
rxs ~= rx;
rys ~= ry;
}
return tuple!("x", "y")(rxs, rys);
}
void experiment(T)(in string label,
in T[] dxs, in T[] dys, in TF rule) {
//immutable (rxs, rys) = funnel(dxs, dys, rule);
immutable rs = funnel(dxs, dys, rule);
label.writeln;
writefln("Mean x, y: %.4f, %.4f", rs.x.mean, rs.y.mean);
writefln("Std dev x, y: %.4f, %.4f", rs.x.stdDev, rs.y.stdDev);
writeln;
}
void main() {
immutable 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];
immutable 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];
static assert(dxs.length == dys.length);
experiment("Rule 1:", dxs, dys, (z, dz) => 0.0);
experiment("Rule 2:", dxs, dys, (z, dz) => -dz);
experiment("Rule 3:", dxs, dys, (z, dz) => -(z + dz));
experiment("Rule 4:", dxs, dys, (z, dz) => 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
| #11l | 11l | print(‘Police Sanitation Fire’)
print(‘----------------------------------’)
L(police) (2..6).step(2)
L(sanitation) 1..7
L(fire) 1..7
I police!=sanitation & sanitation!=fire & fire!=police & police+fire+sanitation==12
print(police"\t\t"sanitation"\t\t"fire) |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #J | J | extend=: {{ y;y,L:0(1+each i.1-{:y)}}
($~ q:@$)(#~ 1 p: ])10#.&>([:~.@;extend each)^:# >:i.9
2 3 31 43 41 431 421 5 53 541 521 5431 61 653 643 641 631 6521 6421 7 73 71 761 751 743 7643 7621 7541 7321
76543 76541 76421 75431 764321 83 863 853 821 8761 8753 8741 8731 8641 8543 8521 8431 87643 87641 87631 87541 87421 86531 876431 865321 8765321 8764321 97 983
971 953 941 9871 9851 9743 9721 9643 9631 9521 9431 9421 98731 98641 98621 98543 98321 97651 96431 94321 987631 987541 986543 975421 9875321 9754321 98765431 98764321 97654321 |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Julia | Julia | using Combinatorics
using Primes
function descendingprimes()
return sort!(filter(isprime, [evalpoly(10, x)
for x in powerset([1, 2, 3, 4, 5, 6, 7, 8, 9]) if !isempty(x)]))
end
foreach(p -> print(rpad(p[2], 10), p[1] % 10 == 0 ? "\n" : ""), enumerate(descendingprimes()))
|
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Lua | Lua | local function is_prime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
for f = 5, n^0.5, 6 do
if n%f==0 or n%(f+2)==0 then return false end
end
return true
end
local function descending_primes()
local digits, candidates, primes = {9,8,7,6,5,4,3,2,1}, {0}, {}
for i = 1, #digits do
for j = 1, #candidates do
local value = candidates[j] * 10 + digits[i]
if is_prime(value) then primes[#primes+1] = value end
candidates[#candidates+1] = value
end
end
table.sort(primes)
return primes
end
print(table.concat(descending_primes(), ", ")) |
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)
| #C.2B.2B | C++ | #include <vector>
#include <iostream>
#include <stdexcept>
using namespace std;
typedef std::pair<double, double> TriPoint;
inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3)
{
return +p1.first*(p2.second-p3.second)
+p2.first*(p3.second-p1.second)
+p3.first*(p1.second-p2.second);
}
void CheckTriWinding(TriPoint &p1, TriPoint &p2, TriPoint &p3, bool allowReversed)
{
double detTri = Det2D(p1, p2, p3);
if(detTri < 0.0)
{
if (allowReversed)
{
TriPoint a = p3;
p3 = p2;
p2 = a;
}
else throw std::runtime_error("triangle has wrong winding direction");
}
}
bool BoundaryCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)
{
return Det2D(p1, p2, p3) < eps;
}
bool BoundaryDoesntCollideChk(TriPoint &p1, TriPoint &p2, TriPoint &p3, double eps)
{
return Det2D(p1, p2, p3) <= eps;
}
bool TriTri2D(TriPoint *t1,
TriPoint *t2,
double eps = 0.0, bool allowReversed = false, bool onBoundary = true)
{
//Trangles must be expressed anti-clockwise
CheckTriWinding(t1[0], t1[1], t1[2], allowReversed);
CheckTriWinding(t2[0], t2[1], t2[2], allowReversed);
bool (*chkEdge)(TriPoint &, TriPoint &, TriPoint &, double) = NULL;
if(onBoundary) //Points on the boundary are considered as colliding
chkEdge = BoundaryCollideChk;
else //Points on the boundary are not considered as colliding
chkEdge = BoundaryDoesntCollideChk;
//For edge E of trangle 1,
for(int i=0; i<3; i++)
{
int j=(i+1)%3;
//Check all points of trangle 2 lay on the external side of the edge E. If
//they do, the triangles do not collide.
if (chkEdge(t1[i], t1[j], t2[0], eps) &&
chkEdge(t1[i], t1[j], t2[1], eps) &&
chkEdge(t1[i], t1[j], t2[2], eps))
return false;
}
//For edge E of trangle 2,
for(int i=0; i<3; i++)
{
int j=(i+1)%3;
//Check all points of trangle 1 lay on the external side of the edge E. If
//they do, the triangles do not collide.
if (chkEdge(t2[i], t2[j], t1[0], eps) &&
chkEdge(t2[i], t2[j], t1[1], eps) &&
chkEdge(t2[i], t2[j], t1[2], eps))
return false;
}
//The triangles collide
return true;
}
int main()
{
{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};
TriPoint t2[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,6)};
cout << TriTri2D(t1, t2) << "," << true << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};
TriPoint t2[] = {TriPoint(0,0),TriPoint(0,5),TriPoint(5,0)};
cout << TriTri2D(t1, t2, 0.0, true) << "," << true << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(0,5)};
TriPoint t2[] = {TriPoint(-10,0),TriPoint(-5,0),TriPoint(-1,6)};
cout << TriTri2D(t1, t2) << "," << false << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(5,0),TriPoint(2.5,5)};
TriPoint t2[] = {TriPoint(0,4),TriPoint(2.5,-1),TriPoint(5,4)};
cout << TriTri2D(t1, t2) << "," << true << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};
TriPoint t2[] = {TriPoint(2,1),TriPoint(3,0),TriPoint(3,2)};
cout << TriTri2D(t1, t2) << "," << false << endl;}
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,1),TriPoint(0,2)};
TriPoint t2[] = {TriPoint(2,1),TriPoint(3,-2),TriPoint(3,4)};
cout << TriTri2D(t1, t2) << "," << false << endl;}
//Barely touching
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};
TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};
cout << TriTri2D(t1, t2, 0.0, false, true) << "," << true << endl;}
//Barely touching
{TriPoint t1[] = {TriPoint(0,0),TriPoint(1,0),TriPoint(0,1)};
TriPoint t2[] = {TriPoint(1,0),TriPoint(2,0),TriPoint(1,1)};
cout << TriTri2D(t1, t2, 0.0, false, false) << "," << false << endl;}
} |
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.
| #8th | 8th |
"input.txt" f:rm drop
"/input.txt" f:rm drop
"docs" f:rmdir drop
"/docs" f:rmdir drop
|
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program deleteFic64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ UNLINK, 35
.equ AT_REMOVEDIR, 0x200 // flag for delete directory
/******************************************/
/* Initialized data */
/******************************************/
.data
szMessDeleteDirOk: .asciz "Delete directory Ok.\n"
szMessErrDeleteDir: .asciz "Unable delete dir. \n"
szMessDeleteFileOk: .asciz "Delete file Ok.\n"
szMessErrDeleteFile: .asciz "Unable delete file. \n"
szNameDir: .asciz "Docs"
szNameFile: .asciz "input.txt"
/******************************************/
/* UnInitialized data */
/******************************************/
.bss
/******************************************/
/* code section */
/******************************************/
.text
.global main
main: // entry of program
// delete file
mov x0,AT_FDCWD // current directory
ldr x1,qAdrszNameFile // file name
mov x8,UNLINK // code call system delete file
svc 0 // call systeme
cmp x0,0 // error ?
blt 99f
ldr x0,qAdrszMessDeleteFileOk // delete file OK
bl affichageMess
// delete directory
mov x0,AT_FDCWD // current directory
ldr x1,qAdrszNameDir // directory name
mov x2,AT_REMOVEDIR
mov x8,UNLINK // code call system delete directory
svc 0 // call systeme
cmp x0,0 // error ?
blt 98f
ldr x0,qAdrszMessDeleteDirOk // display message ok directory
bl affichageMess
// end Ok
b 100f
98: // display error message delete directory
ldr x0,qAdrszMessErrDeleteDir
bl affichageMess
b 100f
99: // display error message delete file
ldr x0,qAdrszMessErrDeleteFile
bl affichageMess
b 100f
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessDeleteDirOk: .quad szMessDeleteDirOk
qAdrszMessErrDeleteDir: .quad szMessErrDeleteDir
qAdrszMessDeleteFileOk: .quad szMessDeleteFileOk
qAdrszNameFile: .quad szNameFile
qAdrszMessErrDeleteFile: .quad szMessErrDeleteFile
qAdrszNameDir: .quad szNameDir
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #Delphi | Delphi |
program Determinant_and_permanent;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TMatrix = TArray<TArray<Double>>;
function Minor(a: TMatrix; x, y: Integer): TMatrix;
begin
var len := Length(a) - 1;
SetLength(result, len, len);
for var i := 0 to len - 1 do
begin
for var j := 0 to len - 1 do
begin
if ((i < x) and (j < y)) then
begin
result[i][j] := a[i][j];
end
else if ((i >= x) and (j < y)) then
begin
result[i][j] := a[i + 1][j];
end
else if ((i < x) and (j >= y)) then
begin
result[i][j] := a[i][j + 1];
end
else //i>x and j>y
result[i][j] := a[i + 1][j + 1];
end;
end;
end;
function det(a: TMatrix): Double;
begin
if length(a) = 1 then
exit(a[0][0]);
var sign := 1;
result := 0.0;
for var i := 0 to high(a) do
begin
result := result + sign * a[0][i] * det(minor(a, 0, i));
sign := sign * - 1;
end;
end;
function perm(a: TMatrix): Double;
begin
if Length(a) = 1 then
exit(a[0][0]);
Result := 0;
for var i := 0 to high(a) do
result := result + a[0][i] * perm(Minor(a, 0, i));
end;
function Readint(Min, Max: Integer; Prompt: string): Integer;
var
val: string;
vali: Integer;
begin
Result := -1;
repeat
writeln(Prompt);
Readln(val);
if TryStrToInt(val, vali) then
if (vali < Min) or (vali > Max) then
writeln(vali, ' is out range [', Min, '...', Max, ']')
else
exit(vali)
else
writeln(val, ' is not a number valid');
until false;
end;
function ReadDouble(Min, Max: double; Prompt: string): double;
var
val: string;
vali: double;
begin
Result := -1;
repeat
writeln(Prompt);
Readln(val);
if TryStrToFloat(val, vali) then
if (vali < Min) or (vali > Max) then
writeln(vali, ' is out range [', Min, '...', Max, ']')
else
exit(vali)
else
writeln(val, ' is not a number valid');
until false;
end;
procedure ShowMatrix(a: TMatrix);
begin
var sz := length(a);
for var i := 0 to sz - 1 do
begin
Write('[');
for var j := 0 to sz - 1 do
write(a[i][j]: 3: 2, ' ');
Writeln(']');
end;
end;
var
a: TMatrix;
sz: integer;
begin
sz := Readint(1, 10, 'Enter with matrix size: ');
SetLength(a, sz, sz);
for var i := 0 to sz - 1 do
for var j := 0 to sz - 1 do
begin
a[i][j] := ReadDouble(-1000, 1000, format('Enter a value of position (%d,%d):',
[i, j]));
end;
writeln('Matrix defined: ');
ShowMatrix(a);
writeln(#10'Determinant: ', det(a): 3: 2);
writeln(#10'Permanent: ', perm(a): 3: 2);
readln;
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.
| #Batch_File | Batch File | @echo off
set /a dummy=5/0 2>nul
if %errorlevel%==1073750993 echo I caught a division by zero operation...
exit /b 0 |
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.
| #BQN | BQN | Div ← {∨´"∞"‿"NaN"≡¨<•Fmt𝕩}◶⊢‿"Division by 0"÷
•Show 5 Div 0
•Show 5 Div 5
•Show 0 Div 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
| #Arturo | Arturo | print numeric? "hello world"
print numeric? "1234"
print numeric? "1234 hello world"
print numeric? "12.34"
print numeric? "!#@$"
print numeric? "-1.23" |
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
| #AutoHotkey | AutoHotkey | list = 0 .14 -5.2 ten 0xf
Loop, Parse, list, %A_Space%
MsgBox,% IsNumeric(A_LoopField)
Return
IsNumeric(x) {
If x is number
Return, 1
Else Return, 0
}
;Output: 1 1 1 0 1 |
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
| #C.23 | C# | using System;
using System.Linq;
public class Program
{
static void Main
{
string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"};
foreach (string s in input) {
Console.WriteLine($"\"{s}\" (Length {s.Length}) " +
string.Join(", ",
s.Select((c, i) => (c, i))
.GroupBy(t => t.c).Where(g => g.Count() > 1)
.Select(g => $"'{g.Key}' (0X{(int)g.Key:X})[{string.Join(", ", g.Select(t => t.i))}]")
.DefaultIfEmpty("All characters are unique.")
)
);
}
}
} |
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
| #Delphi | Delphi |
program Determine_if_a_string_is_collapsible;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure collapsible(s: string);
var
c, last: char;
len: Integer;
begin
writeln('old: <<<', s, '>>>, length = ', s.length);
write('new: <<<');
last := #0;
len := 0;
for c in s do
begin
if c <> last then
begin
write(c);
inc(len);
end;
last := c;
end;
writeln('>>>, length = ', len, #10);
end;
begin
collapsible('');
collapsible('"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ');
collapsible('..1111111111111111111111111111111111111111111111111111111111111117777888');
collapsible('I never give ''em hell, I just tell the truth, and they think it''s hell. ');
collapsible(' --- Harry S Truman ');
readln;
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
| #F.23 | F# |
// Collapse a String. Nigel Galloway: June 9th., 2020
//As per the task description a function which 'determines if a character string is collapsible' by testing if any consecutive characters are the same.
let isCollapsible n=n|>Seq.pairwise|>Seq.tryFind(fun(n,g)->n=g)
//As per the task description a function which 'if the string is collapsable, collapses the string (by removing immediately repeated characters).
let collapse n=match isCollapsible n with
Some _->let i=Seq.head n
let fN=let mutable g=i in (fun n->if n=g then false else g<-n; true)
let g=System.String([|yield i;yield! Seq.tail n|>Seq.filter fN|])
printfn "<<<%s>>> (length %d) colapses to <<<%s>>> (length %d)" n n.Length g g.Length
| _->printfn "<<<%s>>> (length %d) does not colapse" n n.Length
collapse ""
collapse "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
collapse "..1111111111111111111111111111111111111111111111111111111111111117777888"
collapse "I never give 'em hell, I just tell the truth, and they think it's hell. "
collapse " --- Harry S Truman "
collapse "withoutConsecutivelyRepeatedCharacters"
|
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Wren | Wren | var throwDie // recursive
throwDie = Fn.new { |nSides, nDice, s, counts|
if (nDice == 0) {
counts[s] = counts[s] + 1
return
}
for (i in 1..nSides) throwDie.call(nSides, nDice-1, s + i, counts)
}
var beatingProbability = Fn.new { |nSides1, nDice1, nSides2, nDice2|
var len1 = (nSides1 + 1) * nDice1
var c1 = List.filled(len1, 0)
throwDie.call(nSides1, nDice1, 0, c1)
var len2 = (nSides2 + 1) * nDice2
var c2 = List.filled(len2, 0)
throwDie.call(nSides2, nDice2, 0, c2)
var p12 = nSides1.pow(nDice1) * nSides2.pow(nDice2)
var tot = 0
for (i in 0...len1) {
for (j in 0...i.min(len2)) {
tot = tot + c1[i] * c2[j] / p12
}
}
return tot
}
System.print(beatingProbability.call(4, 9, 6, 6))
System.print(beatingProbability.call(10, 5, 7, 6)) |
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
| #D | D | import std.stdio;
void analyze(string s) {
writefln("Examining [%s] which has a length of %d:", s, s.length);
if (s.length > 1) {
auto b = s[0];
foreach (i, c; s[1..$]) {
if (c != b) {
writeln(" Not all characters in the string are the same.");
writefln(" '%c' (0x%x) is different at position %d", c, c, i);
return;
}
}
}
writeln(" All characters in the string are the same.");
}
void main() {
auto strs = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k"];
foreach (str; strs) {
analyze(str);
}
} |
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.
| #Julia | Julia |
mutable struct Philosopher
name::String
hungry::Bool
righthanded::Bool
rightforkheld::Channel
leftforkheld::Channel
function Philosopher(name, leftfork, rightfork)
this = new()
this.name = name
this.hungry = rand([false, true]) # not specified so start as either
this.righthanded = (name == "Aristotle") ? false : true
this.leftforkheld = leftfork
this.rightforkheld = rightfork
this
end
end
mutable struct FiveForkTable
fork51::Channel
fork12::Channel
fork23::Channel
fork34::Channel
fork45::Channel
function FiveForkTable()
this = new()
this.fork51 = Channel(1); put!(this.fork51, "fork") # start with one fork per channel
this.fork12 = Channel(1); put!(this.fork12, "fork")
this.fork23 = Channel(1); put!(this.fork23, "fork")
this.fork34 = Channel(1); put!(this.fork34, "fork")
this.fork45 = Channel(1); put!(this.fork45, "fork")
this
end
end
table = FiveForkTable();
tasks = [Philosopher("Aristotle", table.fork12, table.fork51),
Philosopher("Kant", table.fork23, table.fork12),
Philosopher("Spinoza", table.fork34, table.fork23),
Philosopher("Marx", table.fork45, table.fork34),
Philosopher("Russell", table.fork51, table.fork45)]
function dine(t,p)
if p.righthanded
take!(p.rightforkheld); println("$(p.name) takes right fork")
take!(p.leftforkheld); println("$(p.name) takes left fork")
else
take!(p.leftforkheld); println("$(p.name) takes left fork")
take!(p.rightforkheld); println("$(p.name) takes right fork")
end
end
function leavetothink(t, p)
put!(p.rightforkheld, "fork"); println("$(p.name) puts down right fork")
put!(p.leftforkheld, "fork"); println("$(p.name) puts down left fork")
end
contemplate(t) = sleep(t)
function dophil(p, t, fullaftersecs=2.0, hungryaftersecs=10.0)
while true
if p.hungry
println("$(p.name) is hungry")
dine(table, p)
sleep(fullaftersecs)
p.hungry = false
leavetothink(t, p)
else
println("$(p.name) is out of the dining room for now.")
contemplate(hungryaftersecs)
p.hungry = true
end
end
end
function runall(tasklist)
for p in tasklist
@async dophil(p, table)
end
while true begin sleep(5) end end
end
runall(tasks)
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #JavaScript | JavaScript |
/**
* All Hail Discordia! - this script prints Discordian date using system date.
*
* lang: JavaScript
* author: jklu
* contributors: JamesMcGuigan
*
* changelog:
* - Modified to return same output syntax as unix ddate + module.exports - James McGuigan, 2/Chaos/3183
*
* source: https://rosettacode.org/wiki/Discordian_date#JavaScript
*/
var seasons = [
"Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"
];
var weekday = [
"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"
];
var apostle = [
"Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"
];
var holiday = [
"Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"
];
Date.prototype.isLeapYear = function() {
var year = this.getFullYear();
if( (year & 3) !== 0 ) { return false; }
return ((year % 100) !== 0 || (year % 400) === 0);
};
// Get Day of Year
Date.prototype.getDOY = function() {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var mn = this.getMonth();
var dn = this.getDate();
var dayOfYear = dayCount[mn] + dn;
if( mn > 1 && this.isLeapYear() ) { dayOfYear++; }
return dayOfYear;
};
Date.prototype.isToday = function() {
var today = new Date();
return this.getDate() === today.getDate()
&& this.getMonth() === today.getMonth()
&& this.getFullYear() === today.getFullYear()
;
};
function discordianDate(date) {
if( !date ) { date = new Date(); }
var y = date.getFullYear();
var yold = y + 1166;
var dayOfYear = date.getDOY();
var celebrateHoliday = null;
if( date.isLeapYear() ) {
if( dayOfYear == 60 ) {
celebrateHoliday = "St. Tib's Day";
}
else if( dayOfYear > 60 ) {
dayOfYear--;
}
}
dayOfYear--;
var divDay = Math.floor(dayOfYear / 73);
var seasonDay = (dayOfYear % 73) + 1;
if( seasonDay == 5 ) {
celebrateHoliday = apostle[divDay];
}
if( seasonDay == 50 ) {
celebrateHoliday = holiday[divDay];
}
var season = seasons[divDay];
var dayOfWeek = weekday[dayOfYear % 5];
var nth = (seasonDay % 10 == 1) ? 'st'
: (seasonDay % 10 == 2) ? 'nd'
: (seasonDay % 10 == 3) ? 'rd'
: 'th';
return "" //(date.isToday() ? "Today is " : '')
+ dayOfWeek
+ ", the " + seasonDay + nth
+ " day of " + season
+ " in the YOLD " + yold
+ (celebrateHoliday ? ". Celebrate " + celebrateHoliday + "!" : '')
;
}
function test(y, m, d, result) {
console.assert((discordianDate(new Date(y, m, d)) == result), [y, m, d, discordianDate(new Date(y, m, d)), result]);
}
// Only run test code if node calls this file directly
if( require.main === module ) {
console.log(discordianDate(new Date(Date.now())));
test(2010, 6, 22, "Pungenday, the 57th day of Confusion in the YOLD 3176");
test(2012, 1, 28, "Prickle-Prickle, the 59th day of Chaos in the YOLD 3178");
test(2012, 1, 29, "Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib's Day!");
test(2012, 2, 1, "Setting Orange, the 60th day of Chaos in the YOLD 3178");
test(2010, 0, 5, "Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!");
test(2011, 4, 3, "Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!");
test(2015, 9, 19, "Boomtime, the 73rd day of Bureaucracy in the YOLD 3181");
}
module.exports = discordianDate;
|
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)
| #Lua | Lua | -- Graph definition
local edges = {
a = {b = 7, c = 9, f = 14},
b = {c = 10, d = 15},
c = {d = 11, f = 2},
d = {e = 6},
e = {f = 9}
}
-- Fill in paths in the opposite direction to the stated edges
function complete (graph)
for node, edges in pairs(graph) do
for edge, distance in pairs(edges) do
if not graph[edge] then graph[edge] = {} end
graph[edge][node] = distance
end
end
end
-- Create path string from table of previous nodes
function follow (trail, destination)
local path, nextStep = destination, trail[destination]
while nextStep do
path = nextStep .. " " .. path
nextStep = trail[nextStep]
end
return path
end
-- Find the shortest path between the current and destination nodes
function dijkstra (graph, current, destination, directed)
if not directed then complete(graph) end
local unvisited, distanceTo, trail = {}, {}, {}
local nearest, nextNode, tentative
for node, edgeDists in pairs(graph) do
if node == current then
distanceTo[node] = 0
trail[current] = false
else
distanceTo[node] = math.huge
unvisited[node] = true
end
end
repeat
nearest = math.huge
for neighbour, pathDist in pairs(graph[current]) do
if unvisited[neighbour] then
tentative = distanceTo[current] + pathDist
if tentative < distanceTo[neighbour] then
distanceTo[neighbour] = tentative
trail[neighbour] = current
end
if tentative < nearest then
nearest = tentative
nextNode = neighbour
end
end
end
unvisited[current] = false
current = nextNode
until unvisited[destination] == false or nearest == math.huge
return distanceTo[destination], follow(trail, destination)
end
-- Main procedure
print("Directed:", dijkstra(edges, "a", "e", true))
print("Undirected:", dijkstra(edges, "a", "e", false)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.