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/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
| #Logtalk | Logtalk | dot_product(A, B, Sum) :-
dot_product(A, B, 0, Sum).
dot_product([], [], Sum, Sum).
dot_product([A| As], [B| Bs], Acc, Sum) :-
Acc2 is Acc + A*B,
dot_product(As, Bs, Acc2, Sum). |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Vlang | Vlang | // Returns squeezed string, original and new lengths in
// unicode code points (not normalized).
fn squeeze(s string, c string) (string, int, int) {
mut r := s.runes()
mut t := c.runes()[0]
le, mut del := r.len, 0
for i := le - 2; i >= 0; i-- {
if r[i] == t && r[i] == r[i+1] {
r.delete(i)
del++
}
}
if del == 0 {
return s, le, le
}
r = r[..le-del]
return r.string(), le, r.len
}
fn main() {
strings := [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
]
chars := [[' '], ['-'], ['7'], ['.'], [' ', '-', 'r'], ['e'], ['s'], ['a'], ['😍']]
for i, s in strings {
for c in chars[i] {
ss, olen, slen := squeeze(s, c)
println("specified character = $c")
println("original : length = ${olen:2}, string = «««$s»»»")
println("squeezed : length = ${slen:2}, string = «««$ss»»»\n")
}
}
} |
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
| #Wren | Wren | import "/fmt" for Fmt
// Returns squeezed string, original and new lengths in
// unicode code points (not normalized).
var squeeze = Fn.new { |s, ch|
var c = s.codePoints.toList
var le = c.count
if (le < 2) return [s, le, le]
for (i in le-2..0) {
if (c[i] == ch.codePoints[0] && c[i] == c[i+1]) c.removeAt(i)
}
var cc = c.reduce("") { |acc, cp| acc + String.fromCodePoint(cp) }
return [cc, le, cc.count]
}
var strings = [
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌"
]
var chars = [ [" "], ["-"], ["7"], ["."], [" ", "-", "r"], ["e"], ["s"], ["a"], ["😍"] ]
var i = 0
for (s in strings) {
for (ch in chars[i]) {
var r = squeeze.call(s, ch)
System.print("Specified character = '%(ch)'")
System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
System.print("squeezed : length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
}
i = i + 1
} |
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
| #Delphi | Delphi |
program Department_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
i, j, k, count: Integer;
begin
writeln('Police Sanitation Fire');
writeln('------ ---------- ----');
count := 0;
i := 2;
while i < 7 do
begin
for j := 1 to 7 do
begin
if j = i then
Continue;
for k := 1 to 7 do
begin
if (k = i) or (k = j) then
Continue;
if i + j + k <> 12 then
Continue;
writeln(format(' %d %d %d', [i, j, k]));
inc(count);
end;
end;
inc(i, 2);
end;
writeln(#10, count, ' valid combinations');
readln;
end. |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Oforth | Oforth | Object Class new: Delegate1
Object Class new: Delegate2
Delegate2 method: thing "Delegate implementation" println ;
Object Class new: Delegator(delegate)
Delegator method: initialize := delegate ;
Delegator method: operation
@delegate respondTo(#thing) ifTrue: [ @delegate thing return ]
"Default implementation" println ; |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #ooRexx | ooRexx |
delegator = .delegator~new -- no delegate
say delegator~operation
-- an invalid delegate type
delegator~delegate = "Some string"
say delegator~operation
-- a good delegate
delegator~delegate = .thing~new
say delegator~operation
-- a directory object with a thing entry defined
d = .directory~new
d~thing = "delegate implementation"
delegator~delegate = d
say delegator~operation
-- a class we can use as a delegate
::class thing
::method thing
return "delegate implementation"
::class delegator
::method init
expose delegate
use strict arg delegate = .nil
::attribute delegate
::method operation
expose delegate
if delegate == .nil then return "default implementation"
-- Note: We could use delegate~hasMethod("THING") to check
-- for a THING method, but this will fail of the object relies
-- on an UNKNOWN method to handle the method. By trapping
-- NOMETHOD conditions, we can allow those calls to go
-- through
signal on nomethod
return delegate~thing
nomethod:
return "default implementation"
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #OxygenBasic | OxygenBasic |
class DelegateA 'not implmenting thing()
'==============
'
string message
end class
class DelegateB 'implementing thing()
'==============
'
string message
method thing() as string
return message
end method
'
end class
Class Delegator
'==============
'
has DelegateA dgA
has DelegateB dgB
'
method operation() as DelegateB
dgB.message="Delegate Implementation"
return @dgB
end method
method thing() as string
return "not using Delegate"
end method
'
end class
'====
'TEST
'====
Delegator dgr
let dg=dgr.operation
print dgr.thing 'result "not using Delegate"
print dg.thing 'result "Delegate Implementation"
|
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #Perl | Perl | use strict;
use warnings;
sub det2D {
my $p1 = shift or die "4 Missing first point\n";
my $p2 = shift or die "Missing second point\n";
my $p3 = shift or die "Missing third point\n";
return $p1->{x} * ($p2->{y} - $p3->{y})
+ $p2->{x} * ($p3->{y} - $p1->{y})
+ $p3->{x} * ($p1->{y} - $p2->{y});
}
sub checkTriWinding {
my $p1 = shift or die "14 Missing first point\n";
my $p2 = shift or die "Missing second point\n";
my $p3 = shift or die "Missing third point\n";
my $allowReversed = shift;
my $detTri = det2D($p1, $$p2, $$p3);
if ($detTri < 0.0) {
if ($allowReversed) {
my $t = $$p3;
$$p3 = $$p2;
$$p2 = $t;
} else {
die "triangle has wrong winding direction";
}
}
return undef;
}
sub boundaryCollideChk {
my $p1 = shift or die "33 Missing first point\n";
my $p2 = shift or die "Missing second point\n";
my $p3 = shift or die "Missing third point\n";
my $eps = shift;
return det2D($p1, $p2, $p3) < $eps;
}
sub boundaryDoesntCollideChk {
my $p1 = shift or die "42 Missing first point\n";
my $p2 = shift or die "Missing second point\n";
my $p3 = shift or die "Missing third point\n";
my $eps = shift;
return det2D($p1, $p2, $p3) <= $eps;
}
sub triTri2D {
my $t1 = shift or die "Missing first triangle to calculate with\n";
my $t2 = shift or die "Missing second triangle to calculate with\n";
my $eps = shift;
my $allowReversed = shift;
my $onBoundary = shift;
# triangles must be expressed anti-clockwise
checkTriWinding($t1->[0], \$t1->[1], \$t1->[2], $allowReversed);
checkTriWinding($t2->[0], \$t2->[1], \$t2->[2], $allowReversed);
my $chkEdge;
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 triangle 1
foreach my $i (0, 1, 2) {
my $j = ($i + 1) % 3;
# check all points of triangle 2 lay on the external side of edge E
# if they do, the triangles do not collide
if ($chkEdge->($t1->[$i], $t1->[$j], $t2->[0], $eps)
and $chkEdge->($t1->[$i], $t1->[$j], $t2->[1], $eps)
and $chkEdge->($t1->[$i], $t1->[$j], $t2->[2], $eps)) {
return 0; # false
}
}
# for edge E of triangle 2
foreach my $i (0, 1, 2) {
my $j = ($i + 1) % 3;
# check all points of triangle 1 lay on the external side of edge E
# if they do, the triangles do not collide
if ($chkEdge->($t2->[$i], $t2->[$j], $t1->[0], $eps)
and $chkEdge->($t2->[$i], $t2->[$j], $t1->[1], $eps)
and $chkEdge->($t2->[$i], $t2->[$j], $t1->[2], $eps)) {
return 0; # false
}
}
return 1; # true
}
sub formatTri {
my $t = shift or die "Missing triangle to format\n";
my $p1 = $t->[0];
my $p2 = $t->[1];
my $p3 = $t->[2];
return "Triangle: ($p1->{x}, $p1->{y}), ($p2->{x}, $p2->{y}), ($p3->{x}, $p3->{y})";
}
sub overlap {
my $t1 = shift or die "Missing first triangle to calculate with\n";
my $t2 = shift or die "Missing second triangle to calculate with\n";
my $eps = shift;
my $allowReversed = shift or 0; # false
my $onBoundary = shift or 1; # true
unless ($eps) {
$eps = 0.0;
}
if (triTri2D($t1, $t2, $eps, $allowReversed, $onBoundary)) {
return "overlap\n";
} else {
return "do not overlap\n";
}
}
###################################################
# Main
###################################################
my @t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5});
my @t2 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>6});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n";
@t1 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0});
@t2 = ({x=>0, y=>0}, {x=>0, y=>5}, {x=>5, y=>0});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 1), "\n";
@t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>0, y=>5});
@t2 = ({x=>-10, y=>0}, {x=>-5, y=>0}, {x=>-1, y=>6});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n";
@t1 = ({x=>0, y=>0}, {x=>5, y=>0}, {x=>2.5, y=>5});
@t2 = ({x=>0, y=>4}, {x=>2.5, y=>-1}, {x=>5, y=>4});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n";
@t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2});
@t2 = ({x=>2, y=>1}, {x=>3, y=>0}, {x=>3, y=>2});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n";
@t1 = ({x=>0, y=>0}, {x=>1, y=>1}, {x=>0, y=>2});
@t2 = ({x=>2, y=>1}, {x=>3, y=>-2}, {x=>3, y=>4});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2), "\n";
# Barely touching
@t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1});
@t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 1), "\n";
# Barely touching
@t1 = ({x=>0, y=>0}, {x=>1, y=>0}, {x=>0, y=>1});
@t2 = ({x=>1, y=>0}, {x=>2, y=>0}, {x=>1, y=>1});
print formatTri(\@t1), " and\n", formatTri(\@t2), "\n", overlap(\@t1, \@t2, 0.0, 0, 0), "\n"; |
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.
| #Groovy | Groovy | // Gets the first filesystem root. On most systems this will be / or c:\
def fsRoot = File.listRoots().first()
// Create our list of files (including directories)
def files = [
new File("input.txt"),
new File(fsRoot, "input.txt"),
new File("docs"),
new File(fsRoot, "docs")
]
/*
We use it.directory to determine whether each file is a regular file or directory. If it is a directory, we delete
it with deleteDir(), otherwise we just use delete().
*/
files.each{
it.directory ? it.deleteDir() : it.delete()
} |
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
| #PowerShell | PowerShell |
function det-perm ($array) {
if($array) {
$size = $array.Count
function prod($A) {
$prod = 1
if($A) { $A | foreach{$prod *= $_} }
$prod
}
function generate($sign, $n, $A) {
if($n -eq 1) {
$i = 0
$prod = prod @($A | foreach{$array[$i++][$_]})
[pscustomobject]@{det = $sign*$prod; perm = $prod}
}
else{
for($i = 0; $i -lt ($n - 1); $i += 1) {
generate $sign ($n - 1) $A
if($n % 2 -eq 0){
$i1, $i2 = $i, ($n-1)
$A[$i1], $A[$i2] = $A[$i2], $A[$i1]
}
else{
$i1, $i2 = 0, ($n-1)
$A[$i1], $A[$i2] = $A[$i2], $A[$i1]
}
$sign *= -1
}
generate $sign ($n - 1) $A
}
}
$det = $perm = 0
generate 1 $size @(0..($size-1)) | foreach{
$det += $_.det
$perm += $_.perm
}
[pscustomobject]@{det = "$det"; perm = "$perm"}
} else {Write-Error "empty array"}
}
det-perm 5
det-perm @(@(1,0,0),@(0,1,0),@(0,0,1))
det-perm @(@(0,0,1),@(0,1,0),@(1,0,0))
det-perm @(@(4,3),@(2,5))
det-perm @(@(2,5),@(4,3))
det-perm @(@(4,4),@(2,2))
|
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.
| #JavaScript | JavaScript | function divByZero(dividend,divisor)
{
var quotient=dividend/divisor;
if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity
return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively
}
alert(divByZero(0,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.
| #jq | jq | def div(x;y): if y==0 then error("NaN") else 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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim Shared symbols(0 To 15) As UByte
For i As Integer = 48 to 57
symbols(i - 48) = i
Next
For i As Integer = 97 to 102
symbols(i - 87) = i
Next
Const plus As UByte = 43
Const minus As Ubyte = 45
Const dot As UByte = 46
Function isNumeric(s As Const String, base_ As Integer = 10) As Boolean
If s = "" OrElse s = "." OrElse s = "+" OrElse s = "-" Then Return False
Err = 0
If base_ < 2 OrElse base_ > 16 Then
Err = 1000
Return False
End If
Dim t As String = LCase(s)
If (t[0] = plus) OrElse (t[0] = minus) Then
t = Mid(t, 2)
End If
If Left(t, 2) = "&h" Then
If base_ <> 16 Then Return False
t = Mid(t, 3)
End if
If Left(t, 2) = "&o" Then
If base_ <> 8 Then Return False
t = Mid(t, 3)
End if
If Left(t, 2) = "&b" Then
If base_ <> 2 Then Return False
t = Mid(t, 3)
End if
If Len(t) = 0 Then Return False
Dim As Boolean isValid, hasDot = false
For i As Integer = 0 To Len(t) - 1
isValid = False
For j As Integer = 0 To base_ - 1
If t[i] = symbols(j) Then
isValid = True
Exit For
End If
If t[i] = dot Then
If CInt(Not hasDot) AndAlso (base_ = 10) Then
hasDot = True
IsValid = True
Exit For
End If
Return False ' either more than one dot or not base 10
End If
Next j
If Not isValid Then Return False
Next i
Return True
End Function
Dim s As String
s = "1234.056789"
Print s, " (base 10) => "; isNumeric(s)
s = "1234.56"
Print s, " (base 7) => "; isNumeric(s, 7)
s = "021101"
Print s, " (base 2) => "; isNumeric(s, 2)
s = "Dog"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "Bad125"
Print s, " (base 16) => "; isNumeric(s, 16)
s = "-0177"
Print s, " (base 8) => "; isNumeric(s, 8)
s = "+123abcd.ef"
Print s, " (base 16) => "; isNumeric(s, 8)
s = "54321"
Print s, " (base 6) => "; isNumeric(s, 6)
s = "123xyz"
Print s, " (base 10) => "; isNumeric(s)
s = "xyz"
Print s, " (base 10) => "; isNumeric(s)
Print
Print "Press any key to quit"
Sleep |
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
| #Nanoquery | Nanoquery | def analyze(s)
s = str(s)
println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"
if len(s) < 2
println "\tAll characters in the string are unique."
return
end
seen = list()
for i in range(0, len(s) - 2)
if s[i] in seen
println "\tNot all characters in the string are unique."
println "\t'" + s[i] + "' " + format("(0x%x)", ord(s[i])) +\
" is duplicated at positions " + str(i + 1) + " and " +\
str(s.indexOf(s[i]) + 1)
return
end
seen.append(s[i])
end
println "\tAll characters in the string are unique."
end
tests = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"}
for s in tests
analyze(s)
end |
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
| #Nim | Nim | import unicode, strformat
proc checkUniqueChars(s: string) =
echo fmt"Checking string ""{s}"":"
let runes = s.toRunes
for i in 0..<runes.high:
let rune = runes[i]
for j in (i+1)..runes.high:
if runes[j] == rune:
echo "The string contains duplicate characters."
echo fmt"Character {rune} ({int(rune):x}) is present at positions {i+1} and {j+1}."
echo ""
return
echo "All characters in the string are unique."
echo ""
const Strings = ["",
".",
"abcABC",
"XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"hétérogénéité",
"🎆🎃🎇🎈",
"😍😀🙌💃😍🙌",
"🐠🐟🐡🦈🐬🐳🐋🐡"]
for s in Strings:
s.checkUniqueChars() |
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
| #Sidef | Sidef | func squeeze(str) {
str.gsub(/(.)\1+/, {|s1| s1 })
}
var strings = ["",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌"]
strings.each {|str|
var ssq = squeeze(str)
say "«««#{str}»»» (length: #{str.len})"
say "«««#{ssq}»»» (length: #{ssq.len})\n"
} |
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
| #Smalltalk | Smalltalk | #(
'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!'
'headmistressship'
'aardvark'
'😍😀🙌💃😍😍😍🙌'
) do:[:eachWord |
|shortened|
shortened :=
String streamContents:[:out |
eachWord inject:nil into:[:prev :this |
prev ~= this ifTrue:[out nextPut:this].
this
]
].
Transcript
showCR:( eachWord,'(length:',eachWord size,')' );
showCR:( shortened,'(length:',shortened size,')' ).
] |
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
| #PicoLisp | PicoLisp | (de equal? (Str)
(let (Lst (chop Str) C (car Lst) P 2 F)
(prin Str ": ")
(for A (cdr Lst)
(NIL (= A C) (on F) (prin "First different character " A))
(inc 'P) )
(if F (prinl " at position: " P) (prinl "all characters are the same")) ) )
(equal?)
(equal? " ")
(equal? "333")
(equal? ".55")
(equal? "tttTTT") |
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
| #Plain_English | Plain English | To run:
Start up.
Show the uniformity of "".
Show the uniformity of " ".
Show the uniformity of "2".
Show the uniformity of "333".
Show the uniformity of ".55".
Show the uniformity of "tttTTT".
Show the uniformity of "4444 444k".
Wait for the escape key.
Shut down.
To find the first different character in a string giving a byte and a count:
If the string is blank, put -1 into the count; exit.
Put the string's first's target into a first letter.
Slap a substring on the string.
Loop.
If a counter is past the string's length, put -1 into the count; exit.
Put the substring's first's target into a letter.
If the letter is not the first letter, put the letter into the byte; put the counter minus 1 into the count; exit.
Add 1 to the substring's first.
Repeat.
To show the uniformity of a string:
Write """" then the string then """ (length " then the string's length then ") " on the console without advancing.
Find the first different character in the string giving a byte and a count.
If the count is -1, write "contains all the same character." on the console; exit.
Convert the byte to a nibble string.
Write "contains a different character at index " then the count then ": '" then the byte then "' (0x" then the nibble string then ")." on the console. |
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.
| #REXX | REXX | /*REXX program demonstrates a solution in solving the dining philosophers problem. */
signal on halt /*branches to HALT: (on Ctrl─break).*/
parse arg seed diners /*obtain optional arguments from the CL*/
if datatype(seed, 'W') then call random ,, seed /*this allows for random repeatability.*/
if diners= '' then diners = 'Aristotle, Kant, Spinoza, Marx, Russell'
tell= left(seed, 1) \== '+' /*Leading + in SEED? Then no statistics*/
diners= space( translate(diners, , ',') ) /*change to an uncommatized diners list*/
#= words(diners); @.= 0 /*#: the number of dining philosophers.*/
eatL= 15; eatH= 60 /*minimum & maximum minutes for eating.*/
thinkL= 30; thinkH= 180 /* " " " " " thinking*/
forks.= 1 /*indicate that all forks are on table.*/
do tic=1 /*'til halted.*/ /*use "minutes" for time advancement.*/
call grabForks /*determine if anybody can grab 2 forks*/
call passTime /*handle philosophers eating|thinking. */
end /*tic*/ /* ··· and time marches on ··· */
/* [↓] this REXX program was halted,*/
halt: say ' ··· REXX program halted!' /*probably by Ctrl─Break or equivalent.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fork: parse arg x 1 ox; x= abs(x) ; L= x - 1 ; if L==0 then L= # /*use "round Robin"*/
if ox<0 then do; forks.L= 1; forks.x=1; return; end /*drop the forks. */
got2= forks.L & forks.x /*get 2 forks │ not*/
if got2 then do; forks.L= 0; forks.x=0; end /*obtained 2 forks */
return got2 /*return with success ··· or failure. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
grabForks: do person=1 for # /*see if any person can grab two forks.*/
if @.person.state\==0 then iterate /*this diner ain't in a waiting state. */
if \fork(person) then iterate /* " " didn't grab two forks. */
@.person.state= 'eating' /* " " is slurping spaghetti. */
@.person.dur= random(eatL, eatH) /*how long will this diner eat pasta ? */
end /*person*/ /* [↑] process the dining philosophers*/
return /*all the diners have been examined. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
passTime: if tell then say /*display a handy blank line separator.*/
do p=1 for # /*handle each of the diner's activity. */
if tell then say right(tic, 9, .) right( word( diners, p), 20),
right(word(@.p.state 'waiting',1+(@.p.state==0)),9) right(@.p.dur,5)
if @.p.dur==0 then iterate /*this diner is waiting for two forks. */
@.p.dur= @.p.dur - 1 /*indicate single time unit has passed.*/
if @.p.dur\==0 then iterate /*Activity done? No, then keep it up.*/
if @.p.state=='eating' then do /*now, leave the table.*/
call fork -p /*drop the darn forks. */
@.p.state= 'thinking' /*status.*/
@.p.dur= random(thinkL, thinkH) /*length.*/
end /* [↓] a diner goes ──► the table. */
else if @.p.state=='thinking' then @.p.state=0
end /*p*/ /*[↑] P (person)≡ dining philosophers.*/
return /*now, have some human beans grab forks*/ |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Racket | Racket | #lang racket/base
;;;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;;;; Derived from 'D' Implementation
;;;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(require racket/date racket/match)
(define seasons '(Chaos Discord Confusion Bureaucracy |The Aftermath|))
(define weekday '(Sweetmorn Boomtime Pungenday Prickle-Prickle |Setting Orange|))
(define apostle '(Mungday Mojoday Syaday Zaraday Maladay))
(define holiday '(Chaoflux Discoflux Confuflux Bureflux Afflux))
(define (ymd->date y m d) (seconds->date (find-seconds 0 0 0 d m y)))
(define (leap-year? y) (with-handlers ((exn? (λ (x) #f))) (= 29 (date-day (ymd->date y 2 29)))))
(define (discordian-date d)
(define leap? (leap-year? (date-year d)))
(define year-day (match* (leap? (date-year-day d))
[(#t (? (λ (D) (>= D 59)) d0)) d0]
[(_ d0) (add1 d0)]))
(define season-day (modulo year-day 73)) ; season day
(define (list-ref-season l)
(define season-index (quotient year-day 73))
(symbol->string (list-ref l season-index)))
(string-append
(match* (season-day leap? (date-month d) (date-day d))
[( _ #t 2 29) "St. Tib's Day,"]
[((app (match-lambda
(5 apostle) (50 holiday) (_ #f))
(and (not #f) special)) _ _ _)
(string-append (list-ref-season special) ",")]
[( _ _ _ _)
(define week-day-name (list-ref weekday (modulo (sub1 year-day) 5)))
(format "~a, day ~a of ~a" week-day-name season-day (list-ref-season seasons))])
" in the YOLD " (number->string (+ (date-year d) 1166))))
(displayln (discordian-date (current-date)))
;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;; passing these tests makes me consistent with D implementation
(module+ test
(require rackunit)
(define discordian/ymd (compose discordian-date ymd->date))
(check-equal? (discordian/ymd 2010 7 22) "Pungenday, day 57 of Confusion in the YOLD 3176")
(check-equal? (discordian/ymd 2012 2 28) "Prickle-Prickle, day 59 of Chaos in the YOLD 3178")
(check-equal? (discordian/ymd 2012 2 29) "St. Tib's Day, in the YOLD 3178");
(check-equal? (discordian/ymd 2012 3 1) "Setting Orange, day 60 of Chaos in the YOLD 3178")
(check-equal? (discordian/ymd 2010 1 5) "Mungday, in the YOLD 3176")
(check-equal? (discordian/ymd 2011 5 3) "Discoflux, in the YOLD 3177"))
;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~FIN |
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)
| #Ruby | Ruby | class Graph
Vertex = Struct.new(:name, :neighbours, :dist, :prev)
def initialize(graph)
@vertices = Hash.new{|h,k| h[k]=Vertex.new(k,[],Float::INFINITY)}
@edges = {}
graph.each do |(v1, v2, dist)|
@vertices[v1].neighbours << v2
@vertices[v2].neighbours << v1
@edges[[v1, v2]] = @edges[[v2, v1]] = dist
end
@dijkstra_source = nil
end
def dijkstra(source)
return if @dijkstra_source == source
q = @vertices.values
q.each do |v|
v.dist = Float::INFINITY
v.prev = nil
end
@vertices[source].dist = 0
until q.empty?
u = q.min_by {|vertex| vertex.dist}
break if u.dist == Float::INFINITY
q.delete(u)
u.neighbours.each do |v|
vv = @vertices[v]
if q.include?(vv)
alt = u.dist + @edges[[u.name, v]]
if alt < vv.dist
vv.dist = alt
vv.prev = u.name
end
end
end
end
@dijkstra_source = source
end
def shortest_path(source, target)
dijkstra(source)
path = []
u = target
while u
path.unshift(u)
u = @vertices[u].prev
end
return path, @vertices[target].dist
end
def to_s
"#<%s vertices=%p edges=%p>" % [self.class.name, @vertices.values, @edges]
end
end
g = Graph.new([ [: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],
])
start, stop = :a, :e
path, dist = g.shortest_path(start, stop)
puts "shortest path from #{start} to #{stop} has cost #{dist}:"
puts path.join(" -> ") |
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
| #Phix | Phix | with javascript_semantics
procedure digital_root(atom n, integer base=10)
integer root, persistence = 1
atom work = n
while true do
root = 0
while work!=0 do
root += remainder(work,base)
work = floor(work/base)
end while
if root<base then exit end if
work = root
persistence += 1
end while
printf(1,"%15d root: %d persistence: %d\n",{n,root,persistence})
end procedure
digital_root(627615)
digital_root(39390)
digital_root(588225)
digital_root(393900588225)
|
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?
| #Sidef | Sidef | func dinesman(problem) {
var lines = problem.split('.')
var names = lines.first.scan(/\b[A-Z]\w*/)
var re_names = Regex(names.join('|'))
# Later on, search for these keywords (the word "not" is handled separately).
var words = %w(first second third fourth fifth sixth seventh eighth ninth tenth
bottom top higher lower adjacent)
var re_keywords = Regex(words.join('|'))
# Build an array of lambda's
var predicates = lines.ft(1, lines.end-1).map{ |line|
var keywords = line.scan(re_keywords)
var (name1, name2) = line.scan(re_names)...
keywords.map{ |keyword|
var l = do {
given(keyword) {
when ("bottom") { ->(c) { c.first == name1 } }
when ("top") { ->(c) { c.last == name1 } }
when ("higher") { ->(c) { c.index(name1) > c.index(name2) } }
when ("lower") { ->(c) { c.index(name1) < c.index(name2) } }
when ("adjacent") { ->(c) { c.index(name1) - c.index(name2) -> abs == 1 } }
default { ->(c) { c[words.index(keyword)] == name1 } }
}
}
line ~~ /\bnot\b/ ? func(c) { l(c) -> not } : l; # handle "not"
}
}.flat
names.permutations { |*candidate|
predicates.all { |predicate| predicate(candidate) } && return candidate
}
} |
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
| #Lua | Lua | function dotprod(a, b)
local ret = 0
for i = 1, #a do
ret = ret + a[i] * b[i]
end
return ret
end
print(dotprod({1, 3, -5}, {4, -2, 1})) |
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
| #XPL0 | XPL0 | string 0;
char C, I, J, Last;
proc Squeeze(Char, S); \Eliminate specified repeated characters from string
char Char, S;
[I:= 0; J:= 0; Last:= -1;
loop [if S(I) # Last or Char # Last then
[C(J):= S(I);
if S(I) = 0 then quit;
J:= J+1;
];
Last:= S(I);
I:= I+1;
];
];
int String, K, Char;
[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 "];
Char:= [0, ^-, ^1, ^l, ^ , ^-, ^r];
C:= Reserve(79+1); \space for collapsed string
for K:= 0 to 4+2 do
[Squeeze(Char(K), String(if K>4 then 4 else K));
Text(0, "<<<"); Text(0, String(if K>4 then 4 else K)); Text(0, ">>> ");
IntOut(0, I); CrLf(0);
Text(0, "<<<"); Text(0, C); Text(0, ">>> "); IntOut(0, J); CrLf(0);
];
] |
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
| #zkl | zkl | fcn squeeze(c,str){ // Works with UTF-8
s,cc,sz,n := Data(Void,str), String(c,c), c.len(), 0; // byte buffer in case of LOTs of deletes
while(Void != (n=s.find(cc,n))){ str=s.del(n,sz) } // and searching is faster for big strings
s.text
} |
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
| #Draco | Draco | proc main() void:
byte police, sanitation, fire;
writeln("Police Sanitation Fire");
for police from 2 by 2 upto 7 do
for sanitation from 1 upto 7 do
for fire from 1 upto 7 do
if police /= sanitation
and police /= fire
and sanitation /= fire
and police + sanitation + fire = 12 then
writeln(police:6, " ", sanitation:10, " ", fire:4)
fi
od
od
od
corp |
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
| #Elixir | Elixir |
IO.puts("P - F - S")
for p <- [2,4,6],
f <- 1..7,
s <- 1..7,
p != f and p != s and f != s and p + f + s == 12 do
"#{p} - #{f} - #{s}"
end
|> Enum.each(&IO.puts/1)
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Oz | Oz | declare
class Delegator from BaseObject
attr
delegate:unit
meth set(DG)
{Object.is DG} = true %% assert: DG must be an object
delegate := DG
end
meth operation($)
if @delegate == unit then
{self default($)}
else
try
{@delegate thing($)}
catch error(object(lookup ...) ...) then
%% the delegate did not understand the message
{self default($)}
end
end
end
meth default($)
"default implementation"
end
end
class Delegate from BaseObject
meth thing($)
"delegate Implementation"
end
end
A = {New Delegator noop}
in
{System.showInfo {A operation($)}}
{A set({New BaseObject noop})}
{System.showInfo {A operation($)}}
{A set({New Delegate noop})}
{System.showInfo {A operation($)}} |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Pascal | Pascal | use strict;
package Delegator;
sub new {
bless {}
}
sub operation {
my ($self) = @_;
if (defined $self->{delegate} && $self->{delegate}->can('thing')) {
$self->{delegate}->thing;
} else {
'default implementation';
}
}
1;
package Delegate;
sub new {
bless {};
}
sub thing {
'delegate implementation'
}
1;
package main;
# No delegate
my $a = Delegator->new;
$a->operation eq 'default implementation' or die;
# With a delegate that does not implement "thing"
$a->{delegate} = 'A delegate may be any object';
$a->operation eq 'default implementation' or die;
# With delegate that implements "thing"
$a->{delegate} = Delegate->new;
$a->operation eq 'delegate implementation' or die;
|
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)
| #Phix | Phix | --
-- demo\rosetta\Determine_if_two_triangles_overlap.exw
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
constant triangles = {{{{0,0},{5,0},{0,5}},{{0,0},{5,0},{0,6}}},
{{{0,0},{0,5},{5,0}},{{0,0},{0,5},{5,0}}},
{{{0,0},{5,0},{0,5}},{{-10,0},{-5,0},{-1,6}}},
{{{0,0},{5,0},{2.5,5}},{{0,4},{2.5,-1},{5,4}}},
{{{0,0},{1,1},{0,2}},{{2,1},{3,0},{3,2}}},
{{{0,0},{1,1},{0,2}},{{2,1},{3,-2},{3,4}}},
{{{0,0},{1,0},{0,1}},{{1,0},{2,0},{1,1}}},
{{{0,0},{1,0},{0,1}},{{1,0},{2,0},{1,1}}}}
procedure draw_triangle(sequence t, integer cx,cy, c)
cdCanvasSetForeground(cddbuffer, c)
cdCanvasBegin(cddbuffer,CD_CLOSED_LINES)
for c=1 to 3 do
atom {x,y} = t[c]
cdCanvasVertex(cddbuffer, cx+x*10, cy+y*10)
end for
cdCanvasEnd(cddbuffer)
end procedure
function det2D(sequence triangle)
atom {{p1x,p1y},{p2x,p2y},{p3x,p3y}} := triangle
return p1x*(p2y-p3y) + p2x*(p3y-p1y) + p3x*(p1y-p2y)
end function
bool bReversed
function checkWinding(sequence triangle, bool allowReversed)
atom detTri := det2D(triangle);
if detTri<0.0 then
if allowReversed then
bReversed = true
triangle = extract(triangle,{1,3,2})
else
throw("triangle has wrong winding direction")
end if
end if
return triangle
end function
function overlap(sequence t1, t2, atom epsilon=0.0, bool allowReversed=false, onBoundary=true)
-- Trangles must be expressed anti-clockwise
bReversed = false
t1 = checkWinding(t1, allowReversed)
t2 = checkWinding(t2, allowReversed)
for t=1 to 2 do -- check t1 then t2
for edge=1 to 3 do -- check each edge
sequence p1 = t1[edge],
p2 = t1[mod(edge,3)+1]
-- Check all points of trangle 2 lay on the external side
-- of the edge E. If they do, the triangles do not collide.
integer onside = 0
for k=1 to 3 do
integer c = compare(det2D({p1,p2,t2[k]}),epsilon)
if onBoundary then
if not (c<0) then exit end if
else
if not (c<=0) then exit end if
end if
-- -- (the following incomprehensible one-liner is equivalent:)
-- if compare(det2D({p1,p2,t2[k]}),epsilon)>-onBoundary then exit end if
onside += 1
end for
if onside=3 then
return iff(onBoundary?"no overlap":"no overlap (no boundary)")
end if
end for
{t2,t1} = {t1,t2} -- flip and re-test
end for
return iff(bReversed?"overlap (reversed)":"overlap")
end function
function redraw_cb(Ihandle /*ih*/)
cdCanvasActivate(cddbuffer)
integer cy = 200, cx = 100
for i=1 to length(triangles) do
sequence {t1,t2} = triangles[i]
draw_triangle(t1,cx,cy,CD_RED)
integer s = (i<=2) -- (smudge tests[1..2] by one
-- pixel to show them better)
draw_triangle(t2,cx+s,cy+s,CD_BLUE)
cdCanvasSetForeground(cddbuffer, CD_BLACK)
cdCanvasText(cddbuffer,cx+10,cy-40,overlap(t1,t2,0,i=2,i!=8))
if i=4 then
cy = 100
cx = 100
else
cx += 300
end if
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_WHITE)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=1250x300")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,`RESIZE=NO, TITLE="Triangle overlap"`)
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
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.
| #Haskell | Haskell | import System.IO
import System.Directory
main = do
removeFile "output.txt"
removeDirectory "docs"
removeFile "/output.txt"
removeDirectory "/docs" |
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.
| #HicEst | HicEst | SYSTEM(DIR="docs") ! create docs in current directory (if not existent), make it current
OPEN (FILE="input.txt", "NEW") ! in current directory = docs
WRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst
SYSTEM(DIR="C:\docs") ! create C:\docs (if not existent), make it current
OPEN (FILE="input.txt", "NEW") ! in current directory = C:\docs
WRITE(FIle="input.txt", DELETE=1) |
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
| #Python | Python | from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations
def prod(lst):
return reduce(mul, lst, 1)
def perm(a):
n = len(a)
r = range(n)
s = permutations(r)
return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)
def det(a):
n = len(a)
r = range(n)
s = spermutations(n)
return fsum(sign * prod(a[i][sigma[i]] for i in r)
for sigma, sign in s)
if __name__ == '__main__':
from pprint import pprint as pp
for a in (
[
[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]],
):
print('')
pp(a)
print('Perm: %s Det: %s' % (perm(a), det(a))) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Jsish | Jsish | if (!isFinite(numerator/denominator)) puts("result is infinity or not a number"); |
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.
| #Julia | Julia | isdefinite(n::Number) = !isnan(n) && !isinf(n)
for n in (1, 1//1, 1.0, 1im, 0)
d = n / 0
println("Dividing $n by 0 ", isdefinite(d) ? "results in $d." : "yields an indefinite value ($d).")
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
| #Gambas | Gambas | Public Sub Form_Open()
Dim sAnswer, sString As String
sString = Trim(InputBox("Enter as string", "String or Numeric"))
If IsNumber(sString) Then sAnswer = "'" & sString & "' is numeric" Else sAnswer = "'" & sString & "' is a string"
Print sAnswer
End |
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
use utf8;
binmode(STDOUT, ':utf8');
use List::AllUtils qw(uniq);
use Unicode::UCD 'charinfo';
for my $str (
'',
'.',
'abcABC',
'XYZ ZYX',
'1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ',
'01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X',
'Δ👍👨👍Δ',
'ΔδΔ̂ΔΛ',
) {
my @S;
push @S, $1 while $str =~ /(\X)/g;
printf qq{\n"$str" (length: %d) has }, scalar @S;
if (@S != uniq @S ) {
say "duplicated characters:";
my %P;
push @{ $P{$S[$_]} }, 1+$_ for 0..$#S;
for my $k (sort keys %P) {
next unless @{$P{$k}} > 1;
printf "'%s' %s (0x%x) in positions: %s\n", $k, charinfo(ord $k)->{'name'}, ord($k), join ', ', @{$P{$k}};
}
} else {
say "no duplicated 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
| #Swift | Swift | let strings = [
"",
#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌"
]
let collapsedStrings = strings.map { $0.replacingOccurrences( of: #"(.)\1*"#, with: "$1", options: .regularExpression)}
for (original, collapsed) in zip(strings, collapsedStrings) {
print (String(format: "%03d «%@»\n%03d «%@»\n", original.count, original, collapsed.count, collapsed))
} |
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
| #Tcl | Tcl | set test {
{}
{"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln }
{..1111111111111111111111111111111111111111111111111111111111111117777888}
{I never give 'em hell, I just tell the truth, and they think it's hell. } ;# '
{ --- Harry S Truman }
{The better the 4-wheel drive, the further you'll be from help when ya get stuck!} ;# '
{headmistressship}
}
foreach {str} $test {
# Uses regexp lookbehind to detect repeated characters
set sub [regsub -all {(.)(\1+)} $str {\1}]
# Output
puts [format "Original (length %3d): %s" [string length $str] $str]
puts [format "Subbed (length %3d): %s" [string length $sub] $sub]
puts ----------------------
}
|
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
| #Prolog | Prolog |
:- system:set_prolog_flag(double_quotes,chars) .
main
:-
same_or_different("") ,
same_or_different(" ") ,
same_or_different("2") ,
same_or_different("333") ,
same_or_different(".55") ,
same_or_different("tttTTT") ,
same_or_different("4444 444k")
.
%! same_or_different(INPUTz0)
same_or_different(INPUTz0)
:-
system:format('input string is "~s" .~n',[INPUTz0]) ,
examine(INPUTz0)
.
%! examine(INPUTz0)
examine([])
:-
! ,
system:format('all the same characters .~n',[])
.
examine([COMPARE0|INPUTz0])
:-
examine(INPUTz0,COMPARE0,2,_INDEX_)
.
%! examine(INPUTz0,COMPARE0,INDEX0,INDEX)
examine([],_COMPARE0_,INDEX0,INDEX0)
:-
! ,
system:format('all the same characters .~n',[])
.
examine([COMPARE0|INPUTz0],COMPARE0,INDEX0,INDEX)
:-
! ,
INDEX1 is INDEX0 + 1 ,
examine(INPUTz0,COMPARE0,INDEX1,INDEX)
.
examine([DIFFERENT0|_INPUTz0_],COMPARE0,INDEX0,INDEX0)
:-
prolog:char_code(DIFFERENT0,DIFFERENT_CODE) ,
system:format('character "~s" (hex ~16r) different than "~s" at 1-based index ~10r .~n',[[DIFFERENT0],DIFFERENT_CODE,[COMPARE0],INDEX0])
.
|
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.
| #Ruby | Ruby | require 'mutex_m'
class Philosopher
def initialize(name, left_fork, right_fork)
@name = name
@left_fork = left_fork
@right_fork = right_fork
@meals = 0
end
def go
while @meals < 5
think
dine
end
puts "philosopher #@name is full!"
end
def think
puts "philosopher #@name is thinking..."
sleep(rand())
puts "philosopher #@name is hungry..."
end
def dine
fork1, fork2 = @left_fork, @right_fork
while true
pickup(fork1, :wait => true)
puts "philosopher #@name has fork #{fork1.fork_id}..."
if pickup(fork2, :wait => false)
break
end
puts "philosopher #@name cannot pickup second fork #{fork2.fork_id}..."
release(fork1)
fork1, fork2 = fork2, fork1
end
puts "philosopher #@name has the second fork #{fork2.fork_id}..."
puts "philosopher #@name eats..."
sleep(rand())
puts "philosopher #@name belches"
@meals += 1
release(@left_fork)
release(@right_fork)
end
def pickup(fork, opt)
puts "philosopher #@name attempts to pickup fork #{fork.fork_id}..."
opt[:wait] ? fork.mutex.mu_lock : fork.mutex.mu_try_lock
end
def release(fork)
puts "philosopher #@name releases fork #{fork.fork_id}..."
fork.mutex.unlock
end
end
n = 5
Fork = Struct.new(:fork_id, :mutex)
forks = Array.new(n) {|i| Fork.new(i, Object.new.extend(Mutex_m))}
philosophers = Array.new(n) do |i|
Thread.new(i, forks[i], forks[(i+1)%n]) do |id, f1, f2|
ph = Philosopher.new(id, f1, f2).go
end
end
philosophers.each {|thread| thread.join} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Raku | Raku | my @seasons = << Chaos Discord Confusion Bureaucracy 'The Aftermath' >>;
my @days = << Sweetmorn Boomtime Pungenday Prickle-Prickle 'Setting Orange' >>;
sub ordinal ( Int $n ) { $n ~ ( $n % 100 == 11|12|13
?? 'th' !! < th st nd rd th th th th th th >[$n % 10] ) }
sub ddate ( Str $ymd ) {
my $d = DateTime.new: "{$ymd}T00:00:00Z" or die;
my $yold = 'in the YOLD ' ~ $d.year + 1166;
my $day_of_year0 = $d.day-of-year - 1;
if $d.is-leap-year {
return "St. Tib's Day, $yold" if $d.month == 2 and $d.day == 29;
$day_of_year0-- if $day_of_year0 >= 60; # Compensate for St. Tib's Day
}
my $weekday = @days[ $day_of_year0 mod 5 ];
my $season = @seasons[ $day_of_year0 div 73 ];
my $season_day = ordinal( $day_of_year0 mod 73 + 1 );
return "$weekday, the $season_day day of $season $yold";
}
say "$_ is {.&ddate}" for < 2010-07-22 2012-02-28 2012-02-29 2012-03-01 >;
|
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #Rust | Rust | use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::usize;
struct Grid<T> {
nodes: Vec<Node<T>>,
}
struct Node<T> {
data: T,
edges: Vec<(usize,usize)>,
}
#[derive(Copy, Clone, Eq, PartialEq)]
struct State {
node: usize,
cost: usize,
}
// Manually implement Ord so we get a min-heap instead of a max-heap
impl Ord for State {
fn cmp(&self, other: &Self) -> Ordering {
other.cost.cmp(&self.cost)
}
}
impl PartialOrd for State {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
type WeightedEdge = (usize, usize, usize);
impl<T> Grid<T> {
fn new() -> Self {
Grid { nodes: Vec::new() }
}
fn add_node(&mut self, data: T) -> usize {
let node = Node {
edges: Vec::new(),
data: data,
};
self.nodes.push(node);
self.nodes.len() - 1
}
fn create_edges<'a, I>(&mut self, iterator: I) where I: IntoIterator<Item=&'a WeightedEdge> {
for &(start,end,weight) in iterator.into_iter() {
self.nodes[start].edges.push((end,weight));
self.nodes[end].edges.push((start,weight));
}
}
fn find_path(&self, start: usize, end: usize) -> Option<(Vec<usize>, usize)> {
let mut dist = vec![(usize::MAX, None); self.nodes.len()];
let mut heap = BinaryHeap::new();
dist[start] = (0, None);
heap.push(State {
node: start,
cost: 0,
});
while let Some(State { node, cost }) = heap.pop() {
if node == end {
let mut path = Vec::with_capacity(dist.len() / 2);
let mut current_dist = dist[end];
path.push(end);
while let Some(prev) = current_dist.1 {
path.push(prev);
current_dist = dist[prev];
}
path.reverse();
return Some((path, cost));
}
if cost > dist[node].0 {
continue;
}
for edge in &self.nodes[node].edges {
let next = State {
node: edge.0,
cost: cost + edge.1,
};
if next.cost < dist[next.node].0 {
dist[next.node] = (next.cost, Some(node));
heap.push(next);
}
}
}
None
}
}
fn main() {
let mut grid = Grid::new();
let (a,b,c,d,e,f) = (grid.add_node("a"), grid.add_node("b"),
grid.add_node("c"), grid.add_node("d"),
grid.add_node("e"), grid.add_node("f"));
grid.create_edges(&[
(a,b,7) ,(a,c,9) ,(a,f,14),
(b,c,10),(b,d,15),(c,d,11),
(c,f,2) ,(d,e,6) ,(e,f,9) ,
]);
let (path, cost) = grid.find_path(a,e).unwrap();
print!("{}", grid.nodes[path[0]].data);
for i in path.iter().skip(1) {
print!(" -> {}", grid.nodes[*i].data);
}
println!("\nCost: {}", cost);
} |
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
| #Picat | Picat | go =>
foreach(N in [627615,39390,588225,393900588225,
58142718981673030403681039458302204471300738980834668522257090844071443085937])
[Sum,Persistence] = digital_root(N),
printf("%w har addititive persistence %d and digital root of %d\n", N,Persistence,Sum)
end,
nl.
%
% (Reduced) digit sum (digital root) of a number
%
digital_root(N) = [Sum,Persistence], integer(N) =>
Sum = N,
Persistence = 0,
while(Sum > 9)
Sum := sum([I.to_integer() : I in Sum.to_string()]),
Persistence := Persistence + 1
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
| #PicoLisp | PicoLisp | (for N (627615 39390 588225 393900588225)
(for ((A . I) N T (sum format (chop I)))
(T (> 10 I)
(prinl N " has additive persistance " (dec A) " and digital root of " I ";") ) ) ) |
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?
| #Tailspin | Tailspin |
templates permutations
when <=1> do [1] !
otherwise
def n: $;
templates expand
def p: $;
1..$n -> \(def k: $;
[$p(1..$k-1)..., $n, $p($k..last)...] !\) !
end expand
$n - 1 -> permutations -> expand !
end permutations
templates index&{of:}
$ -> \[i](<=$of> $i! \) ...!
end index
def names: ['Baker', 'Cooper', 'Fletcher', 'Miller', 'Smith'];
5 -> permutations -> $names($)
-> \(<?($ -> index&{of: 'Baker'} <~=5>)> $! \)
-> \(<?($ -> index&{of: 'Cooper'} <~=1>)> $! \)
-> \(<?($ -> index&{of: 'Fletcher'} <~=1|=5>)> $! \)
-> \(<?($ -> index&{of: 'Cooper'} <..($ -> index&{of:'Miller'})>)> $! \)
-> \(<?(($ -> index&{of: 'Smith'}) - ($ -> index&{of:'Fletcher'}) <~=1|=-1>)> $! \)
-> \(<?(($ -> index&{of: 'Cooper'}) - ($ -> index&{of:'Fletcher'}) <~=1|=-1>)> $! \)
-> \[i]('$i;:$;$#10;' ! \)
-> $(last..first:-1)
-> '$...;$#10;' -> !OUT::write
|
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
| #M2000_Interpreter | M2000 Interpreter |
Module dot_product {
A=(1,3,-5)
B=(4,-2,-1)
Function Dot(a, b) {
if len(a)<>len(b) Then Error "not same length"
if len(a)=0 then Error "empty vectors"
Let a1=each(a), b1=each(b), sum=0
While a1, b1 {sum+=array(a1)*array(b1)}
=sum
}
Print Dot(A, B)
Print Dot((1,3,-5), (4,-2,-1))
}
Module 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
| #Maple | Maple | <1,2,3> . <4,5,6> |
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
| #Excel | Excel | departmentNumbers
=validRows(
LAMBDA(ab,
LET(
x, INDEX(ab, 0, 1),
y, INDEX(ab, 0, 2),
z, 12 - (x + y),
IF(y <> z,
IF(1 <= z,
IF(7 >= z,
CHOOSE({1, 2, 3}, x, y, z),
NA()
),
NA()
),
NA()
)
)
)(
cartesianProduct({2;4;6})(
SEQUENCE(7, 1, 1, 1)
)
)
) |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Perl | Perl | use strict;
package Delegator;
sub new {
bless {}
}
sub operation {
my ($self) = @_;
if (defined $self->{delegate} && $self->{delegate}->can('thing')) {
$self->{delegate}->thing;
} else {
'default implementation';
}
}
1;
package Delegate;
sub new {
bless {};
}
sub thing {
'delegate implementation'
}
1;
package main;
# No delegate
my $a = Delegator->new;
$a->operation eq 'default implementation' or die;
# With a delegate that does not implement "thing"
$a->{delegate} = 'A delegate may be any object';
$a->operation eq 'default implementation' or die;
# With delegate that implements "thing"
$a->{delegate} = Delegate->new;
$a->operation eq 'delegate implementation' or die;
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Phix | Phix | enum OTHER, OPERATION
function operation(object o)
integer rid = o[OPERATION]
if rid!=NULL then
return call_func(rid,{})
end if
return "no implementation"
end function
function xthing()
return "default implementation"
end function
function newX()
return {1,routine_id("xthing"),2}
end function
function newY()
object res = newX()
res[OTHER] = "something else"
-- remove delegate:
res[OPERATION] = NULL
return res
end function
function zthing()
return "delegate implementation"
end function
function newZ()
object res = newX()
-- replace delegate:
res[OPERATION] = routine_id("zthing")
return res
end function
object x = newX(),
y = newY(),
z = newZ()
?operation(x)
?operation(y)
?operation(z) |
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)
| #Python | Python | from __future__ import print_function
import numpy as np
def CheckTriWinding(tri, allowReversed):
trisq = np.ones((3,3))
trisq[:,0:2] = np.array(tri)
detTri = np.linalg.det(trisq)
if detTri < 0.0:
if allowReversed:
a = trisq[2,:].copy()
trisq[2,:] = trisq[1,:]
trisq[1,:] = a
else: raise ValueError("triangle has wrong winding direction")
return trisq
def TriTri2D(t1, t2, eps = 0.0, allowReversed = False, onBoundary = True):
#Trangles must be expressed anti-clockwise
t1s = CheckTriWinding(t1, allowReversed)
t2s = CheckTriWinding(t2, allowReversed)
if onBoundary:
#Points on the boundary are considered as colliding
chkEdge = lambda x: np.linalg.det(x) < eps
else:
#Points on the boundary are not considered as colliding
chkEdge = lambda x: np.linalg.det(x) <= eps
#For edge E of trangle 1,
for i in range(3):
edge = np.roll(t1s, i, axis=0)[:2,:]
#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(np.vstack((edge, t2s[0]))) and
chkEdge(np.vstack((edge, t2s[1]))) and
chkEdge(np.vstack((edge, t2s[2])))):
return False
#For edge E of trangle 2,
for i in range(3):
edge = np.roll(t2s, i, axis=0)[:2,:]
#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(np.vstack((edge, t1s[0]))) and
chkEdge(np.vstack((edge, t1s[1]))) and
chkEdge(np.vstack((edge, t1s[2])))):
return False
#The triangles collide
return True
if __name__=="__main__":
t1 = [[0,0],[5,0],[0,5]]
t2 = [[0,0],[5,0],[0,6]]
print (TriTri2D(t1, t2), True)
t1 = [[0,0],[0,5],[5,0]]
t2 = [[0,0],[0,6],[5,0]]
print (TriTri2D(t1, t2, allowReversed = True), True)
t1 = [[0,0],[5,0],[0,5]]
t2 = [[-10,0],[-5,0],[-1,6]]
print (TriTri2D(t1, t2), False)
t1 = [[0,0],[5,0],[2.5,5]]
t2 = [[0,4],[2.5,-1],[5,4]]
print (TriTri2D(t1, t2), True)
t1 = [[0,0],[1,1],[0,2]]
t2 = [[2,1],[3,0],[3,2]]
print (TriTri2D(t1, t2), False)
t1 = [[0,0],[1,1],[0,2]]
t2 = [[2,1],[3,-2],[3,4]]
print (TriTri2D(t1, t2), False)
#Barely touching
t1 = [[0,0],[1,0],[0,1]]
t2 = [[1,0],[2,0],[1,1]]
print (TriTri2D(t1, t2, onBoundary = True), True)
#Barely touching
t1 = [[0,0],[1,0],[0,1]]
t2 = [[1,0],[2,0],[1,1]]
print (TriTri2D(t1, t2, onBoundary = 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.
| #Icon_and_Unicon | Icon and Unicon | every dir := !["./","/"] do {
remove(f := dir || "input.txt") |stop("failure for file remove ",f)
rmdir(f := dir || "docs") |stop("failure for directory remove ",f)
}
|
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.
| #Io | Io | Directory fileNamed("input.txt") remove
Directory directoryNamed("docs") remove
RootDir := Directory clone setPath("/")
RootDir fileNamed("input.txt") remove
RootDir directoryNamed("docs") remove |
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
| #R | R | library(combinat)
perm <- function(A)
{
stopifnot(is.matrix(A))
n <- nrow(A)
if(n != ncol(A)) stop("Matrix is not square.")
if(n < 1) stop("Matrix has a dimension of size 0.")
sum(sapply(combinat::permn(n), function(sigma) prod(sapply(1:n, function(i) A[i, sigma[i]]))))
}
#We copy our test cases from the Python example.
testData <- list("Test 1" = rbind(c(1, 2), c(3, 4)),
"Test 2" = rbind(c(1, 2, 3, 4), c(4, 5, 6, 7), c(7, 8, 9, 10), c(10, 11, 12, 13)),
"Test 3" = rbind(c(0, 1, 2, 3, 4), c(5, 6, 7, 8, 9), c(10, 11, 12, 13, 14),
c(15, 16, 17, 18, 19), c(20, 21, 22, 23, 24)))
print(sapply(testData, function(x) list(Determinant = det(x), Permanent = perm(x)))) |
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.
| #Kotlin | Kotlin | // version 1.1
fun divideByZero(x: Int, y:Int): Boolean =
try {
x / y
false
} catch(e: ArithmeticException) {
true
}
fun main(args: Array<String>) {
val x = 1
val y = 0
if (divideByZero(x, y)) {
println("Attempted to divide by zero")
} else {
@Suppress("DIVISION_BY_ZERO")
println("$x / $y = ${x / y}")
}
} |
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.
| #Lambdatalk | Lambdatalk |
{def DivByZero?
{lambda {:w}
{W.equal? :w Infinity}}}
{DivByZero? {/ 3 2}}
-> false
{DivByZero? {/ 3 0}}
-> true
|
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
| #Go | Go | package main
import (
"fmt"
"strconv"
)
func isNumeric(s string) bool {
_, err := strconv.ParseFloat(s, 64)
return err == nil
}
func main() {
fmt.Println("Are these strings numeric?")
strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"}
for _, s := range strings {
fmt.Printf(" %4s -> %t\n", s, isNumeric(s))
}
} |
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
| #Phix | Phix | procedure all_uniq(sequence s)
string chars = ""
sequence posns = {},
multi = {}
integer lm = 0
for i=1 to length(s) do
integer si = s[i],
k = find(si,chars)
if k=0 then
chars &= si
posns &= {{i}}
else
posns[k] &= i
if length(posns[k])=2 then
multi &= k
lm += 1
end if
end if
end for
string msg = sprintf("\"%s\" (length %d): ",{s,length(s)}),
nod = ordinal(lm,true),
ess = "s"[1..lm>1],
res = iff(lm=0?"all characters are unique"
:sprintf("contains %s duplicate%s:",{nod,ess}))
printf(1,"%s %s\n",{msg,res})
res = repeat(' ',length(msg))
for i=1 to length(multi) do
integer mi = multi[i],
ci = chars[mi]
printf(1,"%s '%c'(#%02x) at %V\n",{res,ci,ci,posns[mi]})
end for
printf(1,"\n")
end procedure
constant tests = {"",".","abcABC","XYZ ZYX","1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
" ","2","333","55","tttTTT","tTTTtt","4444 444k"}
papply(tests,all_uniq)
|
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Collapse(s As String) As String
If String.IsNullOrEmpty(s) Then
Return ""
End If
Return s(0) + New String(Enumerable.Range(1, s.Length - 1).Where(Function(i) s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray)
End Function
Sub Main()
Dim input() = {
"",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
ControlChars.Quote + "If I were two-faced, would I be wearing this one?" + ControlChars.Quote + " --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman "
}
For Each s In input
Console.WriteLine($"old: {s.Length} «««{s}»»»")
Dim c = Collapse(s)
Console.WriteLine($"new: {c.Length} «««{c}»»»")
Next
End Sub
End Module |
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
| #VBA | VBA | Function Collapse(strIn As String) As String
Dim i As Long, strOut As String
If Len(strIn) > 0 Then
strOut = Mid$(strIn, 1, 1)
For i = 2 To Len(strIn)
If Mid$(strIn, i, 1) <> Mid$(strIn, i - 1, 1) Then
strOut = strOut & Mid$(strIn, i, 1)
End If
Next i
End If
Collapse = strOut
End Function |
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
| #Python | Python | '''Determine if a string has all the same characters'''
from itertools import groupby
# firstDifferingCharLR :: String -> Either String Dict
def firstDifferingCharLR(s):
'''Either a message reporting that no character changes were
seen, or a dictionary with details of the first character
(if any) that differs from that at the head of the string.
'''
def details(xs):
c = xs[1][0]
return {
'char': repr(c),
'hex': hex(ord(c)),
'index': s.index(c),
'total': len(s)
}
xs = list(groupby(s))
return Right(details(xs)) if 1 < len(xs) else (
Left('Total length ' + str(len(s)) + ' - No character changes.')
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test of 7 strings'''
print(fTable('First, if any, points of difference:\n')(repr)(
either(identity)(
lambda dct: dct['char'] + ' (' + dct['hex'] +
') at character ' + str(1 + dct['index']) +
' of ' + str(dct['total']) + '.'
)
)(firstDifferingCharLR)([
'',
' ',
'2',
'333',
'.55',
'tttTTT',
'4444 444'
]))
# GENERIC -------------------------------------------------
# either :: (a -> c) -> (b -> c) -> Either a b -> c
def either(fl):
'''The application of fl to e if e is a Left value,
or the application of fr to e if e is a Right value.
'''
return lambda fr: lambda e: fl(e['Left']) if (
None is e['Right']
) else fr(e['Right'])
# identity :: a -> a
def identity(x):
'''The identity function.'''
return x
# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
'''Heading -> x display function -> fx display function ->
f -> xs -> tabular string.
'''
def go(xShow, fxShow, f, xs):
ys = [xShow(x) for x in xs]
w = max(map(len, ys))
return s + '\n' + '\n'.join(map(
lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
xs, ys
))
return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
xShow, fxShow, f, xs
)
# Left :: a -> Either a b
def Left(x):
'''Constructor for an empty Either (option type) value
with an associated string.
'''
return {'type': 'Either', 'Right': None, 'Left': x}
# Right :: b -> Either a b
def Right(x):
'''Constructor for a populated Either (option type) value'''
return {'type': 'Either', 'Left': None, 'Right': x}
# MAIN ---
if __name__ == '__main__':
main() |
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.
| #Rust | Rust | use std::thread;
use std::sync::{Mutex, Arc};
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left: left,
right: right,
}
}
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} is eating.", self.name);
thread::sleep_ms(1000);
println!("{} is done eating.", self.name);
}
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn main() {
let table = Arc::new(Table { forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
]});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Friedrich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4),
];
let handles: Vec<_> = philosophers.into_iter().map(|p| {
let table = table.clone();
thread::spawn(move || {
p.eat(&table);
})
}).collect();
for h in handles {
h.join().unwrap();
}
} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #REXX | REXX | /*REXX program converts a mm/dd/yyyy Gregorian date ───► a Discordian date. */
@day.1= 'Sweetness' /*define the 1st day─of─Discordian─week*/
@day.2= 'Boomtime' /* " " 2nd " " " " */
@day.3= 'Pungenday' /* " " 3rd " " " " */
@day.4= 'Prickle-Prickle' /* " " 4th " " " " */
@day.5= 'Setting Orange' /* " " 5th " " " " */
@seas.0= "St. Tib's day," /*define the leap─day of Discordian yr.*/
@seas.1= 'Chaos' /* " 1st season─of─Discordian─year.*/
@seas.2= 'Discord' /* " 2nd " " " " */
@seas.3= 'Confusion' /* " 3rd " " " " */
@seas.4= 'Bureaucracy' /* " 4th " " " " */
@seas.5= 'The Aftermath' /* " 5th " " " " */
parse arg gM '/' gD "/" gY . /*obtain the specified Gregorian date. */
if gM=='' | gM=="," | gM=='*' then parse value date("U") with gM '/' gD "/" gY .
gY=left( right( date(), 4), 4 - length(Gy) )gY /*adjust for two─digit year or no year.*/
/* [↓] day─of─year, leapyear adjust. */
doy= date('d', gY || right(gM, 2, 0)right(gD ,2, 0), "s") - (leapyear(gY) & gM>2)
dW= doy//5; if dW==0 then dW= 5 /*compute the Discordian weekday. */
dS= (doy-1) % 73 + 1 /* " " " season. */
dD= doy//73; if dD==0 then dD= 73 /* " " " day─of─month. */
if leapyear(gY) & gM==2 & gD==29 then ds= 0 /*is this St. Tib's day (leapday) ? */
if ds==0 then dD= /*adjust for the Discordian leap day. */
say space(@day.dW',' @seas.dS dD"," gY + 1166) /*display Discordian date to terminal. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
leapyear: procedure; parse arg y /*obtain a four─digit Gregorian year. */
if y//4 \== 0 then return 0 /*Not ÷ by 4? Then not a leapyear. */
return y//100 \== 0 | y//400 == 0 /*apply the 100 and 400 year rules.*/ |
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)
| #SAS | SAS | /* create SAS data set */
data Edges;
input Start $ End $ Cost;
datalines;
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
;
/* call OPTMODEL procedure in SAS/OR */
proc optmodel;
/* declare sets and parameters, and read input data */
set <str,str> LINKS;
num cost {LINKS};
read data Edges into LINKS=[start end] cost;
set NODES = union {<i,j> in LINKS} {i,j};
set SOURCES = {'a'};
set SINKS = {'e'};
/* <source,sink,order,from,to> */
set <str,str,num,str,str> PATHS;
/* call network solver */
solve with network /
shortpath=(source=SOURCES sink=SINKS) links=(weight=cost) out=(sppaths=PATHS);
/* write shortest path to SAS data set */
create data path from [source sink order from to]=PATHS cost[from,to];
quit;
/* print shortest path */
proc print data=path;
run; |
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
| #PL.2FI | PL/I | digrt: Proc Options(main);
/* REXX ***************************************************************
* Test digroot
**********************************************************************/
Call digrtst('7');
Call digrtst('627615');
Call digrtst('39390');
Call digrtst('588225');
Call digrtst('393900588225');
digrtst: Proc(n);
Dcl n Char(100) Var;
Dcl dr Pic'9';
Dcl p Dec Fixed(5);
Call digroot(n,dr,p);
Put Edit(n,dr,p)(skip,a,col(20),f(1),f(3));
End;
digroot: Proc(n,dr,p);
/**********************************************************************
* Compute the digital root and persistence of the given decimal number
* 27.07.2012 Walter Pachl (derived from REXX)
**********************************************************************/
Dcl n Char(100) Var;
Dcl dr Pic'9';
Dcl p Dec Fixed(5);
Dcl s Pic'(14)Z9';
Dcl v Char(100) Var;
p=0;
v=strip(n); /* copy the number */
If length(v)=1 Then
dr=v;
Else Do;
Do While(length(v)>1); /* more than one digit in v */
s=0; /* initialize sum */
p+=1; /* increment persistence */
Do i=1 To length(v); /* loop over all digits */
dig=substr(v,i,1); /* pick a digit */
s=s+dig; /* add to the new sum */
End;
/*Put Skip Data(v,p,s);*/
v=strip(s); /* the 'new' number */
End;
dr=Decimal(s,1,0);
End;
Return;
End;
strip: Proc(x) Returns(Char(100) Var);
Dcl x Char(*);
Dcl res Char(100) Var Init('');
Do i=1 To length(x);
If substr(x,i,1)>' ' Then
res=res||substr(x,i,1);
End;
Return(res);
End;
End; |
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?
| #Tcl | Tcl | package require Tcl 8.5
package require struct::list
proc dinesmanSolve {floors people constraints} {
# Search for a possible assignment that satisfies the constraints
struct::list foreachperm p $floors {
lassign $p {*}$people
set found 1
foreach c $constraints {
if {![expr $c]} {
set found 0
break
}
}
if {$found} break
}
# Found something, or exhausted possibilities
if {!$found} {
error "no solution possible"
}
# Generate in "nice" order
foreach f $floors {
foreach person $people {
if {[set $person] == $f} {
lappend result $f $person
break
}
}
}
return $result
} |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | {1,3,-5}.{4,-2,-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
| #MATLAB | MATLAB | A = [1 3 -5]
B = [4 -2 -1]
C = dot(A,B) |
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
| #F.23 | F# |
// A function to generate department numbers. Nigel Galloway: May 2nd., 2018
type dNum = {Police:int; Fire:int; Sanitation:int}
let fN n=n.Police%2=0&&n.Police+n.Fire+n.Sanitation=12&&n.Police<>n.Fire&&n.Police<>n.Sanitation&&n.Fire<>n.Sanitation
List.init (7*7*7) (fun n->{Police=n%7+1;Fire=(n/7)%7+1;Sanitation=(n/49)+1})|>List.filter fN|>List.iter(printfn "%A")
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #PHP | PHP | class Delegator {
function __construct() {
$this->delegate = NULL ;
}
function operation() {
if(method_exists($this->delegate, "thing"))
return $this->delegate->thing() ;
return 'default implementation' ;
}
}
class Delegate {
function thing() {
return 'Delegate Implementation' ;
}
}
$a = new Delegator() ;
print "{$a->operation()}\n" ;
$a->delegate = 'A delegate may be any object' ;
print "{$a->operation()}\n" ;
$a->delegate = new Delegate() ;
print "{$a->operation()}\n" ; |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #PicoLisp | PicoLisp | (class +Delegator)
# delegate
(dm operation> ()
(if (: delegate)
(thing> @)
"default implementation" ) )
(class +Delegate)
# thing
(dm T (Msg)
(=: thing Msg) )
(dm thing> ()
(: thing) )
(let A (new '(+Delegator))
# Without a delegate
(println (operation> A))
# With delegate that does not implement 'thing>'
(put A 'delegate (new '(+Delegate)))
(println (operation> A))
# With delegate that implements 'thing>'
(put A 'delegate (new '(+Delegate) "delegate implementation"))
(println (operation> A)) ) |
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)
| #QB64 | QB64 |
DATA 0,0,5,0,0,5,0,0,5,0,0,6
DATA 0,0,0,5,5,0,0,0,0,5,5,0
DATA 0,0,5,0,0,5,-10,0,-5,0,-1,6
DATA 0,0,5,0,2.5,5,0,4,2.5,-1,5,4
DATA 0,0,1,1,0,2,2,1,3,0,3,2
DATA 0,0,1,1,0,2,2,1,3,-2,3,4
TYPE point
x AS INTEGER
y AS INTEGER
END TYPE
DIM coord(12, 3) AS point
workscreen = _NEWIMAGE(800, 800, 32)
backscreen = _NEWIMAGE(800, 800, 32)
SCREEN workscreen
FOR i = 1 TO 12 '12 triangles
FOR j = 1 TO 3 'with 3 coordinates for each
READ coord(i, j).x 'X coord
READ coord(i, j).y 'Y coord
FixCoord coord(i, j)
NEXT
NEXT
_DELAY .5
_SCREENMOVE _MIDDLE
FOR i = 1 TO 12
_DEST workscreen
CLS
_DEST backscreen
_DONTBLEND
CLS , 0
PSET (coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 255, 255, 128)
FOR j = 2 TO 3
LINE -(coord(i, j).x, coord(i, j).y), _RGBA32(255, 255, 255, 128)
NEXT
LINE -(coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 255, 255, 128)
xinside = (coord(i, 1).x + coord(i, 2).x + coord(i, 3).x) / 3
yinside = (coord(i, 1).y + coord(i, 2).y + coord(i, 3).y) / 3
PAINT (xinside, yinside), _RGBA32(255, 255, 255, 128)
_BLEND
_PUTIMAGE , backscreen, 0
CLS , 0
_DONTBLEND
i = i + 1
PSET (coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 0, 0, 128)
FOR j = 2 TO 3
LINE -(coord(i, j).x, coord(i, j).y), _RGBA32(255, 0, 0, 128)
NEXT
LINE -(coord(i, 1).x, coord(i, 1).y), _RGBA32(255, 0, 0, 128)
xinside = (coord(i, 1).x + coord(i, 2).x + coord(i, 3).x) / 3
yinside = (coord(i, 1).y + coord(i, 2).y + coord(i, 3).y) / 3
PAINT (xinside, yinside), _RGBA32(255, 0, 0, 128)
_BLEND
_PUTIMAGE , backscreen, 0
_DEST workscreen
_SOURCE workscreen
overlap = 0
FOR x = 0 TO 999
FOR y = 0 TO 999
IF POINT(x, y) = _RGBA32(190, 63, 63, 255) THEN overlap = -1: GOTO overlap
NEXT
NEXT
overlap:
IF overlap THEN PRINT "OVERLAP" ELSE PRINT "NO OVERLAP"
SLEEP
NEXT
SYSTEM
SUB FixCoord (p AS point)
p.x = (10 + p.x) * 30 + 100
p.y = (10 + p.y) * 30
END SUB
|
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.
| #J | J | load 'files'
ferase 'input.txt'
ferase '\input.txt'
ferase 'docs'
ferase '\docs'
NB. Or all at once...
ferase 'input.txt';'/input.txt';'docs';'/docs' |
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.
| #Java | Java | import java.io.File;
public class FileDeleteTest {
public static boolean deleteFile(String filename) {
boolean exists = new File(filename).delete();
return exists;
}
public static void test(String type, String filename) {
System.out.println("The following " + type + " called " + filename +
(deleteFile(filename) ? " was deleted." : " could not be deleted.")
);
}
public static void main(String args[]) {
test("file", "input.txt");
test("file", File.seperator + "input.txt");
test("directory", "docs");
test("directory", File.seperator + "docs" + File.seperator);
}
} |
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
| #Racket | Racket |
#lang racket
(require math)
(define determinant matrix-determinant)
(define (permanent M)
(define n (matrix-num-rows M))
(for/sum ([σ (in-permutations (range n))])
(for/product ([i n] [σi σ])
(matrix-ref M i σi))))
|
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
| #Raku | Raku | sub insert ($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. @xs) }
sub order ($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }
multi σ_permutations ([]) { [] => 1 }
multi σ_permutations ([$x, *@xs]) {
σ_permutations(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(1,-1) xx *
}
sub m_arith ( @a, $op ) {
note "Not a square matrix" and return
if [||] map { @a.elems cmp @a[$_].elems }, ^@a;
sum σ_permutations([^@a]).race.map: {
my $permutation = .key;
my $term = $op eq 'perm' ?? 1 !! .value;
for $permutation.kv -> $i, $j { $term *= @a[$i][$j] };
$term
}
}
######### helper subs #########
sub hilbert-matrix (\h) {[(1..h).map(-> \n {[(n..^n+h).map: {(1/$_).FatRat}]})]}
sub rat-or-int ($num) {
return $num unless $num ~~ Rat|FatRat;
return $num.narrow if $num.narrow.WHAT ~~ Int;
$num.nude.join: '/';
}
sub say-it ($message, @array) {
my $max;
@array.map: {$max max= max $_».&rat-or-int.comb(/\S+/)».chars};
say "\n$message";
$_».&rat-or-int.fmt(" %{$max}s").put for @array;
}
########### Testing ###########
my @tests = (
[
[ 1, 2 ],
[ 3, 4 ]
],
[
[ 1, 2, 3, 4 ],
[ 4, 5, 6, 7 ],
[ 7, 8, 9, 10 ],
[ 10, 11, 12, 13 ]
],
hilbert-matrix 7
);
for @tests -> @matrix {
say-it 'Matrix:', @matrix;
say "Determinant:\t", rat-or-int @matrix.&m_arith: <det>;
say "Permanent: \t", rat-or-int @matrix.&m_arith: <perm>;
say '-' x 40;
} |
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.
| #LabVIEW | LabVIEW | define dividehandler(a,b) => {
(
#a->isNotA(::integer) && #a->isNotA(::decimal) ||
#b->isNotA(::integer) && #b->isNotA(::decimal)
) ? return 'Error: Please supply all params as integers or decimals'
protect => {
handle_error => { return 'Error: Divide by zero' }
local(x = #a / #b)
return #x
}
}
dividehandler(1,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.
| #Lasso | Lasso | define dividehandler(a,b) => {
(
#a->isNotA(::integer) && #a->isNotA(::decimal) ||
#b->isNotA(::integer) && #b->isNotA(::decimal)
) ? return 'Error: Please supply all params as integers or decimals'
protect => {
handle_error => { return 'Error: Divide by zero' }
local(x = #a / #b)
return #x
}
}
dividehandler(1,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.
| #Lingo | Lingo | on div (a, b)
-- for simplicity type check of vars omitted
res = value("float(a)/b")
if voidP(res) then
_player.alert("Division by zero!")
else
return res
end if
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
| #Groovy | Groovy | def isNumeric = {
def formatter = java.text.NumberFormat.instance
def pos = [0] as java.text.ParsePosition
formatter.parse(it, pos)
// if parse position index has moved to end of string
// them the whole string was numeric
pos.index == it.size()
} |
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
| #Haskell | Haskell | isInteger s = case reads s :: [(Integer, String)] of
[(_, "")] -> True
_ -> False
isDouble s = case reads s :: [(Double, String)] of
[(_, "")] -> True
_ -> False
isNumeric :: String -> Bool
isNumeric s = isInteger s || isDouble s |
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
| #PicoLisp | PicoLisp | (de burn (Lst)
(let P 0
(by
'((A)
(set A (inc 'P))
(put A 'P (char A)) )
group
Lst ) ) )
(de first (Lst)
(mini
'((L)
(nand
(cdr L)
(apply min (mapcar val L)) ) )
Lst ) )
(de uniq? (Str)
(let M (first (burn (chop Str)))
(ifn M
(prinl Str " (length " (length Str) "): all characters are unique")
(prin
Str " (length " (length Str) "): first duplicate character "
(car M)
" at positions " )
(println (mapcar val M)) ) ) )
(uniq?)
(uniq? ".")
(uniq? "abcABC")
(uniq? "XYZ ZYX")
(uniq? "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ") |
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
| #Prolog | Prolog | report_duplicates(S) :-
duplicates(S, Dups),
format('For value "~w":~n', S),
report(Dups),
nl.
report(Dups) :-
maplist(only_one_position, Dups),
format(' All characters are unique~n').
report(Dups) :-
exclude(only_one_position, Dups, [c(Char,Positions)|_]),
reverse(Positions, PosInOrder),
atomic_list_concat(PosInOrder, ', ', PosAsList),
format(' The character ~w is non unique at ~p~n', [Char, PosAsList]).
only_one_position(c(_,[_])).
duplicates(S, Count) :-
atom_chars(S, Chars),
char_count(Chars, 0, [], Count).
char_count([], _, C, C).
char_count([C|T], Index, Counted, Result) :-
select(c(C,Positions), Counted, MoreCounted),
succ(Index, Index1),
char_count(T, Index1, [c(C,[Index|Positions])|MoreCounted], Result).
char_count([C|T], Index, Counted, Result) :-
\+ member(c(C,_), Counted),
succ(Index, Index1),
char_count(T, Index1, [c(C,[Index])|Counted], Result).
test :- report_duplicates('').
test :- report_duplicates('.').
test :- report_duplicates('abcABC').
test :- report_duplicates('XYZ ZYX').
test :- report_duplicates('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'). |
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
| #Vlang | Vlang | // Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
fn collapse(s string) (string, int, int) {
mut r := s.runes()
le, mut del := r.len, 0
for i := le - 2; i >= 0; i-- {
if r[i] == r[i+1] {
r.delete(i)
del++
}
}
if del == 0 {
return s, le, le
}
r = r[..le-del]
return r.string(), le, r.len
}
fn main() {
strings:= [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
]
for s in strings {
cs, olen, clen := collapse(s)
println("original : length = ${olen:2}, string = «««$s»»»")
println("collapsed: length = ${clen:2}, string = «««$cs»»»\n")
}
} |
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
| #Wren | Wren | import "/fmt" for Fmt
// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
var collapse = Fn.new { |s|
var c = s.codePoints.toList
var le = c.count
if (le < 2) return [s, le, le]
for (i in le-2..0) {
if (c[i] == c[i+1]) c.removeAt(i)
}
var cc = c.reduce("") { |acc, cp| acc + String.fromCodePoint(cp) }
return [cc, le, cc.count]
}
var strings = [
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌"
]
for (s in strings) {
var r = collapse.call(s)
System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
System.print("collapsed: length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
} |
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
| #Quackery | Quackery |
[ 0 swap
dup size 0 = iff
drop done
behead swap witheach
[ over != if
[ drop i^ 1+
swap conclude ] ]
drop ] is allsame ( [ --> n )
( 0 indicates all items are the same,
otherwise n is first different item )
[ say ' String: "' dup echo$
say '" length ' dup size echo
dup allsame dup 0 = iff
[ say ', all characters are the same.'
2drop ]
else
[ say ', first difference is item '
dup echo
say ', char "'
peek dup emit
say '", hex: '
16 base put echo base release
say '.' ]
cr ] is task ( $ --> )
$ "" task
$ " " task
$ "2" task
$ ".55" task
$ "tttTTT" task
$ "4444 444k" task |
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
| #R | R | isAllSame <- function(string)
{
strLength <- nchar(string)
if(length(strLength) > 1)
{
#R has a distinction between the length of a string and that of a character vector. It is a common source
#of problems when coming from another language. We will try to avoid the topic here.
#For our purposes, let us only say that there is a good reason why we have made
#isAllSame(c("foo", "bar") immediately throw an error.
stop("This task is intended for character vectors with lengths of at most 1.")
}
else if(length(strLength) == 0)
{
cat("Examining a character vector of length 0.\n")
TRUE
}
else if(strLength == 0)
{
cat("Examining a character vector of length 1, containing an empty string.\n")
TRUE
}
else
{
cat("Examining the string", paste0(sQuote(string), ","),
"which is of length", paste0(strLength, ":"), "\n")
#strsplit outputs a list. Its first element is the vector of characters that we desire.
characters <- strsplit(string, "")[[1]]
#Our use of match is using R's vector recycling rules. Every element is being checked
#against the first.
differentElementIndex <- match(FALSE, characters[1] == characters, nomatch = 0)
if(differentElementIndex == 0)
{
cat("It has no duplicates.\n")
TRUE
}
else
{
cat("It has duplicates. ")
firstDifferentCharacter <- characters[differentElementIndex]
cat(sQuote(firstDifferentCharacter), "is the first different character. It has hex value",
sprintf("0x%X", as.integer(charToRaw(firstDifferentCharacter))),
"and is at index", paste0(differentElementIndex, "."), "\n")
FALSE
}
}
}
#Tests:
cat("Test: A string of length 0 (an empty string):\n")
cat("Test 1 of 2: An empty character vector:\n")
print(isAllSame(character(0)))
cat("Test 2 of 2: A character vector containing the empty string:\n")
print(isAllSame(""))
cat("Test: A string of length 3 which contains three blanks:\n")
print(isAllSame(" "))
cat("Test: A string of length 1 which contains 2:\n")
print(isAllSame("2"))
cat("Test: A string of length 3 which contains 333:\n")
print(isAllSame("333"))
cat("Test: A string of length 3 which contains .55:\n")
print(isAllSame(".55"))
cat("Test: A string of length 6 which contains tttTTT:\n")
print(isAllSame("tttTTT"))
cat("Test: A string of length 9 which contains 4444 444k:\n")
print(isAllSame("4444 444k")) |
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.
| #Simula | Simula | COMMENT
! DEADLOCK IS PREVENTED BY REVERSING THE ORDER OF TAKING THE CHOPSTICKS FOR THE LAST PHILOSOPHER.
! THAT MEANS ALL PHILOSOPHERS FIRST TAKE THE LEFT CHOPSTICK, THEN THE RIGHT CHOPSTICK.
! BUT THE LAST PHILOSOPHER FIRST TAKES THE RIGHT CHOPSTICK, THEN THE LEFT.
!
! THE DETACH STATEMENT IN CLASS PHILOSOPHER GIVES CONTROL BACK TO THE MAIN BLOCK.
! THE MAIN BLOCK CALLS/RESUMES ALL THE PHILOSOPHERS USING THE RESUME(PHILOSOPHER) STATEMENT.
! THIS CONTINUES THE CODE IN THE PHILOSOPHER CLASS AFTER THE LAST DETACH STATEMENT.
! (ANOTHER NAME FOR THIS FEATURE IS THE CONCEPT OF A COROUTINE)
;
BEGIN
INTEGER N;
INTEGER PNR, CNR;
INTEGER SEED;
SEED := ININT;
N := 5;
BEGIN
CLASS CHOPSTICK;
BEGIN
REF(PHILOSOPHER) OWNER;
INTEGER ID;
ID := CNR := CNR + 1;
END CHOPSTICK;
CLASS PHILOSOPHER(L,R);
REF(CHOPSTICK) L,R;
BEGIN
INTEGER ID;
ID := PNR := PNR + 1;
WHILE TRUE DO
BEGIN
DETACH;
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") THINKING...");
OUTIMAGE;
DETACH;
WHILE RANDINT(0,1,SEED) = 0 DO BEGIN
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") THINKING DEEPER...");
OUTIMAGE;
DETACH;
END;
WHILE L.OWNER =/= NONE DO BEGIN
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") WAITING FOR LEFT CHOPSTICK(");
OUTINT(L.ID, 0);
OUTTEXT(") ...");
OUTIMAGE;
DETACH;
END;
L.OWNER :- THIS PHILOSOPHER;
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") GRABBED LEFT CHOPSTICK(");
OUTINT(L.ID, 0);
OUTTEXT(")");
OUTIMAGE;
WHILE R.OWNER =/= NONE DO BEGIN
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") WAITING FOR RIGHT CHOPSTICK(");
OUTINT(R.ID, 0);
OUTTEXT(") ...");
OUTIMAGE;
DETACH;
END;
R.OWNER :- THIS PHILOSOPHER;
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") GRABBED RIGHT CHOPSTICK(");
OUTINT(R.ID, 0);
OUTTEXT(")");
OUTIMAGE;
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") EATING...");
OUTIMAGE;
WHILE RANDINT(0,1,SEED) = 0 DO BEGIN
DETACH;
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") STILL EATING...");
OUTIMAGE;
END;
L.OWNER :- NONE;
R.OWNER :- NONE;
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") RELEASED LEFT CHOPSTICK(");
OUTINT(L.ID, 0);
OUTTEXT(")");
OUTIMAGE;
OUTTEXT("PHILOSOPHER(");
OUTINT(ID, 0);
OUTTEXT(") RELEASED RIGHT CHOPSTICK(");
OUTINT(R.ID, 0);
OUTTEXT(")");
OUTIMAGE;
END;
END PHILOSOPHER;
!---------------------------------------|
! |
! |
! (3) |
! P2 P3 |
! |
! (2) (4) |
! |
! |
! P1 P4 |
! |
! |
! (1) (5) |
! |
! P5 | only P5 takes Right first (5), then Left (1)
! |
!---------------------------------------|
!;
REF(PHILOSOPHER) ARRAY PHILS (1:N);
REF(CHOPSTICK) L, R;
INTEGER I, LOOPS;
R :- NEW CHOPSTICK;
FOR I := 1 STEP 1 UNTIL N-1 DO
BEGIN
L :- NEW CHOPSTICK;
PHILS(I) :- NEW PHILOSOPHER(L,R);
R :- L;
END;
! REVERSED ORDER FOR THE LAST PHILOSOPHER ;
PHILS(N) :- NEW PHILOSOPHER(R,PHILS(1).R);
FOR I := 1 STEP 1 UNTIL N DO BEGIN
OUTTEXT("PHILOSOPHER(ID=");
OUTINT(PHILS(I).ID, 0);
OUTTEXT(", L=");
OUTINT(PHILS(I).L.ID, 0);
OUTTEXT(", R=");
OUTINT(PHILS(I).R.ID, 0);
OUTTEXT(")");
OUTIMAGE;
END;
FOR LOOPS := 1 STEP 1 UNTIL 10 DO BEGIN
FOR I := 1 STEP 1 UNTIL N DO BEGIN
RESUME(PHILS(I));
END;
END;
END;
END. |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Ruby | Ruby | require 'date'
class DiscordianDate
SEASON_NAMES = ["Chaos","Discord","Confusion","Bureaucracy","The Aftermath"]
DAY_NAMES = ["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"]
YEAR_OFFSET = 1166
DAYS_PER_SEASON = 73
DAYS_PER_WEEK = 5
ST_TIBS_DAY_OF_YEAR = 60
def initialize(year, month, day)
gregorian_date = Date.new(year, month, day)
@day_of_year = gregorian_date.yday
@st_tibs = false
if gregorian_date.leap?
if @day_of_year == ST_TIBS_DAY_OF_YEAR
@st_tibs = true
elsif @day_of_year > ST_TIBS_DAY_OF_YEAR
@day_of_year -= 1
end
end
@season, @day = (@day_of_year-1).divmod(DAYS_PER_SEASON)
@day += 1 #← ↑ fixes of-by-one error (only visible at season changes)
@year = gregorian_date.year + YEAR_OFFSET
end
attr_reader :year, :day
def season
SEASON_NAMES[@season]
end
def weekday
if @st_tibs
"St. Tib's Day"
else
DAY_NAMES[(@day_of_year - 1) % DAYS_PER_WEEK]
end
end
def to_s
%Q{#{@st_tibs ? "St. Tib's Day" : "%s, %s %d" % [weekday, season, day]}, #{year} YOLD}
end
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)
| #Scala | Scala | object Dijkstra {
type Path[Key] = (Double, List[Key])
def Dijkstra[Key](lookup: Map[Key, List[(Double, Key)]], fringe: List[Path[Key]], dest: Key, visited: Set[Key]): Path[Key] = fringe match {
case (dist, path) :: fringe_rest => path match {case key :: path_rest =>
if (key == dest) (dist, path.reverse)
else {
val paths = lookup(key).flatMap {case (d, key) => if (!visited.contains(key)) List((dist + d, key :: path)) else Nil}
val sorted_fringe = (paths ++ fringe_rest).sortWith {case ((d1, _), (d2, _)) => d1 < d2}
Dijkstra(lookup, sorted_fringe, dest, visited + key)
}
}
case Nil => (0, List())
}
def main(x: Array[String]): Unit = {
val lookup = Map(
"a" -> List((7.0, "b"), (9.0, "c"), (14.0, "f")),
"b" -> List((10.0, "c"), (15.0, "d")),
"c" -> List((11.0, "d"), (2.0, "f")),
"d" -> List((6.0, "e")),
"e" -> List((9.0, "f")),
"f" -> Nil
)
val res = Dijkstra[String](lookup, List((0, List("a"))), "e", Set())
println(res)
}
} |
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
| #PL.2FM | PL/M | 100H: /* SHOW THE DIGITAL ROOT AND PERSISTENCE OF SOME NUMBERS */
/* BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* PRINTS A BYTE AS A CHARACTER */
PRINT$CHAR: PROCEDURE( CH ); DECLARE CH BYTE; CALL BDOS( 2, CH ); END;
/* PRINTS A BYTE AS A NUMBER */
PRINT$BYTE: PROCEDURE( N );
DECLARE N BYTE;
DECLARE ( V, D2 ) BYTE;
IF ( V := N / 10 ) <> 0 THEN DO;
D2 = V MOD 10;
IF ( V := V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V );
CALL PRINT$CHAR( '0' + D2 );
END;
CALL PRINT$CHAR( '0' + N MOD 10 );
END PRINT$BYTE;
/* PRINTS A $ TERMINATED STRING */
PRINT$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
/* PRINTS N1, N2, N3 AS A SINGLE NUMBER */
/* N1, N2, N3 MUST ALL BE BETWEEN 0 AND 9999 INCLUSIVE */
PRINT$NUMBER3: PROCEDURE( N1, N2, N3 );
DECLARE ( N1, N2, N3 ) ADDRESS;
DECLARE V ADDRESS, N$STR( 14 ) BYTE, ( W, I, J ) BYTE;
W = LAST( N$STR );
N$STR( W ) = '$';
/* ADD THE DIGITS OF THE THREE NUMBERS TO N$STR */
DO I = 0 TO 2;
DO CASE I;
V = N3;
V = N2;
V = N1;
END;
DO J = 1 TO 4;
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
V = V / 10;
END;
END;
/* SPACE FILL THE REMAINDER OF THE NUMBER */
I = W;
DO WHILE( I > 0 );
N$STR( I := I - 1 ) = ' ';
END;
/* SUPPRESS LEADING ZEROS */
DO WHILE( W < LAST( N$STR ) - 1 AND N$STR( W ) = '0' );
N$STR( W ) = ' ';
W = W + 1;
END;
CALL PRINT$STRING( .N$STR );
END PRINT$NUMBER3;
/* CALCULATES THE DIGITAL ROOT AND PERSISTENCE OF AN INTEGER IN BASE 10 */
/* IN ORDER TO ALLOW FOR NUMBERS LARGER THAN 2^15, THE NUMBER IS PASSED */
/* AS THE UPPER, MIDDLE AND LOWER DIGITS IN N1, N2 AND N3 */
/* E.G. 393900588225 CAN BE PROCESSED BY N1=3939, N2=0058, N3=8225 */
FIND$DIGITAL$ROOT: PROCEDURE( N1, N2, N3, ROOT$PTR, PERSISTENCE$PTR );
DECLARE ( N1, N2, N3, ROOT$PTR, PERSISTENCE$PTR ) ADDRESS;
DECLARE DIGITAL$ROOT BASED ROOT$PTR BYTE;
DECLARE PERSISTENCE BASED PERSISTENCE$PTR BYTE;
SUM$DIGITS: PROCEDURE( N ) ADDRESS;
DECLARE N ADDRESS;
DECLARE DIGITS ADDRESS, SUM BYTE;
DIGITS = N;
SUM = 0;
DO WHILE DIGITS > 0;
SUM = SUM + ( DIGITS MOD 10 );
DIGITS = DIGITS / 10;
END;
RETURN SUM;
END SUM$DIGITS;
DIGITAL$ROOT = SUM$DIGITS( N1 ) + SUM$DIGITS( N2 ) + SUM$DIGITS( N3 );
PERSISTENCE = 1;
DO WHILE( DIGITAL$ROOT > 9 );
PERSISTENCE = PERSISTENCE + 1;
DIGITAL$ROOT = SUM$DIGITS( DIGITAL$ROOT );
END;
END FIND$DIGITAL$ROOT ;
/* CALCULATES AND PRINTS THE DIGITAL ROOT AND PERSISTENCE OF THE */
/* NUMBER FORMED FROM THE CONCATENATION OF N1, N2 AND N3 */
PRINT$DR$AND$PERSISTENCE: PROCEDURE( N1, N2, N3 );
DECLARE ( N1, N2, N3 ) ADDRESS;
DECLARE ( DIGITAL$ROOT, PERSISTENCE ) BYTE;
CALL FIND$DIGITAL$ROOT( N1, N2, N3, .DIGITAL$ROOT, .PERSISTENCE );
CALL PRINT$NUMBER3( N1, N2, N3 );
CALL PRINT$STRING( .': DIGITAL ROOT: $' );
CALL PRINT$BYTE( DIGITAL$ROOT );
CALL PRINT$STRING( .', PERSISTENCE: $' );
CALL PRINT$BYTE( PERSISTENCE );
CALL PRINT$STRING( .( 0DH, 0AH, '$' ) );
END PRINT$DR$AND$PERSISTENCE;
/* TEST THE DIGITAL ROOT AND PERSISTENCE PROCEDURES */
CALL PRINT$DR$ANDPERSISTENCE( 0, 62, 7615 );
CALL PRINT$DR$ANDPERSISTENCE( 0, 3, 9390 );
CALL PRINT$DR$ANDPERSISTENCE( 0, 58, 8225 );
CALL PRINT$DR$ANDPERSISTENCE( 3939, 0058, 8225 );
EOF |
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
| #Potion | Potion | digital = (x) :
dr = x string # Digital Root.
ap = 0 # Additive Persistence.
while (dr length > 1) :
sum = 0
dr length times (i): sum = sum + dr(i) number integer.
dr = sum string
ap++
.
(x, " has additive persistence ", ap,
" and digital root ", dr, ";\n") join print
.
digital(627615)
digital(39390)
digital(588225)
digital(393900588225) |
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?
| #UNIX_Shell | UNIX Shell | #!/bin/bash
# NAMES is a list of names. It can be changed as needed. It can be more than five names, or less.
NAMES=(Baker Cooper Fletcher Miller Smith)
# CRITERIA are the rules imposed on who lives where. Each criterion must be a valid bash expression
# that will be evaluated. TOP is the top floor; BOTTOM is the bottom floor.
# The CRITERIA can be changed to create different rules.
CRITERIA=(
'Baker != TOP' # Baker does not live on the top floor
'Cooper != BOTTOM' # Cooper does not live on the bottom floor
'Fletcher != TOP' # Fletcher does not live on the top floor
'Fletcher != BOTTOM' # and Fletch also does not live on the bottom floor
'Miller > Cooper' # Miller lives above Cooper
'$(abs $(( Smith - Fletcher )) ) > 1' # Smith and Fletcher are not on adjacent floors
'$(abs $(( Fletcher - Cooper )) ) > 1' # Fletcher and Cooper are not on adjacent floors
)
# Code below here shouldn't need to change to vary parameters
let BOTTOM=0
let TOP=${#NAMES[@]}-1
# Not available as a builtin
abs() { local n=$(( 10#$1 )) ; echo $(( n < 0 ? -n : n )) ; }
# Algorithm we use to iterate over the permutations
# requires that we start with the array sorted lexically
NAMES=($(printf "%s\n" "${NAMES[@]}" | sort))
while true; do
# set each name to its position in the array
for (( i=BOTTOM; i<=TOP; ++i )); do
eval "${NAMES[i]}=$i"
done
# check to see if we've solved the problem
let solved=1
for criterion in "${CRITERIA[@]}"; do
if ! eval "(( $criterion ))"; then
let solved=0
break
fi
done
if (( solved )); then
echo "From bottom to top: ${NAMES[@]}"
break
fi
# Bump the names list to the next permutation
let j=TOP-1
while (( j >= BOTTOM )) && ! [[ "${NAMES[j]}" < "${NAMES[j+1]}" ]]; do
let j-=1
done
if (( j < BOTTOM )); then break; fi
let k=TOP
while (( k > j )) && [[ "${NAMES[k]}" < "${NAMES[j]}" ]]; do
let k-=1
done
if (( k <= j )); then break; fi
t="${NAMES[j]}"
NAMES[j]="${NAMES[k]}"
NAMES[k]="$t"
for (( k=1; k<=(TOP-j); ++k )); do
a=BOTTOM+j+k
b=TOP-k+1
if (( a < b )); then
t="${NAMES[a]}"
NAMES[a]="${NAMES[b]}"
NAMES[b]="$t"
fi
done
done |
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
| #Maxima | Maxima | [1, 3, -5] . [4, -2, -1];
/* 3 */ |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Mercury | Mercury | :- module dot_product.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list.
main(!IO) :-
io.write_int([1, 3, -5] `dot_product` [4, -2, -1], !IO),
io.nl(!IO).
:- func dot_product(list(int), list(int)) = int.
dot_product(As, Bs) =
list.foldl_corresponding((func(A, B, Acc) = Acc + A * B), As, Bs, 0). |
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
| #Factor | Factor | USING: formatting io kernel math math.combinatorics math.ranges
sequences sets ;
IN: rosetta-code.department-numbers
7 [1,b] 3 <k-permutations>
[ [ first even? ] [ sum 12 = ] bi and ] filter
"{ Police, Sanitation, Fire }" print nl
[ "%[%d, %]\n" printf ] each |
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
| #Fermat | Fermat | !!'Police Sanitation Fire';
!!'------|----------|----';
for p = 2 to 6 by 2 do
for s = 1 to 7 do
for f = 1 to 7 do
if p+f+s=12 and f<>p and f<>s and s<>p then !!(' ',p,' ',s,' ',f);
fi od od od; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.