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/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
| #C.23 | C# | using System;
using System.Linq;
class Program
{
static Tuple<int, int> DigitalRoot(long num)
{
int additivepersistence = 0;
while (num > 9)
{
num = num.ToString().ToCharArray().Sum(x => x - '0');
additivepersistence++;
}
return new Tuple<int, int>(additivepersistence, (int)num);
}
static void Main(string[] args)
{
foreach (long num in new long[] { 627615, 39390, 588225, 393900588225 })
{
var t = DigitalRoot(num);
Console.WriteLine("{0} has additive persistence {1} and digital root {2}", num, t.Item1, t.Item2);
}
}
} |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #J | J | 10&#.inv 123321
1 2 3 3 2 1 |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Xfractint | Xfractint | Dragon3 {
Angle 4
Axiom XF
X=XF+Y
Y=XF-Y
} |
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?
| #Erlang | Erlang |
-module( dinesman_multiple_dwelling ).
-export( [solve/2, task/0] ).
solve( All_persons, Rules ) ->
[house(Bottom_floor, B, C, D, Top_floor) || Bottom_floor <- All_persons, B <- All_persons, C <- All_persons, D <- All_persons, Top_floor <- All_persons,
lists:all( fun (Fun) -> Fun( house(Bottom_floor, B, C, D, Top_floor) ) end, rules( Rules ))].
task() ->
All_persons = [baker, cooper, fletcher, miller, smith],
Rules = [all_on_different_floors, {not_lives_on_floor, 4, baker}, {not_lives_on_floor, 0, cooper}, {not_lives_on_floor, 4, fletcher}, {not_lives_on_floor, 0, fletcher},
{on_higher_floor, miller, cooper}, {not_adjacent, smith, fletcher}, {not_adjacent, fletcher, cooper}],
[House] = solve( All_persons, Rules ),
[io:fwrite("~p lives on floor ~p~n", [lists:nth(X, House), X - 1]) || X <- lists:seq(1,5)].
house( A, B, C, D, E ) -> [A, B, C, D, E].
is_all_on_different_floors( [A, B, C, D, E] ) ->
A =/= B andalso A =/= C andalso A =/= D andalso A =/= E
andalso B =/= C andalso B =/= D andalso B =/= E
andalso C =/= D andalso C =/= E
andalso D =/= E.
is_not_adjacent( Person1, Person2, House ) ->
is_not_below( Person1, Person2, House ) andalso is_not_below( Person2, Person1, House ).
is_not_below( _Person1, _Person2, [_Person] ) -> true;
is_not_below( Person1, Person2, [Person1, Person2 | _T] ) -> false;
is_not_below( Person1, Person2, [_Person | T] ) -> is_not_below( Person1, Person2, T ).
is_on_higher_floor( Person1, _Person2, [Person1 | _T] ) -> false;
is_on_higher_floor( _Person1, Person2, [Person2 | _T] ) -> true;
is_on_higher_floor( Person1, Person2, [_Person | T] ) -> is_on_higher_floor( Person1, Person2, T ).
rules( Rules ) -> lists:map( fun rules_fun/1, Rules ).
rules_fun( all_on_different_floors ) -> fun is_all_on_different_floors/1;
rules_fun( {not_lives_on_floor, N, Person} ) -> fun (House) -> Person =/= lists:nth(N + 1, House) end;
rules_fun( {on_higher_floor, Person1, Person2} ) -> fun (House) -> is_on_higher_floor( Person1, Person2, House ) end;
rules_fun( {not_below, Person1, Person2} ) -> fun (House) -> is_not_below( Person1, Person2, House ) end;
rules_fun( {not_adjacent, Person1, Person2} ) -> fun (House) -> is_not_adjacent( Person1, Person2, House ) end.
|
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
| #DWScript | DWScript | function DotProduct(a, b : array of Float) : Float;
require
a.Length = b.Length;
var
i : Integer;
begin
Result := 0;
for i := 0 to a.High do
Result += a[i]*b[i];
end;
PrintLn(DotProduct([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
| #11l | 11l | F squeeze(input, include)
V s = ‘’
L(i) 0 .< input.len
I i == 0 | input[i - 1] != input[i] | (input[i - 1] == input[i] & input[i] != include)
s ‘’= input[i]
R s
V testStrings = [
‘’,
‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ’,
‘..1111111111111111111111111111111111111111111111111111111111111117777888’,
‘I never give 'em hell, I just tell the truth, and they think it's hell. ’,
‘ --- Harry S Truman ’,
‘122333444455555666666777777788888888999999999’,
‘The better the 4-wheel drive, the further you'll be from help when ya get stuck!’,
‘headmistressship’
]
V testChar = [
‘ ’,
‘-’,
‘7’,
‘.’,
‘ -r’,
‘5’,
‘e’,
‘s’
]
L(testNum) 0 .< testStrings.len
V s = testStrings[testNum]
L(c) testChar[testNum]
V result = squeeze(s, c)
print("use: '#.'\nold: #2 <<<#.>>>\nnew: #2 <<<#.>>>\n".format(c, s.len, s, result.len, result)) |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Raku | Raku | role DLElem[::T] {
has DLElem[T] $.prev is rw;
has DLElem[T] $.next is rw;
has T $.payload = T;
method pre-insert(T $payload) {
die "Can't insert before beginning" unless $!prev;
my $elem = ::?CLASS.new(:$payload);
$!prev.next = $elem;
$elem.prev = $!prev;
$elem.next = self;
$!prev = $elem;
$elem;
}
method post-insert(T $payload) {
die "Can't insert after end" unless $!next;
my $elem = ::?CLASS.new(:$payload);
$!next.prev = $elem;
$elem.next = $!next;
$elem.prev = self;
$!next = $elem;
$elem;
}
method delete {
die "Can't delete a sentinel" unless $!prev and $!next;
$!next.prev = $!prev;
$!prev.next = $!next; # conveniently returns next element
}
}
role DLList[::DLE] {
has DLE $.first;
has DLE $.last;
submethod BUILD {
$!first = DLE.new;
$!last = DLE.new;
$!first.next = $!last;
$!last.prev = $!first;
}
method list { ($!first.next, *.next ...^ !*.next).map: *.payload }
method reverse { ($!last.prev, *.prev ...^ !*.prev).map: *.payload }
}
class DLElem_Int does DLElem[Int] {}
class DLList_Int does DLList[DLElem_Int] {}
my $dll = DLList_Int.new;
$dll.first.post-insert(1).post-insert(2).post-insert(3);
$dll.first.post-insert(0);
$dll.last.pre-insert(41).pre-insert(40).prev.delete; # (deletes 3)
$dll.last.pre-insert(42);
say $dll.list; # 0 1 2 40 41 42
say $dll.reverse; # 42 41 40 2 1 0 |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Lua | Lua |
local function simu(ndice1, nsides1, ndice2, nsides2)
local function roll(ndice, nsides)
local result = 0;
for i = 1, ndice do
result = result + math.random(nsides)
end
return result
end
local wins, coms = 0, 1000000
for i = 1, coms do
local roll1 = roll(ndice1, nsides1)
local roll2 = roll(ndice2, nsides2)
if (roll1 > roll2) then
wins = wins + 1
end
end
print("simulated: p1 = "..ndice1.."d"..nsides1..", p2 = "..ndice2.."d"..nsides2..", prob = "..wins.." / "..coms.." = "..(wins/coms))
end
simu(9, 4, 6, 6)
simu(5, 10, 6, 7)
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Jsish | Jsish | /* Determine if only one instance, in Jsish */
var sock;
try {
sock = new Socket({client:false, port:54321});
puts('\nApplication running for 30 seconds, from', strftime());
update(30000);
puts('\nApplication ended at', strftime());
} catch (err) {
puts('Applicaion already running');
exit(1);
} |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Julia | Julia |
using Sockets
const portnum = 12345
function canopen()
try
server = listen(portnum)
println("This is the only instance.")
sleep(20)
catch y
if findfirst("EADDRINUSE", string(y)) != nothing
println("There is already an instance running.")
end
end
end
canopen()
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Kotlin | Kotlin | // version 1.0.6
import java.io.IOException
import java.net.*
object SingleInstance {
private var ss: ServerSocket? = null
fun alreadyRunning(): Boolean {
try {
ss = ServerSocket(65000, 10, InetAddress.getLocalHost()) // using private port 65000
}
catch (e: IOException) {
// port already in use so an instance is already running
return true
}
return false
}
fun close() {
if (ss == null || ss?.isClosed() == true) return
ss?.close()
}
}
fun main(args: Array<String>) {
if (SingleInstance.alreadyRunning()) {
println("Application is already running, so terminating this instance")
System.exit(0)
}
else {
println("OK, only this instance is running but will terminate in 10 seconds")
Thread.sleep(10000)
SingleInstance.close()
}
} |
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.
| #EchoLisp | EchoLisp |
(lib 'tasks)
(define names #(Aristotle Kant Spinoza Marx Russell))
(define abouts #("Wittgenstein" "the nature of the World" "Kant" "starving"
"spaghettis" "the essence of things" "Ω" "📞" "⚽️" "🍅" "🌿"
"philosophy" "💔" "👠" "rosetta code" "his to-do list" ))
(define (about) (format "thinking about %a." (vector-ref abouts (random (vector-length abouts)))))
;; statistics
(define rounds (make-vector 5 0))
(define (eat i) (vector-set! rounds i (1+ (vector-ref rounds i))))
;; forks are resources = semaphores
(define (left i) i)
(define (right i) (modulo (1+ i) 5))
(define forks (for/vector ((i 5)) (make-semaphore 1)))
(define (fork i) (vector-ref forks i))
(define laquais (make-semaphore 4))
;; philosophers tasks
(define (philo i)
;; thinking
(writeln (vector-ref names i) (about))
(sleep (+ 2000 (random 1000)))
(wait laquais)
;; get forks
(writeln (vector-ref names i) 'sitting)
(wait (fork (left i)))
(wait (fork (right i)))
(writeln (vector-ref names i) 'eating)
(eat i)
(sleep (+ 6000 (random 1000)))
;; put-forks
(signal (fork (left i)))
(signal (fork (right i)))
(signal laquais)
i)
(define tasks (for/vector ((i 5)) (make-task philo i)))
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Clojure | Clojure | (require '[clj-time.core :as tc])
(def seasons ["Chaos" "Discord" "Confusion" "Bureaucracy" "The Aftermath"])
(def weekdays ["Sweetmorn" "Boomtime" "Pungenday" "Prickle-Prickle" "Setting Orange"])
(def year-offset 1166)
(defn leap-year? [year]
(= 29 (tc/number-of-days-in-the-month year 2)))
(defn discordian-day [day leap]
(let [offset (if (and leap (>= day 59)) 1 0)
day-off (- day offset)
day-num (inc (rem day-off 73))
season (seasons (quot day-off 73))
weekday (weekdays (mod day-off 5))]
(if (and (= day 59) (= offset 1))
"St. Tib's Day"
(str weekday ", " season " " day-num))))
(defn discordian-date [year month day]
(let [day-of-year (dec (.getDayOfYear (tc/date-time year month day)))
dday (discordian-day day-of-year (leap-year? year))]
(format "%s, YOLD %s" dday (+ year year-offset)))) |
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)
| #Delphi | Delphi | program Rosetta_Dijkstra_Console;
{$APPTYPE CONSOLE}
uses SysUtils; // for printing the result
// Conventional values (any negative values would do)
const
INFINITY = -1;
NO_VERTEX = -2;
const
NR_VERTICES = 6;
// DISTANCE_MATRIX[u, v] = length of directed edge from u to v, or -1 if no such edge exists.
// A simple way to represent a directed graph with not many vertices.
const DISTANCE_MATRIX : array [0..(NR_VERTICES - 1), 0..(NR_VERTICES - 1)] of integer
= ((-1, 7, 9, -1, -1, -1),
(-1, -1, 10, 15, -1, -1),
(-1, -1, -1, 11, -1, 2),
(-1, -1, -1, -1, 6, -1),
(-1, -1, -1, -1, -1, 9),
(-1, -1, -1, -1, -1, -1));
type TVertex = record
Distance : integer; // distance from vertex 0; infinity if a path has not yet been found
Previous : integer; // previous vertex in the path from vertex 0
Visited : boolean; // as defined in the algorithm
end;
// For distances x and y, test whether x < y, using the convention that -1 means infinity.
function IsLess( x, y : integer) : boolean;
begin
result := (x <> INFINITY)
and ( (y = INFINITY) or (x < y) );
end;
// Main routine
var
v : array [0..NR_VERTICES - 1] of TVertex; // array of vertices
c : integer; // index of current vertex
j : integer; // loop counter
trialDistance : integer;
minDistance : integer;
// Variables for printing the result
p : integer;
lineOut : string;
begin
// Initialize the vertices
for j := 0 to NR_VERTICES - 1 do begin
v[j].Distance := INFINITY;
v[j].Previous := NO_VERTEX;
v[j].Visited := false;
end;
// Start with vertex 0 as the current vertex
c := 0;
v[c].Distance := 0;
// Main loop of Dijkstra's algorithm
repeat
// Work through unvisited neighbours of the current vertex, updating them where possible.
// "Neighbour" means the end of a directed edge from the current vertex.
// Note that v[c].Distance is always finite.
for j := 0 to NR_VERTICES - 1 do begin
if (not v[j].Visited) and (DISTANCE_MATRIX[c, j] >= 0) then begin
trialDistance := v[c].Distance + DISTANCE_MATRIX[c, j];
if IsLess( trialDistance, v[j].Distance) then begin
v[j].Distance := trialDistance;
v[j].Previous := c;
end;
end;
end;
// When all neighbours have been tested, mark the current vertex as visited.
v[c].Visited := true;
// The new current vertex is the unvisited vertex with the smallest finite distance.
// If there is no such vertex, the algorithm is finished.
c := NO_VERTEX;
minDistance := INFINITY;
for j := 0 to NR_VERTICES - 1 do begin
if (not v[j].Visited) and IsLess( v[j].Distance, minDistance) then begin
minDistance := v[j].Distance;
c := j;
end;
end;
until (c = NO_VERTEX);
// Print the result
for j := 0 to NR_VERTICES - 1 do begin
if (v[j].Distance = INFINITY) then begin
// The algorithm never found a path to v[j]
lineOut := SysUtils.Format( '%2d: inaccessible', [j]);
end
else begin
// Build up the path of vertices, working backwards from v[j]
lineOut := SysUtils.Format( '%2d', [j]);
p := v[j].Previous;
while (p <> NO_VERTEX) do begin
lineOut := SysUtils.Format( '%2d --> ', [p]) + lineOut;
p := v[p].Previous;
end;
// Print the path of vertices, preceded by distance from vertex 0
lineOut := SysUtils.Format( '%2d: distance = %3d, ', [j, v[j].Distance]) + lineOut;
end;
WriteLn( lineOut);
end;
end. |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #C.2B.2B | C++ | // Calculate the Digital Root and Additive Persistance of an Integer - Compiles with gcc4.7
//
// Nigel Galloway. July 23rd., 2012
//
#include <iostream>
#include <cmath>
#include <utility>
template<class P_> P_ IncFirst(const P_& src) {return P_(src.first + 1, src.second);}
std::pair<int, int> DigitalRoot(unsigned long long digits, int base = 10)
{
int x = SumDigits(digits, base);
return x < base ? std::make_pair(1, x) : IncFirst(DigitalRoot(x, base)); // x is implicitly converted to unsigned long long; this is lossless
}
int main() {
const unsigned long long ip[] = {961038,923594037444,670033,448944221089};
for (auto i:ip){
auto res = DigitalRoot(i);
std::cout << i << " has digital root " << res.second << " and additive persistance " << res.first << "\n";
}
std::cout << "\n";
const unsigned long long hip[] = {0x7e0,0x14e344,0xd60141,0x12343210};
for (auto i:hip){
auto res = DigitalRoot(i,16);
std::cout << std::hex << i << " has digital root " << res.second << " and additive persistance " << res.first << "\n";
}
return 0;
} |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Java | Java | import java.util.*;
public class MultiplicativeDigitalRoot {
public static void main(String[] args) {
System.out.println("NUMBER MDR MP");
for (long n : new long[]{123321, 7739, 893, 899998}) {
long[] a = multiplicativeDigitalRoot(n);
System.out.printf("%6d %4d %4d%n", a[0], a[1], a[2]);
}
System.out.println();
Map<Long, List<Long>> table = new HashMap<>();
for (long i = 0; i < 10; i++)
table.put(i, new ArrayList<>());
for (long cnt = 0, n = 0; cnt < 10;) {
long[] res = multiplicativeDigitalRoot(n++);
List<Long> list = table.get(res[1]);
if (list.size() < 5) {
list.add(res[0]);
cnt = list.size() == 5 ? cnt + 1 : cnt;
}
}
System.out.println("MDR: first five numbers with same MDR");
table.forEach((key, lst) -> {
System.out.printf("%3d: ", key);
lst.forEach(e -> System.out.printf("%6s ", e));
System.out.println();
});
}
public static long[] multiplicativeDigitalRoot(long n) {
int mp = 0;
long mdr = n;
while (mdr > 9) {
long m = mdr;
long total = 1;
while (m > 0) {
total *= m % 10;
m /= 10;
}
mdr = total;
mp++;
}
return new long[]{n, mdr, mp};
}
} |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc Dragon(D, P, Q); \Draw a colorful dragon curve
int D, P, Q; \recursive depth, coordinates of line segment
int R(2), \coordinates of generated new point
DX, DY, C; \deltas, color
[C:= [0]; \color is a local, static-like variable
D:= D+1; \depth of recursion increases
if D >= 13 then \draw lines at maximum depth to get solid image
[Move(P(0), P(1)); Line(Q(0), Q(1), C(0)>>9+4!8); C(0):= C(0)+1; return];
DX:= Q(0)-P(0); DY:= Q(1)-P(1);
R(0):= P(0) + (DX-DY)/2; \new point
R(1):= P(1) + (DX+DY)/2;
Dragon(D, P, R); \draw two segments that include the new point
Dragon(D, Q, R);
];
int X, Y, P(2), Q(2);
[SetVid($101); \set 640x480 video graphics mode
X:= 32; Y:= 32; \coordinates of initial horizontal line segment
P(0):= X; P(1):= Y;
Q(0):= X+64; Q(1):= Y; \(power of two length works best for integers)
Dragon(0, P, Q); \draw its dragon curve
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore normal text mode
] |
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?
| #ERRE | ERRE | PROGRAM DINESMAN
BEGIN
! Floors are numbered 0 (ground) to 4 (top)
! "Baker, Cooper, Fletcher, Miller, and Smith live on different floors":
stmt1$="Baker<>Cooper AND Baker<>Fletcher AND Baker<>Miller AND "+"Baker<>Smith AND Cooper<>Fletcher AND Cooper<>Miller AND "+"Cooper<>Smith AND Fletcher<>Miller AND Fletcher<>Smith AND "+"Miller<>Smith"
! "Baker does not live on the top floor":
stmt2$="Baker<>4"
! "Cooper does not live on the bottom floor":
stmt3$="Cooper<>0"
! "Fletcher does not live on either the top or the bottom floor":
stmt4$="Fletcher<>0 AND Fletcher<>4"
! "Miller lives on a higher floor than does Cooper":
stmt5$="Miller>Cooper"
! "Smith does not live on a floor adjacent to Fletcher's":
stmt6$="ABS(Smith-Fletcher)<>1"
! "Fletcher does not live on a floor adjacent to Cooper's":
stmt7$="ABS(Fletcher-Cooper)<>1"
FOR Baker=0 TO 4 DO
FOR Cooper=0 TO 4 DO
FOR Fletcher=0 TO 4 DO
FOR Miller=0 TO 4 DO
FOR Smith=0 TO 4 DO
IF Baker<>4 AND Cooper<>0 AND Miller>Cooper THEN
IF Fletcher<>0 AND Fletcher<>4 AND ABS(Smith-Fletcher)<>1 AND ABS(Fletcher-Cooper)<>1 THEN
IF Baker<>Cooper AND Baker<>Fletcher AND Baker<>Miller AND Baker<>Smith AND Cooper<>Fletcher AND Cooper<>Miller AND Cooper<>Smith AND Fletcher<>Miller AND Fletcher<>Smith AND Miller<>Smith THEN
PRINT("Baker lives on floor ";Baker)
PRINT("Cooper lives on floor ";Cooper)
PRINT("Fletcher lives on floor ";Fletcher)
PRINT("Miller lives on floor ";Miller)
PRINT("Smith lives on floor ";Smith)
END IF
END IF
END IF
END FOR ! Smith
END FOR ! Miller
END FOR ! Fletcher
END FOR ! Cooper
END FOR ! Baker
END PROGRAM |
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | dot a b:
if /= len a len b:
Raise value-error "dot product needs two vectors with the same length"
0
while a:
+ * pop-from a pop-from b
!. dot [ 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
| #8080_Assembly | 8080 Assembly | puts: equ 9
org 100h
jmp demo
;;; Squeeze the string at DE on the character in C.
;;; The result is written starting at HL.
squeez: mvi b,'$' ; Last character seen
dcx d ; Move pointer back one item
sqzlp: mvi m,'$' ; Stop on end of string
inx d ; Increment input pointer
ldax d ; Grab character from input string
cmp m ; End reached?
rz ; Then stop
cmp c ; Was it equal to the character to squeeze?
jnz sqzwr ; If not, then write it to the output
mov a,b ; If so, is the previous character?
cmp c
jz sqzlp ; If so, ignore this one
sqzwr: ldax d ; Retrieve the character again
mov m,a ; It goes in the output
mov b,a ; And it is the last character seen
inx h ; Increment output pointer
jmp sqzlp
;;; Print the string in DE and character in C as specified,
;;; squeeze the string and print the output.
prsqz: push b ; Save input parameters
push d
mov a,c ; Store character
sta chval
lxi d,chstr ; Print character
mvi c,puts
call 5
pop h ; Retrieve input string pointer
push h
call prbrkt ; Print the string in brackets
pop d ; Retrieve both input parameters
pop b
lxi h,buffer
call squeez ; Squeeze the input string
lxi h,buffer ; ... fall through to print the result
;;; Write the string at HL and its length in brackets
prbrkt: push h ; Keep the pointer
mvi b,0FFh ; Find the length
mvi a,'$' ; End marker
dcx h
lscan: inr b ; Scan through the string incrementing B
inx h ; and HL until the end is found
cmp m
jnz lscan
mov a,b ; Find high and low digit (assuming < 100)
mvi b,'0'-1
pdigit: inr b ; B = high digit
sui 10
jnc pdigit
lxi h,bstart+1
adi '0'+10
mov m,a ; Write low digit
dcx h
mov m,b ; Write high digit
xchg
mvi c,puts ; Print length and brackets
call 5
pop d ; Retrieve the string pointer
mvi c,puts ; Print the string
call 5
lxi d,bend ; Print the ending brackets
mvi c,puts
jmp 5
;;; Squeeze each string by the given character
demo: lxi h,list ; Pointer to start of list
loop: mov e,m ; Load pointer and character
inx h
mov d,m
inx h
mov c,m
inx h
xra a ; Stop when zero reached
ora c
rz
push h ; Keep list pointer
call prsqz ; Squeeze and print
pop h ; Restore list pointer
jmp loop
;;; Formatting strings
chstr: db 'Character: "'
chval: db '*"',13,10,'$'
bstart: db '##<<<$'
bend: db '>>>'
nl: db 13,10,'$'
;;; Input strings
str1: db '$'
str2: db '"If I were two-faced, would I be wearing'
db ' this one?" --- Abraham Lincoln $'
str3: db '..11111111111111111111111111111111111111'
db '11111111111111111111111117777888$'
str4: db 'I never give ',39,'em hell, I just tell the t'
db 'ruth, and they think it',39,'s hell. $'
str5: db ' '
db ' --- Harry S Truman $'
;;; Pairs of string pointers and characters to squeeze
list: dw str1
db ' '
dw str2
db '-'
dw str3
db '7'
dw str4
db '.'
dw str5
db ' '
dw str5
db '-'
dw str5
db 'r'
dw 0
db 0
buffer: equ $ |
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
| #Action.21 | Action! | PROC Squeeze(CHAR ARRAY in,out CHAR a)
BYTE i,j
CHAR c
j=1 c=0
FOR i=1 TO in(0)
DO
IF in(i)#c OR in(i)#a THEN
c=in(i)
out(j)=c
j==+1
FI
OD
out(0)=j-1
RETURN
PROC Test(CHAR ARRAY s CHAR a)
CHAR ARRAY c(100)
BYTE CH=$02FC ;Internal hardware value for last key pressed
Squeeze(s,c,a)
PrintF("Character to squeeze: ""%C""%E",a)
PrintF("<<<%S>>> (len=%B)%E",s,s(0))
PrintF("<<<%S>>> (len=%B)%E",c,c(0))
PutE()
PrintE("Press any key to continue")
PutE()
DO UNTIL CH#$FF OD
CH=$FF
RETURN
PROC Main()
Test("",' )
Test("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ",'-)
Test("..1111111111111111111111111111111111111111111111111111111111111117777888",'7)
Test("I never give 'em hell, I just tell the truth, and they think it's hell. ",'.)
Test(" --- Harry S Truman ",' )
Test(" --- Harry S Truman ",'-)
Test(" --- Harry S Truman ",'r)
RETURN |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #REXX | REXX | ╔═════════════════════════════════════════════════════════════════════════╗
║ ☼☼☼☼☼☼☼☼☼☼☼ Functions of the List Manager ☼☼☼☼☼☼☼☼☼☼☼ ║
║ @init ─── initializes the List. ║
║ ║
║ @size ─── returns the size of the List [could be a 0 (zero)]. ║
║ ║
║ @show ─── shows (displays) the complete List. ║
║ @show k,1 ─── shows (displays) the Kth item. ║
║ @show k,m ─── shows (displays) M items, starting with Kth item. ║
║ @show ,,─1 ─── shows (displays) the complete List backwards. ║
║ ║
║ @get k ─── returns the Kth item. ║
║ @get k,m ─── returns the M items starting with the Kth item. ║
║ ║
║ @put x ─── adds the X items to the end (tail) of the List. ║
║ @put x,0 ─── adds the X items to the start (head) of the List. ║
║ @put x,k ─── adds the X items to before of the Kth item. ║
║ ║
║ @del k ─── deletes the item K. ║
║ @del k,m ─── deletes the M items starting with item K. ║
╚═════════════════════════════════════════════════════════════════════════╝
|
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[GetProbability]
GetProbability[{dice1_List, n_Integer}, {dice2_List, m_Integer}] :=
Module[{a, b, lena, lenb},
a = Tuples[dice1, n];
a = Plus @@@ a;
lena = a // Length;
a = Tally[a];
a[[All, 2]] /= lena;
b = Tuples[dice2, m];
b = Plus @@@ b;
lenb = b // Length;
b = Tally[b];
b[[All, 2]] /= lenb;
Total[If[#[[1, 1]] > #[[2, 1]], #[[1, 2]] #[[2, 2]], 0] & /@
Tuples[{a, b}]]
]
GetProbability[{Range[4], 9}, {Range[6], 6}]
GetProbability[{Range[10], 5}, {Range[7], 6}] |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Nim | Nim | import bignum
from math import sum
proc counts(ndices, nsides: int): seq[int] =
result.setlen(ndices * nsides + 1)
for i in 1..nsides:
result[i] = 1
for i in 1..<ndices:
var c = newSeq[int](result.len)
for sum in i..(i * nsides):
for val in 1..nsides:
inc c[sum + val], result[sum]
result.shallowCopy(c)
proc probabilities(counts: seq[int]): seq[Rat] =
result.setLen(counts.len)
let total = sum(counts)
for i, n in counts:
result[i] = newRat(n, total)
proc beatingProbability(ndices1, nsides1, ndices2, nsides2: int): Rat =
let counts1 = counts(ndices1, nsides1)
let counts2 = counts(ndices2, nsides2)
var p1 = counts1.probabilities()
var p2 = counts2.probabilities()
result = newRat(0)
for sum1 in ndices1..p1.high:
var p = newRat(0)
for sum2 in ndices2..min(sum1 - 1, p2.high):
p += p2[sum2]
result += p1[sum1] * p
echo beatingProbability(9, 4, 6, 6).toFloat
echo beatingProbability(5, 10, 6, 7).toFloat |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Lasso | Lasso | #!/usr/bin/lasso9
local(lockfile = file('/tmp/myprocess.lockfile'))
if(#lockfile -> exists) => {
stdoutnl('Error: App is running as of ' + #lockfile -> readstring)
abort
}
handle => {
#lockfile -> delete
}
stdoutnl('Starting execution')
#lockfile -> doWithClose => {
#lockfile -> writebytes(bytes(date))
}
sleep(10000)
stdoutnl('Execution done') |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Liberty_BASIC | Liberty BASIC | 'Create a Mutex to prevent more than one instance from being open at a single time.
CallDLL #kernel32, "CreateMutexA", 0 as Long, 1 as Long, "Global\My Program" as ptr, mutex as ulong
CallDLL #kernel32, "GetLastError", LastError as Long
if LastError = 183 then 'Error returned when a Mutex already exists
'Close the handle if the mutex already exists
calldll #kernel32, "CloseHandle", mutex as ulong, ret as ulong
notice "An instance of My Program is currently running!"
end
end if
'Release the Mutex/ Close the handle prior to ending the program
'Comment out these lines to allow the program to remain active to test for the mutex's presence
calldll #kernel32, "ReleaseMutex", mutex as ulong, ret as ulong
calldll #kernel32, "CloseHandle", mutex as ulong, ret as ulong
end |
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.
| #Eiffel | Eiffel | class
DINING_PHILOSOPHERS
create
make
feature -- Initialization
make
-- Create philosophers and forks.
local
first_fork: separate FORK
left_fork: separate FORK
right_fork: separate FORK
philosopher: separate PHILOSOPHER
i: INTEGER
do
print ("Dining Philosophers%N" + philosopher_count.out + " philosophers, " + round_count.out + " rounds%N%N")
create philosophers.make
from
i := 1
create first_fork.make (philosopher_count, 1)
left_fork := first_fork
until
i > philosopher_count
loop
if i < philosopher_count then
create right_fork.make (i, i + 1)
else
right_fork := first_fork
end
create philosopher.make (i, left_fork, right_fork, round_count)
philosophers.extend (philosopher)
left_fork := right_fork
i := i + 1
end
philosophers.do_all (agent launch_philosopher)
print ("Make Done!%N")
end
feature {NONE} -- Implementation
philosopher_count: INTEGER = 5
-- Number of philosophers.
round_count: INTEGER = 30
-- Number of times each philosopher should eat.
philosophers: LINKED_LIST [separate PHILOSOPHER]
-- List of philosophers.
launch_philosopher (a_philosopher: separate PHILOSOPHER)
-- Launch a_philosopher.
do
a_philosopher.live
end
end -- class DINING_PHILOSOPHERS |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #CLU | CLU | % This program needs to be merged with PCLU's "useful.lib",
% so it can use get_argv to read the command line.
%
% pclu -merge $CLUHOME/lib/useful.lib -compile cmdline.clu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Represent a day in the Discordian calendar %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
eris_date = cluster is from_greg_y_m_d,
from_date,
get_year,
get_day,
get_season,
get_weekday,
get_day_name,
get_holyday,
get_format
greyface = 1166
% A Discordian day is either St. Tib's day
% or a day in a season
season_day = struct[season, day: int]
eris_day = oneof[st_tibs: null, season_day: season_day]
% A Discordian date is a day in a year
rep = struct[year: int, day: eris_day]
% Offset of each Gregorian month in a non-leap year
own month_offset: sequence[int] := sequence[int]$[
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
]
% Length of each Gregorian month in a non-leap year
own month_length: sequence[int] := sequence[int]$[
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
]
own week_days: sequence[string] := sequence[string]$[
"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle",
"Setting Orange"
]
own seasons: sequence[string] := sequence[string]$[
"Chaos", "Discord", "Confusion", "Bureacuracy",
"The Aftermath"
]
own apostle_holydays: sequence[string] := sequence[string]$[
"Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"
]
own season_holydays: sequence[string] := sequence[string]$[
"Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"
]
% Check if a Gregorian year is a leap year
is_leap = proc (year: int) returns (bool)
if year // 4 ~= 0 then return(false)
elseif year // 100 ~= 0 then return(true)
elseif year // 400 ~= 0 then return(false)
else return(true)
end
end is_leap
% Convert a Gregorian date to a Discordian date
from_greg_y_m_d = proc (year, month, day: int)
returns (cvt) signals (invalid)
% Make sure the month is valid
if month<1 cor month>12 then signal invalid end
% Saint Tib's Day?
if month=2 cand day=29 then
% Only valid in leap years
if ~is_leap(year) then signal invalid end
return(rep${year: year+greyface, day: eris_day$make_st_tibs(nil)})
end
% If not, make sure the day of the month is valid
if day<1 cor day>month_length[month] then signal invalid end
% The Discordian calendar doesn't consider Saint Tib's Day
% part of a season, so we can use the day number for a non-leap
% year even in a leap year
year_day: int := (day + month_offset[month]) - 1
sd: season_day := season_day${
season: year_day / 73 + 1,
day: year_day // 73 + 1
}
return(rep${year: year+greyface,
day: eris_day$make_season_day(sd)})
end from_greg_y_m_d
% Convert a CLU 'date' object to a Discordian date (ignoring the time)
from_date = proc (d: date) returns (cvt) signals (invalid)
return(down(from_greg_y_m_d(d.year, d.month, d.day)))
resignal invalid
end from_date
% Retrieve year, season, day, weekday number
get_year = proc (d: cvt) returns (int) return(d.year) end get_year
get_day = proc (d: cvt) returns (int) signals (st_tibs)
tagcase d.day
tag st_tibs: signal st_tibs
tag season_day (s: season_day): return(s.day)
end
end get_day
get_season = proc (d: cvt) returns (int) signals (st_tibs)
tagcase d.day
tag st_tibs: signal st_tibs
tag season_day (s: season_day): return(s.season)
end
end get_season
get_weekday = proc (d: cvt) returns (int) signals (st_tibs)
day: int := up(d).day resignal st_tibs
season: int := up(d).season resignal st_tibs
weekday: int := ( (season-1)*73 + (day-1) ) // 5 + 1
return( weekday )
end get_weekday
% Retrieve formatted day in year
get_day_name = proc (d: cvt) returns (string)
begin
fmt: stream := stream$create_output()
stream$puts(fmt, week_days[up(d).weekday])
stream$puts(fmt, ", day " || int$unparse(up(d).day))
stream$puts(fmt, " of " || seasons[up(d).season])
return(stream$get_contents(fmt))
end except when st_tibs:
return("St. Tib's Day")
end
end get_day_name
% Retrieve holyday name if there is one
get_holyday = proc (d: cvt) returns (string) signals (no_holyday)
begin
if up(d).day = 5 then return(apostle_holydays[up(d).season])
elseif up(d).day = 50 then return(season_holydays[up(d).season])
else signal no_holyday
end
end except when st_tibs:
signal no_holyday % St. Tib's Day is not a normal holyday
end
end get_holyday
% Retrieve long format
get_format = proc (d: cvt) returns (string)
fmt: stream := stream$create_output()
stream$puts(fmt, up(d).day_name)
stream$puts(fmt, " in the YOLD ")
stream$puts(fmt, int$unparse(up(d).year))
stream$puts(fmt, ": celebrate " || up(d).holyday) except when no_holyday: end
return(stream$get_contents(fmt))
end get_format
end eris_date
% Parse a date string (MM/DD/YYYY) and return a date object
parse_date = proc (s: string) returns (date) signals (bad_format)
begin
parts: array[int] := array[int]$[]
while true do
slash: int := string$indexc('/', s)
if slash=0 then
array[int]$addh(parts, int$parse(s))
break
else
array[int]$addh(parts, int$parse(string$substr(s, 1, slash-1)))
s := string$rest(s, slash+1)
end
end
if array[int]$size(parts) ~= 3 then signal bad_format end
return(date$create(parts[2], parts[1], parts[3], 0, 0, 0))
end resignal bad_format
end parse_date
% Read date(s) from the command line, or use the current date,
% and convert to the Discordian date
start_up = proc ()
po: stream := stream$primary_output()
args: sequence[string] := get_argv()
dates: array[date] := array[date]$[]
if sequence[string]$empty(args) then
% No argument - use today's date
stream$puts(po, "Today is ")
array[date]$addh(dates, now())
else
% There are argument(s) - parse each of them
for arg: string in sequence[string]$elements(args) do
array[date]$addh(dates, parse_date(arg))
end
end
% Convert all dates
for d: date in array[date]$elements(dates) do
stream$putl(po, eris_date$from_date(d).format)
end
end start_up |
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)
| #Erlang | Erlang |
-module(dijkstra).
-include_lib("eunit/include/eunit.hrl").
-export([dijkstrafy/3]).
% just hide away recursion so we have a nice interface
dijkstrafy(Graph, Start, End) when is_map(Graph) ->
shortest_path(Graph, [{0, [Start]}], End, #{}).
shortest_path(_Graph, [], _End, _Visited) ->
% if we're not going anywhere, it's time to start going back
{0, []};
shortest_path(_Graph, [{Cost, [End | _] = Path} | _ ], End, _Visited) ->
% this is the base case, and finally returns the distance and the path
{Cost, lists:reverse(Path)};
shortest_path(Graph, [{Cost, [Node | _ ] = Path} | Routes], End, Visited) ->
% this is the recursive case.
% here we build a list of new "unvisited" routes, where the stucture is
% a tuple of cost, then a list of paths taken to get to that cost from the "Start"
NewRoutes = [{Cost + NewCost, [NewNode | Path]}
|| {NewCost, NewNode} <- maps:get(Node, Graph),
not maps:get(NewNode, Visited, false)],
shortest_path(
Graph,
% add the routes we ripped off earlier onto the new routes
% that we want to visit. sort the list of routes to get the
% shortest routes (lowest cost) at the beginning.
% Erlangs sort is already good enough, and it will sort the
% tuples by the number at the beginning of each (the cost).
lists:sort(NewRoutes ++ Routes),
End,
Visited#{Node => true}
).
basic_test() ->
Graph = #{
a => [{7,b},{9,c},{14,f}],
b => [{7,a},{10,c},{15,d}],
c => [{10,b},{9,c},{11,d},{2,f}],
d => [{15,b},{6,e},{11,c}],
e => [{9,f},{6,d}],
f => [{14,f},{2,c},{9,e}]
},
{Cost, Path} = dijkstrafy(Graph, a, e),
{20,[a,c,f,e]} = {Cost, Path},
io:format(user, "The total cost was ~p and the path was: ", [Cost]),
io:format(user, "~w~n", [Path]).
|
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
| #Clojure | Clojure |
(defn dig-root [value]
(let [digits (fn [n]
(map #(- (byte %) (byte \0))
(str n)))
sum (fn [nums]
(reduce + nums))]
(loop [n value
step 0]
(if (< n 10)
{:n value :add-persist step :digital-root n}
(recur (sum (digits n))
(inc step))))))
|
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #jq | jq | def do_until(condition; next):
def u: if condition then . else (next|u) end;
u;
def mdroot(n):
def multiply: reduce .[] as $i (1; .*$i);
# state: [mdr, persist]
[n, 0]
| do_until( .[0] < 10;
[(.[0] | tostring | explode | map(.-48) | multiply), .[1] + 1]
);
# Produce a table with 10 rows (numbered from 0),
# showing the first n numbers having the row-number as the mdr
def tabulate(n):
# state: [answer_matrix, next_i]
def tab:
def minlength: map(length) | min;
.[0] as $matrix
| .[1] as $i
| if (.[0]|minlength) == n then .[0]
else (mdroot($i) | .[0]) as $mdr
| if $matrix[$mdr]|length < n then
($matrix[$mdr] + [$i]) as $row
| $matrix | setpath([$mdr]; $row)
else $matrix
end
| [ ., $i + 1 ]
| tab
end;
[[], 0] | tab; |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Yabasic | Yabasic | w = 390 : h = int(w * 11 / 16)
open window w, h
level = 18 : insize = 247
x = 92 : y = 94
iters = 2^level
qiter = 510/iters
SQ = sqrt(2) : QPI = pi/4
rotation = 0 : iter = 0 : rq = 1.0
dim rqs(level)
color 0,0,0
clear window
dragon()
sub dragon()
if level<=0 then
yn = sin(rotation)*insize + y
xn = cos(rotation)*insize + x
if iter*2<iters then
color 0,iter*qiter,255-iter*qiter
else
color qiter*iter-255,(iters-iter)*qiter,0
end if
line x,y,xn,yn
iter = iter + 1
x = xn : y = yn
return
end if
insize = insize/SQ
rotation = rotation + rq*QPI
level = level - 1
rqs(level) = rq : rq = 1
dragon()
rotation = rotation - rqs(level)*QPI*2
rq = -1
dragon()
rq = rqs(level)
rotation = rotation + rq*QPI
level = level + 1
insize = insize*SQ
return
end sub |
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?
| #F.23 | F# |
// Dinesman's multiple-dwelling. Nigel Galloway: September 23rd., 2020
type names = |Baker=0 |Cooper=1 |Miller=2 |Smith=3 |Fletcher=4
let fN=Ring.PlainChanges [|for n in System.Enum.GetValues(typeof<names>)->n:?>names|]
let fG n g l=n|>Array.pairwise|>Array.forall(fun n->match n with (n,i) when (n=g && i=l)->false |(i,n) when (n=g && i=l)->false |_->true)
fN|>Seq.filter(fun n->n.[4]<>names.Baker && n.[0]<>names.Cooper && n.[0]<>names.Fletcher && n.[4]<>names.Fletcher && fG n names.Smith names.Fletcher
&& fG n names.Cooper names.Fletcher && (Array.findIndex((=)names.Cooper) n) < (Array.findIndex((=)names.Miller) n))
|>Seq.iter(Array.iteri(fun n g->printfn "%A lives on floor %d" g n))
|
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
| #Draco | Draco | proc nonrec dot_product([*] int a, b) int:
int total;
word i;
total := 0;
for i from 0 upto dim(a,1)-1 do
total := total + a[i] * b[i]
od;
total
corp
proc nonrec main() void:
[3] int a = (1, 3, -5);
[3] int b = (4, -2, -1);
write(dot_product(a, b))
corp |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Squeezable is
procedure Squeeze (S : in String; C : in Character) is
Res : String (1 .. S'Length);
Len : Natural := 0;
begin
Put_Line ("Character to be squeezed: '" & C & "'");
Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image);
for I in S'Range loop
if Len = 0 or else (S(I) /= Res(Len) or S(I) /= C) then
Len := Len + 1;
Res(Len) := S(I);
end if;
end loop;
Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image);
end Squeeze;
begin
Squeeze ("", ' ');
Squeeze ("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ", '-');
Squeeze ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7');
Squeeze ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.');
Squeeze (" --- Harry S Truman ", ' ');
Squeeze (" --- Harry S Truman ", '-');
Squeeze (" --- Harry S Truman ", 'r');
end Test_Squeezable;
|
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ring | Ring |
# Project : Doubly-linked list/Definition
test = [1, 5, 7, 0, 3, 2]
insert(test, 0, 9)
insert(test, len(test), 4)
item = len(test)/2
insert(test, item, 6)
showarray(test)
func showarray(vect)
svect = ""
for n = 1 to len(vect)
svect = svect + vect[n] + " "
next
svect = left(svect, len(svect) - 1)
see svect
|
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #ooRexx | ooRexx | Numeric Digits 30
Call test '9 4 6 6'
Call test '5 10 6 7'
Exit
test:
Parse Arg w1 s1 w2 s2
p1.=0
p2.=0
Call pp 1,w1,s1,p1.,p2.
Call pp 2,w2,s2,p1.,p2.
p2low.=0
Do x=w1 To w1*s1
Do y=0 To x-1
p2low.x+=p2.y
End
End
pwin1=0
Do x=w1 To w1*s1
pwin1+=p1.x*p2low.x
End
Say 'Player 1 has' w1 'dice with' s1 'sides each'
Say 'Player 2 has' w2 'dice with' s2 'sides each'
Say 'Probability for player 1 to win:' pwin1
Say ''
Return
pp: Procedure
/*---------------------------------------------------------------------
* Compute and assign probabilities to get a sum x
* when throwing w dice each having s sides (marked from 1 to s)
* k=1 sets p1.*, k=2 sets p2.*
*--------------------------------------------------------------------*/
Use Arg k,w,s,p1.,p2.
str=''
cnt.=0
Do wi=1 To w
str=str||'Do v'wi'=1 To' s';'
End
str=str||'sum='
Do wi=1 To w-1
str=str||'v'wi'+'
End
str=str||'v'w';'
str=str||'cnt.'sum'+=1;'
Do wi=1 To w
str=str||'End;'
End
Interpret str
psum=0
Do x=0 To w*s
If k=1 Then
p1.x=cnt.x/(s**w)
Else
p2.x=cnt.x/(s**w)
psum+=p1.x
End
Return |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Try {
Open "MYLOCK" For Output Exclusive As #F
Print "DO SOMETHING"
A$=Key$
Close#f
}
}
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | $Epilog := Print["Another instance is running "];
If[Attributes[Global`Mutex] == {Protected},
Exit[],
Global`Mutex[x_] := Locked; Protect[Global`Mutex];
] |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Nim | Nim | import os, posix
let fn = getHomeDir() & "rosetta-code-lock"
proc ooiUnlink {.noconv.} = discard unlink fn
proc onlyOneInstance =
var fl = TFlock(lType: F_WRLCK.cshort, lWhence: SEEK_SET.cshort)
var fd = getFileHandle fn.open fmReadWrite
if fcntl(fd, F_SETLK, addr fl) < 0:
stderr.writeLine "Another instance of this program is running"
quit 1
addQuitProc ooiUnlink
onlyOneInstance()
for i in countdown(10, 1):
echo i
sleep 1000
echo "Fin!" |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #OCaml | OCaml | open Sem
let () =
let oflags = [Unix.O_CREAT;
Unix.O_EXCL] in
let sem = sem_open "MyUniqueName" ~oflags () in
(* here the real code of the app *)
Unix.sleep 20;
(* end of the app *)
sem_unlink "MyUniqueName";
sem_close sem |
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.
| #Elixir | Elixir |
defmodule Philosopher do
defstruct missing: [], clean: [], promised: []
def run_demo do
pid1 = spawn(__MODULE__, :init, ["Russell"])
pid2 = spawn(__MODULE__, :init, ["Marx"])
pid3 = spawn(__MODULE__, :init, ["Spinoza"])
pid4 = spawn(__MODULE__, :init, ["Kant"])
pid5 = spawn(__MODULE__, :init, ["Aristotle"])
# a chopstick is simply represented by the pid of the neighbour that shares it.
send(pid1, {:run, %Philosopher{}})
send(pid2, {:run, %Philosopher{missing: [pid1]}})
send(pid3, {:run, %Philosopher{missing: [pid2]}})
send(pid4, {:run, %Philosopher{missing: [pid3]}})
send(pid5, {:run, %Philosopher{missing: [pid1, pid4]}})
end
def init(philosopher_name) do
receive do
{:run, state} ->
spawn(__MODULE__, :change_state, [self()])
case flip_coin() do
:heads -> thinking(philosopher_name, state)
:tails -> hungry(philosopher_name, state)
end
end
end
defp thinking(philosopher_name, state) do
receive do
{:change_state} ->
hungry(philosopher_name, state)
{:chopstick_request, pid} ->
if clean?(pid, state) do
thinking(philosopher_name, promise_chopstick(philosopher_name, pid, state))
else
give_chopstick(philosopher_name, self(), pid)
%{missing: missing} = state
thinking(philosopher_name, %{state | missing: [pid | missing]})
end
end
end
defp hungry(philosopher_name, state) do
IO.puts "#{philosopher_name} is hungry."
%{missing: missing} = state
for pid <- missing, do: request_chopstick(philosopher_name, self(), pid)
wait_for_chopsticks(philosopher_name, state)
end
defp wait_for_chopsticks(philosopher_name, state) do
if has_chopsticks?(state) do
eating(philosopher_name, state)
end
receive do
{:chopstick_request, pid} ->
if clean?(pid, state) do
wait_for_chopsticks(philosopher_name, promise_chopstick(philosopher_name, pid, state))
else
give_chopstick(philosopher_name, self(), pid)
request_chopstick(philosopher_name, self(), pid)
%{missing: missing} = state
wait_for_chopsticks(philosopher_name, %{state | missing: [pid | missing]})
end
{:chopstick_response, pid} ->
%{missing: missing, clean: clean} = state
wait_for_chopsticks(philosopher_name, %{state | missing: List.delete(missing, pid), clean: [pid | clean]})
end
end
defp eating(philosopher_name, state) do
IO.puts "*** #{philosopher_name} is eating."
receive do
{:change_state} ->
%{promised: promised} = state
for pid <- promised, do: give_chopstick(philosopher_name, self(), pid)
thinking(philosopher_name, %Philosopher{missing: promised})
end
end
defp clean?(pid, state) do
%{clean: clean} = state
Enum.member?(clean, pid)
end
defp has_chopsticks?(state) do
%{missing: missing} = state
Enum.empty?(missing)
end
defp promise_chopstick(philosopher_name, pid, state) do
IO.puts "#{philosopher_name} promises a chopstick."
%{promised: promised} = state
%{state | promised: [pid | promised]}
end
defp request_chopstick(philosopher_name, snd_pid, recv_pid) do
IO.puts "#{philosopher_name} requests a chopstick."
send(recv_pid, {:chopstick_request, snd_pid})
end
defp give_chopstick(philosopher_name, snd_pid, recv_pid) do
IO.puts "#{philosopher_name} gives a chopstick."
send(recv_pid, {:chopstick_response, snd_pid})
end
defp flip_coin do
case Enum.random(0..1) do
0 -> :heads
1 -> :tails
end
end
def change_state(pid) do
Process.sleep(Enum.random(1..10) * 1000)
send(pid, {:change_state})
change_state(pid)
end
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #D | D | import std.stdio, std.datetime, std.conv, std.string;
immutable seasons = ["Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"],
weekday = ["Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"],
apostle = ["Mungday", "Mojoday", "Syaday",
"Zaraday", "Maladay"],
holiday = ["Chaoflux", "Discoflux", "Confuflux",
"Bureflux", "Afflux"];
string discordianDate(in Date date) pure {
immutable dYear = text(date.year + 1166);
immutable isLeapYear = date.isLeapYear;
if (isLeapYear && date.month == 2 && date.day == 29)
return "St. Tib's Day, in the YOLD " ~ dYear;
immutable doy = (isLeapYear && date.dayOfYear >= 60) ?
date.dayOfYear - 1 :
date.dayOfYear;
immutable dsDay = (doy % 73)==0? 73:(doy % 73); // Season day.
if (dsDay == 5)
return apostle[doy / 73] ~ ", in the YOLD " ~ dYear;
if (dsDay == 50)
return holiday[doy / 73] ~ ", in the YOLD " ~ dYear;
immutable dSeas = seasons[(((doy%73)==0)?doy-1:doy) / 73];
immutable dWday = weekday[(doy - 1) % 5];
return format("%s, day %s of %s in the YOLD %s",
dWday, dsDay, dSeas, dYear);
}
unittest {
assert(Date(2010, 7, 22).discordianDate ==
"Pungenday, day 57 of Confusion in the YOLD 3176");
assert(Date(2012, 2, 28).discordianDate ==
"Prickle-Prickle, day 59 of Chaos in the YOLD 3178");
assert(Date(2012, 2, 29).discordianDate ==
"St. Tib's Day, in the YOLD 3178");
assert(Date(2012, 3, 1).discordianDate ==
"Setting Orange, day 60 of Chaos in the YOLD 3178");
assert(Date(2010, 1, 5).discordianDate ==
"Mungday, in the YOLD 3176");
assert(Date(2011, 5, 3).discordianDate ==
"Discoflux, in the YOLD 3177");
}
void main(string args[]) {
int yyyymmdd, day, mon, year, sign;
if (args.length == 1) {
(cast(Date)Clock.currTime).discordianDate.writeln;
return;
}
foreach (i, arg; args) {
if (i > 0) {
//writef("%d: %s: ", i, arg);
yyyymmdd = to!int(arg);
if (yyyymmdd < 0) {
sign = -1;
yyyymmdd = -yyyymmdd;
}
else {
sign = 1;
}
day = yyyymmdd % 100;
if (day == 0) {
day = 1;
}
mon = ((yyyymmdd - day) / 100) % 100;
if (mon == 0) {
mon = 1;
}
year = sign * ((yyyymmdd - day - 100*mon) / 10000);
writefln("%s", Date(year, mon, day).discordianDate);
}
}
} |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree.
This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex.
For instance
If the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities.
As a result, the shortest path first is widely used in network routing protocols, most notably:
IS-IS (Intermediate System to Intermediate System) and
OSPF (Open Shortest Path First).
Important note
The inputs to Dijkstra's algorithm are a directed and weighted graph consisting of 2 or more nodes, generally represented by:
an adjacency matrix or list, and
a start node.
A destination node is not specified.
The output is a set of edges depicting the shortest path to each destination node.
An example, starting with
a──►b, cost=7, lastNode=a
a──►c, cost=9, lastNode=a
a──►d, cost=NA, lastNode=a
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►b so a──►b is added to the output.
There is a connection from b──►d so the input is updated to:
a──►c, cost=9, lastNode=a
a──►d, cost=22, lastNode=b
a──►e, cost=NA, lastNode=a
a──►f, cost=14, lastNode=a
The lowest cost is a──►c so a──►c is added to the output.
Paths to d and f are cheaper via c so the input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
a──►f, cost=11, lastNode=c
The lowest cost is a──►f so c──►f is added to the output.
The input is updated to:
a──►d, cost=20, lastNode=c
a──►e, cost=NA, lastNode=a
The lowest cost is a──►d so c──►d is added to the output.
There is a connection from d──►e so the input is updated to:
a──►e, cost=26, lastNode=d
Which just leaves adding d──►e to the output.
The output should now be:
[ d──►e
c──►d
c──►f
a──►c
a──►b ]
Task
Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
Run your program with the following directed graph starting at node a.
Write a program which interprets the output from the above and use it to output the shortest path from node a to nodes e and f.
Vertices
Number
Name
1
a
2
b
3
c
4
d
5
e
6
f
Edges
Start
End
Cost
a
b
7
a
c
9
a
f
14
b
c
10
b
d
15
c
d
11
c
f
2
d
e
6
e
f
9
You can use numbers or names to identify vertices in your program.
See also
Dijkstra's Algorithm vs. A* Search vs. Concurrent Dijkstra's Algorithm (youtube)
| #F.23 | F# |
//Dijkstra's algorithm: Nigel Galloway, August 5th., 2018
[<CustomEquality;CustomComparison>]
type Dijkstra<'N,'G when 'G:comparison>={toN:'N;cost:Option<'G>;fromN:'N}
override g.Equals n =match n with| :? Dijkstra<'N,'G> as n->n.cost=g.cost|_->false
override g.GetHashCode() = hash g.cost
interface System.IComparable with
member n.CompareTo g =
match g with
| :? Dijkstra<'N,'G> as n when n.cost=None -> (-1)
| :? Dijkstra<'N,'G> when n.cost=None -> 1
| :? Dijkstra<'N,'G> as g -> compare n.cost g.cost
| _-> invalidArg "n" "expecting type Dijkstra<'N,'G>"
let inline Dijkstra N G y =
let rec fN l f=
if List.isEmpty l then f
else let n=List.min l
if n.cost=None then f else
fN(l|>List.choose(fun n'->if n'.toN=n.toN then None else match n.cost,n'.cost,Map.tryFind (n.toN,n'.toN) G with
|Some g,None,Some wg ->Some {toN=n'.toN;cost=Some(g+wg);fromN=n.toN}
|Some g,Some g',Some wg when g+wg<g'->Some {toN=n'.toN;cost=Some(g+wg);fromN=n.toN}
|_ ->Some n'))((n.fromN,n.toN)::f)
let r = fN (N|>List.map(fun n->{toN=n;cost=(Map.tryFind(y,n)G);fromN=y})) []
(fun n->let rec fN z l=match List.tryFind(fun (_,g)->g=z) r with
|Some(n',g') when y=n'->Some(n'::g'::l)
|Some(n',g') ->fN n' (g'::l)
|_ ->None
fN n [])
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #CLU | CLU | sum_digits = proc (n, base: int) returns (int)
sum: int := 0
while n > 0 do
sum := sum + n // base
n := n / base
end
return (sum)
end sum_digits
digital_root = proc (n, base: int) returns (int, int)
persistence: int := 0
while n >= base do
persistence := persistence + 1
n := sum_digits(n, base)
end
return (n, persistence)
end digital_root
start_up = proc ()
po: stream := stream$primary_output()
tests: array[int] := array[int]$[627615, 39390, 588225, 393900588225]
for test: int in array[int]$elements(tests) do
root, persistence: int := digital_root(test, 10)
stream$putl(po, int$unparse(test)
|| " has additive persistence "
|| int$unparse(persistence)
|| " and digital root of "
|| int$unparse(root))
end
end start_up |
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
| #Common_Lisp | Common Lisp | (defun digital-root (number &optional (base 10))
(loop for n = number then s
for ap = 1 then (1+ ap)
for s = (sum-digits n base)
when (< s base)
return (values s ap)))
(loop for (nr base) in '((627615 10) (393900588225 10) (#X14e344 16) (#36Rdg9r 36))
do (multiple-value-bind (dr ap) (digital-root nr base)
(format T "~vR (base ~a): additive persistence = ~a, digital root = ~vR~%"
base nr base ap base dr))) |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Julia | Julia |
function digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10)
-1 < n && 1 < bs || throw(DomainError())
ds = n
pers = 0
while bs <= ds
ds = prod(digits(ds, bs))
pers += 1
end
return (pers, ds)
end
|
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #zkl | zkl | println(0'|<?xml version='1.0' encoding='utf-8' standalone='no'?>|"\n"
0'|<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'|"\n"
0'|'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>|"\n"
0'|<svg width='100%' height='100%' version='1.1'|"\n"
0'|xmlns='http://www.w3.org/2000/svg'>|);
order:=13.0; # akin to number of recursion steps
d_size:=1000.0; # size in pixels
pi:=(1.0).pi;
turn_angle:=pi/2; # turn angle of each segment, 90 degrees for the canonical dragon
angle:=pi - (order * (pi/4)); # starting angle
len:=(d_size/1.5) / (2.0).sqrt().pow(order); # size of each segment
x:=d_size*5/6; y:=d_size*1/3; # starting point
foreach i in ([0 .. (2.0).pow(order-1)]){
# find which side to turn based on the iteration
angle += i.bitAnd(-i).shiftLeft(1).bitAnd(i) and -turn_angle or turn_angle;
dx:=x + len * angle.sin(); dy:=y - len * angle.cos();
println("<line x1='",x,"' y1='",y,"' x2='",dx,"' y2='",dy,
"' style='stroke:rgb(0,0,0);stroke-width:1'/>");
x=dx; y=dy;
}
println("</svg>"); |
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?
| #Factor | Factor | USING: kernel
combinators.short-circuit
math math.combinatorics math.ranges
sequences
qw prettyprint ;
IN: rosetta.dinesman
: /= ( x y -- ? ) = not ;
: fifth ( seq -- elt ) 4 swap nth ;
: meets-constraints? ( seq -- ? )
{
[ first 5 /= ] ! Baker does not live on the top floor.
[ second 1 /= ] ! Cooper does not live on the bottom floor.
[ third { 1 5 } member? not ] ! Fletcher does not live on either the top or bottom floor.
[ [ fourth ] [ second ] bi > ] ! Miller lives on a higher floor than does Cooper.
[ [ fifth ] [ third ] bi - abs 1 /= ] ! Smith does not live on a floor adjacent to Fletcher's.
[ [ third ] [ second ] bi - abs 1 /= ] ! Fletcher does not live on a floor adjacent to Cooper's.
} 1&& ;
: solutions ( -- seq )
5 [1,b] all-permutations [ meets-constraints? ] filter ;
: >names ( seq -- seq )
[ qw{ baker cooper fletcher miller smith } nth swap 2array ] map-index ;
: dinesman ( -- )
solutions [ >names . ] each ; |
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
| #EchoLisp | EchoLisp |
(define a #(1 3 -5))
(define b #(4 -2 -1))
;; function definition
(define ( ⊗ a b) (for/sum ((x a)(y b)) (* x y)))
(⊗ a b) → 3
;; library
(lib 'math)
(dot-product a b) → 3
|
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | BEGIN
# returns a squeezed version of s #
# i.e. s with adjacent duplicate c characters removed #
PRIO SQUEEZE = 9;
OP SQUEEZE = ( STRING s, CHAR c )STRING:
IF s = ""
THEN "" # empty string #
ELSE # non-empty string #
[ LWB s : UPB s ]CHAR result;
INT r pos := LWB result;
result[ r pos ] := s[ LWB s ];
FOR s pos FROM LWB s + 1 TO UPB s DO
IF result[ r pos ] /= s[ s pos ]
OR result[ r pos ] /= c
THEN
r pos +:= 1;
result[ r pos ] := s[ s pos ]
FI
OD;
result[ LWB result : r pos ]
FI # SQUEEZE # ;
# test the SQUEEZE operator #
PROC test squeeze = ( STRING s, CHAR c )VOID:
BEGIN
STRING z = s SQUEEZE c;
print( ( "Squeezing """, c, """ in ", "<<<", s, ">>> (length ", whole( ( UPB s + 1 ) - LWB s, 0 ), ")", newline ) );
print( ( " -> ", "<<<", z, ">>> (length ", whole( ( UPB z + 1 ) - LWB z, 0 ), ")", newline ) )
END # test squeeze # ;
# task test cases #
test squeeze( "", " " );
test squeeze( """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ", "-" );
test squeeze( "..1111111111111111111111111111111111111111111111111111111111111117777888", "7" );
test squeeze( "I never give 'em hell, I just tell the truth, and they think it's hell. ", "." );
STRING hst = " --- Harry S Truman ";
test squeeze( hst, " " );
test squeeze( hst, "-" );
test squeeze( hst, "r" )
END |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ruby | Ruby | (cond-expand
(r7rs)
(chicken (import r7rs)))
(import (scheme base))
(import (scheme write))
(import (scheme case-lambda))
(import (scheme process-context))
;; A doubly-linked list will be represented by a reference to any of
;; its nodes. This is possible because the "root node" is marked as
;; such.
(define-record-type <dllist>
(%dllist root? prev next element)
dllist?
(root? dllist-root?)
(prev dllist-prev %dllist-set-prev!)
(next dllist-next %dllist-set-next!)
(element %dllist-element))
(define (dllist-element node)
;; Get the element in a node. It is an error if the node is the
;; root.
(when (dllist-root? node)
(display "dllist-element of a root node\n" (current-error-port))
(exit 1))
(%dllist-element node))
(define (dllist . elements)
;; Make a doubly-linked list from the given elements.
(list->dllist elements))
(define (make-dllist)
;; Return a node marked as being a root, and which points to itself.
(let ((root (%dllist #t #f #f #f)))
(%dllist-set-prev! root root)
(%dllist-set-next! root root)
root))
(define (dllist-root node)
;; Given a reference to any node of a <dllist>, return a reference
;; to the list's root node.
(if (dllist-root? node)
node
(dllist-root (dllist-prev node))))
(define (dllist-insert-after! node element)
;; Insert an element after the given node, which may be either the
;; root or some other node.
(let* ((next-node (dllist-next node))
(new-node (%dllist #f node next-node element)))
(%dllist-set-next! node new-node)
(%dllist-set-prev! next-node new-node)))
(define (dllist-insert-before! node element)
;; Insert an element before the given node, which may be either the
;; root or some other node.
(let* ((prev-node (dllist-prev node))
(new-node (%dllist #f prev-node node element)))
(%dllist-set-next! prev-node new-node)
(%dllist-set-prev! node new-node)))
(define (dllist-remove! node)
;; Remove a node from a <dllist>. It is an error if the node is the
;; root.
(when (dllist-root? node)
(display "dllist-remove! of a root node\n" (current-error-port))
(exit 1))
(let ((prev (dllist-prev node))
(next (dllist-next node)))
(%dllist-set-next! prev next)
(%dllist-set-prev! next prev)))
(define dllist-make-generator
;; Make a thunk that returns the elements of the list, starting at
;; the root and going in either direction.
(case-lambda
((node) (dllist-make-generator node 1))
((node direction)
(if (negative? direction)
(let ((p (dllist-prev (dllist-root node))))
(lambda ()
(and (not (dllist-root? p))
(let ((element (dllist-element p)))
(set! p (dllist-prev p))
element))))
(let ((p (dllist-next (dllist-root node))))
(lambda ()
(and (not (dllist-root? p))
(let ((element (dllist-element p)))
(set! p (dllist-next p))
element))))))))
(define (list->dllist lst)
;; Make a doubly-linked list from the elements of an ordinary list.
(let loop ((node (make-dllist))
(lst lst))
(if (null? lst)
(dllist-next node)
(begin
(dllist-insert-after! node (car lst))
(loop (dllist-next node) (cdr lst))))))
(define (dllist->list node)
;; Make an ordinary list from the elements of a doubly-linked list.
(let loop ((lst '())
(node (dllist-prev (dllist-root node))))
(if (dllist-root? node)
lst
(loop (cons (dllist-element node) lst) (dllist-prev node)))))
;;;
;;; Some demonstration.
;;;
(define (print-it node)
(let ((gen (dllist-make-generator node)))
(do ((x (gen) (gen)))
((not x))
(display " ")
(write x))
(newline)))
(define dl (dllist 10 20 30 40 50))
(let ((gen (dllist-make-generator dl)))
(display "forwards generator: ")
(do ((x (gen) (gen)))
((not x))
(display " ")
(write x))
(newline))
(let ((gen (dllist-make-generator dl -1)))
(display "backwards generator:")
(do ((x (gen) (gen)))
((not x))
(display " ")
(write x))
(newline))
(display "insertion after the root: ")
(dllist-insert-after! dl 5)
(print-it dl)
(display "insertion before the root:")
(dllist-insert-before! dl 55)
(print-it dl)
(display "insertion after the second element:")
(dllist-insert-after! (dllist-next (dllist-next dl)) 15)
(print-it dl)
(display "insertion before the second from last element:")
(dllist-insert-before! (dllist-prev (dllist-prev dl)) 45)
(print-it dl)
(display "removal of the element 30:")
(let ((node (let loop ((node (dllist-next dl)))
(if (= (dllist-element node) 30)
node
(loop (dllist-next node))))))
(dllist-remove! node))
(print-it dl)
(display "any node can be used for the generator:")
(print-it (dllist-next (dllist-next (dllist-next dl))))
(display "conversion to a list: ")
(display (dllist->list dl))
(newline)
(display "conversion from a list:")
(print-it (list->dllist (list "a" "b" "c"))) |
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
| #11l | 11l | F collapse(s)
V cs = ‘’
V last = Char("\0")
L(c) s
I c != last
cs ‘’= c
last = c
R cs
V 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’
]
L(s) strings
V c = collapse(s)
print(‘original : length = ’s.len‘, string = <<<’s‘>>>’)
print(‘collapsed : length = ’c.len‘, string = <<<’c‘>>>’)
print() |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Perl | Perl | use List::Util qw(sum0 max);
sub comb {
my ($s, $n) = @_;
$n || return (1);
my @r = (0) x ($n - max(@$s) + 1);
my @c = comb($s, $n - 1);
foreach my $i (0 .. $#c) {
$c[$i] || next;
foreach my $k (@$s) {
$r[$i + $k] += $c[$i];
}
}
return @r;
}
sub winning {
my ($s1, $n1, $s2, $n2) = @_;
my @p1 = comb($s1, $n1);
my @p2 = comb($s2, $n2);
my ($win, $loss, $tie) = (0, 0, 0);
foreach my $i (0 .. $#p1) {
$win += $p1[$i] * sum0(@p2[0 .. $i - 1]);
$tie += $p1[$i] * sum0(@p2[$i .. $i ]);
$loss += $p1[$i] * sum0(@p2[$i+1 .. $#p2 ]);
}
my $total = sum0(@p1) * sum0(@p2);
map { $_ / $total } ($win, $tie, $loss);
}
print '(', join(', ', winning([1 .. 4], 9, [1 .. 6], 6)), ")\n";
print '(', join(', ', winning([1 .. 10], 5, [1 .. 7], 6)), ")\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
| #11l | 11l | F analyze(s)
print(‘Examining [’s‘] which has a length of ’s.len‘:’)
I s.len > 1
V b = s[0]
L(c) s
V i = L.index
I c != b
print(‘ Not all characters in the string are the same.’)
print(‘ '’c‘' (0x’hex(c.code)‘) is different at position ’i)
R
print(‘ All characters in the string are the same.’)
V strs = [‘’, ‘ ’, ‘2’, ‘333’, ‘.55’, ‘tttTTT’, ‘4444 444k’]
L(s) strs
analyze(s) |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Oz | Oz | functor
import Application Open System
define
fun {IsAlreadyRunning}
try
S = {New Open.socket init}
in
{S bind(takePort:12345)}
false
catch system(os(os "bind" ...) ...) then
true
end
end
if {IsAlreadyRunning} then
{System.showInfo "Exiting because already running."}
{Application.exit 1}
end
{System.showInfo "Press enter to exit."}
{{New Open.file init(name:stdin)} read(list:_ size:1)}
{Application.exit 0}
end |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Perl | Perl | use Fcntl ':flock';
INIT
{
die "Not able to open $0\n" unless (open ME, $0);
die "I'm already running !!\n" unless(flock ME, LOCK_EX|LOCK_NB);
}
sleep 60; # then your code goes here |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Phix | Phix | -- demo\rosetta\Single_instance.exw
without js
include pGUI.e
function copydata_cb(Ihandle /*ih*/, atom pCommandLine, integer size)
-- (the first instance is sent a copy of the second one's command line)
printf(1,"COPYDATA(%s, %d)\n",{peek_string(pCommandLine), size});
return IUP_DEFAULT;
end function
IupOpen()
IupSetGlobal("SINGLEINSTANCE", "Single") -- (must [partially] match the main window title)
if IupGetGlobal("SINGLEINSTANCE")!="" then
Ihandle dlg = IupDialog(IupVbox({IupLabel("hello")},"MARGIN=200x200"))
IupSetAttribute(dlg,"TITLE","Single Instance")
IupSetCallback(dlg, "COPYDATA_CB", Icallback("copydata_cb"));
IupShow(dlg)
IupMainLoop()
end if
IupClose()
|
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.
| #Erlang | Erlang |
%%%
%%% to compile and run:
%%% $ erl
%%% > c(rosetta).
%%% {ok,rosetta}
%%% > rosetta:dining().
%%%
%%% contributor: bksteele
%%%
-module(rosetta).
-export([dining/0]).
sleep(T) ->
receive
after T ->
true
end.
doForks(ForkList) ->
receive
{grabforks, {Left, Right}} ->
doForks(ForkList -- [Left, Right]);
{releaseforks, {Left, Right}} ->
doForks([Left, Right| ForkList]);
{available, {Left, Right}, Sender} ->
Sender ! {areAvailable,
lists:member(Left, ForkList)
andalso lists:member(Right, ForkList)},
doForks(ForkList);
{die} -> io:format("Forks put away.~n")
end.
areAvailable(Forks) ->
forks ! {available, Forks, self()},
receive
{areAvailable, false} -> false;
{areAvailable, true} -> true
end.
processWaitList([]) -> false;
processWaitList([H|T]) ->
{Client, Forks} = H,
case areAvailable(Forks) of
true -> Client ! {served},
true;
false -> processWaitList(T)
end.
doWaiter([], 0, 0, false) ->
forks ! {die},
io:format("Waiter is leaving.~n"),
diningRoom ! {allgone};
doWaiter(WaitList, ClientCount, EatingCount, Busy) ->
receive
{waiting, Client} ->
WaitList1 = [Client|WaitList],
% add to waiting list
case (not Busy) and (EatingCount<2) of
true ->
Busy1 = processWaitList(WaitList1);
false -> Busy1 = Busy
end,
doWaiter(WaitList1, ClientCount, EatingCount, Busy1);
{eating, Client} ->
doWaiter(WaitList -- [Client], ClientCount, EatingCount+1, false);
{finished} ->
doWaiter(WaitList, ClientCount, EatingCount-1,
processWaitList(WaitList));
{leaving} ->
doWaiter(WaitList, ClientCount-1, EatingCount, Busy)
end.
philosopher(Name, _Forks, 0) ->
io:format("~s is leaving.~n", [Name]),
waiter ! {leaving};
philosopher(Name, Forks, Cycle) ->
io:format("~s is thinking.~n", [Name]),
sleep(rand:uniform(1000)),
io:format("~s is hungry.~n", [Name]),
% sit at table
waiter ! {waiting, {self(), Forks}},
receive
{served} -> forks ! {grabforks, Forks},
% grab forks
waiter ! {eating, {self(), Forks}},
% start eating
io:format("~s is eating.~n", [Name])
end,
sleep(rand:uniform(1000)),
% put forks down
forks ! {releaseforks, Forks},
waiter ! {finished},
philosopher(Name, Forks, Cycle-1).
dining() -> AllForks = [1, 2, 3, 4, 5],
Clients = 5,
register(diningRoom, self()),
register(forks,
spawn(fun() -> doForks(AllForks) end)),
register(waiter,
spawn(fun() -> doWaiter([], Clients, 0, false) end)),
% run for 7 cycles
Life_span = 7,
spawn(fun() -> philosopher('Aristotle', {5, 1}, Life_span) end),
spawn(fun() -> philosopher('Kant', {1, 2}, Life_span) end),
spawn(fun() -> philosopher('Spinoza', {2, 3}, Life_span) end),
spawn(fun() -> philosopher('Marx', {3, 4}, Life_span) end),
spawn(fun() -> philosopher('Russell', {4, 5}, Life_span) end),
receive
{allgone} -> io:format("Dining room closed.~n")
end,
unregister(diningRoom).
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Delphi | Delphi |
program Discordian_date;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.DateUtils;
type
TDateTimeHelper = record helper for TDateTime
const
seasons: array of string = ['Chaos', 'Discord', 'Confusion', 'Bureaucracy',
'The Aftermath'];
weekday: array of string = ['Sweetmorn', 'Boomtime', 'Pungenday',
'Prickle-Prickle', 'Setting Orange'];
apostle: array of string = ['Mungday', 'Mojoday', 'Syaday', 'Zaraday', 'Maladay'];
holiday: array of string = ['Chaoflux', 'Discoflux', 'Confuflux',
'Bureflux', 'Afflux'];
function DiscordianDate(): string;
end;
{ TDateTimeHelper }
function TDateTimeHelper.DiscordianDate: string;
var
isLeapYear: boolean;
begin
isLeapYear := IsInLeapYear(self);
var dYear := (YearOf(self) + 1166).ToString;
if isLeapYear and (MonthOf(self) = 2) and (dayof(self) = 29) then
exit('St. Tib''s Day, in the YOLD ' + dYear);
var doy := DayOfTheYear(self);
if isLeapYear and (doy >= 60) then
doy := doy - 1;
var dsDay := doy mod 73;
if dsDay = 0 then
dsDay := 73;
if dsDay = 5 then
exit(apostle[doy div 73] + ', in the YOLD ' + dYear);
if dsDay = 50 then
exit(holiday[doy div 73] + ', in the YOLD ' + dYear);
var dSeas: string;
if (doy mod 73) = 0 then
dSeas := seasons[(doy - 1) div 73]
else
dSeas := seasons[doy div 73];
var dWday := weekday[(doy - 1) mod 5];
Result := format('%s, day %d of %s in the YOLD %s', [dWday, dsDay, dSeas, dYear]);
end;
procedure Test();
begin
Assert(EncodeDate(2010, 7, 22).DiscordianDate =
'Pungenday, day 57 of Confusion in the YOLD 3176');
Assert(EncodeDate(2012, 2, 28).DiscordianDate =
'Prickle-Prickle, day 59 of Chaos in the YOLD 3178');
Assert(EncodeDate(2012, 2, 29).DiscordianDate = 'St. Tib''s Day, in the YOLD 3178');
Assert(EncodeDate(2012, 3, 1).DiscordianDate =
'Setting Orange, day 60 of Chaos in the YOLD 3178');
Assert(EncodeDate(2010, 1, 5).DiscordianDate = 'Mungday, in the YOLD 3176');
Assert(EncodeDate(2011, 5, 3).DiscordianDate = 'Discoflux, in the YOLD 3177');
writeln('OK');
end;
var
dt: TDateTime;
i: Integer;
begin
if ParamCount = 0 then
begin
writeln(now.DiscordianDate);
readln;
halt;
end;
for i := 1 to ParamCount do
begin
if not TryStrToDate(ParamStr(i), dt) then
Continue;
writeln(dt.DiscordianDate);
end;
readln;
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)
| #Go | Go | package main
import (
"container/heap"
"fmt"
)
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue struct {
items []Vertex
m map[Vertex]int // value to index
pr map[Vertex]int // value to priority
}
func (pq *PriorityQueue) Len() int { return len(pq.items) }
func (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }
func (pq *PriorityQueue) Swap(i, j int) {
pq.items[i], pq.items[j] = pq.items[j], pq.items[i]
pq.m[pq.items[i]] = i
pq.m[pq.items[j]] = j
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(pq.items)
item := x.(Vertex)
pq.m[item] = n
pq.items = append(pq.items, item)
}
func (pq *PriorityQueue) Pop() interface{} {
old := pq.items
n := len(old)
item := old[n-1]
pq.m[item] = -1
pq.items = old[0 : n-1]
return item
}
// update modifies the priority of an item in the queue.
func (pq *PriorityQueue) update(item Vertex, priority int) {
pq.pr[item] = priority
heap.Fix(pq, pq.m[item])
}
func (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {
heap.Push(pq, item)
pq.update(item, priority)
}
const (
Infinity = int(^uint(0) >> 1)
Uninitialized = -1
)
func Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {
vs := g.Vertices()
dist = make(map[Vertex]int, len(vs))
prev = make(map[Vertex]Vertex, len(vs))
sid := source
dist[sid] = 0
q := &PriorityQueue{
items: make([]Vertex, 0, len(vs)),
m: make(map[Vertex]int, len(vs)),
pr: make(map[Vertex]int, len(vs)),
}
for _, v := range vs {
if v != sid {
dist[v] = Infinity
}
prev[v] = Uninitialized
q.addWithPriority(v, dist[v])
}
for len(q.items) != 0 {
u := heap.Pop(q).(Vertex)
for _, v := range g.Neighbors(u) {
alt := dist[u] + g.Weight(u, v)
if alt < dist[v] {
dist[v] = alt
prev[v] = u
q.update(v, alt)
}
}
}
return dist, prev
}
// A Graph is the interface implemented by graphs that
// this algorithm can run on.
type Graph interface {
Vertices() []Vertex
Neighbors(v Vertex) []Vertex
Weight(u, v Vertex) int
}
// Nonnegative integer ID of vertex
type Vertex int
// sg is a graph of strings that satisfies the Graph interface.
type sg struct {
ids map[string]Vertex
names map[Vertex]string
edges map[Vertex]map[Vertex]int
}
func newsg(ids map[string]Vertex) sg {
g := sg{ids: ids}
g.names = make(map[Vertex]string, len(ids))
for k, v := range ids {
g.names[v] = k
}
g.edges = make(map[Vertex]map[Vertex]int)
return g
}
func (g sg) edge(u, v string, w int) {
if _, ok := g.edges[g.ids[u]]; !ok {
g.edges[g.ids[u]] = make(map[Vertex]int)
}
g.edges[g.ids[u]][g.ids[v]] = w
}
func (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {
s = g.names[v]
for prev[v] >= 0 {
v = prev[v]
s = g.names[v] + s
}
return s
}
func (g sg) Vertices() []Vertex {
vs := make([]Vertex, 0, len(g.ids))
for _, v := range g.ids {
vs = append(vs, v)
}
return vs
}
func (g sg) Neighbors(u Vertex) []Vertex {
vs := make([]Vertex, 0, len(g.edges[u]))
for v := range g.edges[u] {
vs = append(vs, v)
}
return vs
}
func (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }
func main() {
g := newsg(map[string]Vertex{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5,
"f": 6,
})
g.edge("a", "b", 7)
g.edge("a", "c", 9)
g.edge("a", "f", 14)
g.edge("b", "c", 10)
g.edge("b", "d", 15)
g.edge("c", "d", 11)
g.edge("c", "f", 2)
g.edge("d", "e", 6)
g.edge("e", "f", 9)
dist, prev := Dijkstra(g, g.ids["a"])
fmt.Printf("Distance to %s: %d, Path: %s\n", "e", dist[g.ids["e"]], g.path(g.ids["e"], prev))
fmt.Printf("Distance to %s: %d, Path: %s\n", "f", dist[g.ids["f"]], g.path(g.ids["f"], prev))
} |
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
| #Component_Pascal | Component Pascal |
MODULE DigitalRoot;
IMPORT StdLog, Strings, TextMappers, DevCommanders;
PROCEDURE CalcDigitalRoot(x: LONGINT; OUT dr,pers: LONGINT);
VAR
str: ARRAY 64 OF CHAR;
i: INTEGER;
BEGIN
dr := 0;pers := 0;
LOOP
Strings.IntToString(x,str);
IF LEN(str$) = 1 THEN dr := x ;EXIT END;
i := 0;dr := 0;
WHILE (i < LEN(str$)) DO
INC(dr,ORD(str[i]) - ORD('0'));
INC(i)
END;
INC(pers);
x := dr
END;
END CalcDigitalRoot;
PROCEDURE Do*;
VAR
dr,pers: LONGINT;
s: TextMappers.Scanner;
BEGIN
s.ConnectTo(DevCommanders.par.text);
s.SetPos(DevCommanders.par.beg);
REPEAT
s.Scan;
IF (s.type = TextMappers.int) OR (s.type = TextMappers.lint) THEN
CalcDigitalRoot(s.int,dr,pers);
StdLog.Int(s.int);
StdLog.String(" Digital root: ");StdLog.Int(dr);
StdLog.String(" Persistence: ");StdLog.Int(pers);StdLog.Ln
END
UNTIL s.rider.eot;
END Do;
END DigitalRoot.
|
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Kotlin | Kotlin | // version 1.1.2
fun multDigitalRoot(n: Int): Pair<Int, Int> = when {
n < 0 -> throw IllegalArgumentException("Negative numbers not allowed")
else -> {
var mdr: Int
var mp = 0
var nn = n
do {
mdr = if (nn > 0) 1 else 0
while (nn > 0) {
mdr *= nn % 10
nn /= 10
}
mp++
nn = mdr
}
while (mdr >= 10)
Pair(mdr, mp)
}
}
fun main(args: Array<String>) {
val ia = intArrayOf(123321, 7739, 893, 899998)
for (i in ia) {
val (mdr, mp) = multDigitalRoot(i)
println("${i.toString().padEnd(9)} MDR = $mdr MP = $mp")
}
println()
println("MDR n0 n1 n2 n3 n4")
println("=== ===========================")
val ia2 = Array(10) { IntArray(6) } // all zero by default
var n = 0
var count = 0
do {
val (mdr, _) = multDigitalRoot(n)
if (ia2[mdr][0] < 5) {
ia2[mdr][0]++
ia2[mdr][ia2[mdr][0]] = n
count++
}
n++
}
while (count < 50)
for (i in 0..9) {
print("$i:")
for (j in 1..5) print("%6d".format(ia2[i][j]))
println()
}
} |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET level=15: LET insize=120
20 LET x=80: LET y=70
30 LET iters=2^level
40 LET qiter=256/iters
50 LET sq=SQR (2): LET qpi=PI/4
60 LET rotation=0: LET iter=0: LET rq=1
70 DIM r(level)
75 GO SUB 80: STOP
80 REM Dragon
90 IF level>1 THEN GO TO 200
100 LET yn=SIN (rotation)*insize+y
110 LET xn=COS (rotation)*insize+x
120 PLOT x,y: DRAW xn-x,yn-y
130 LET iter=iter+1
140 LET x=xn: LET y=yn
150 RETURN
200 LET insize=insize/sq
210 LET rotation=rotation+rq*qpi
220 LET level=level-1
230 LET r(level)=rq: LET rq=1
240 GO SUB 80
250 LET rotation=rotation-r(level)*qpi*2
260 LET rq=-1
270 GO SUB 80
280 LET rq=r(level)
290 LET rotation=rotation+rq*qpi
300 LET level=level+1
310 LET insize=insize*sq
320 RETURN |
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?
| #Forth | Forth | 0 enum baker \ enumeration of all tenants
enum cooper
enum fletcher
enum miller
constant smith
create names \ names of all the tenants
," Baker"
," Cooper"
," Fletcher"
," Miller"
," Smith" \ get name, type it
does> swap cells + @c count type ." lives in " ;
5 constant #floor \ number of floors
#floor 1- constant top \ top floor
0 constant bottom \ we're counting the floors from 0
: num@ c@ [char] 0 - ; ( a -- n)
: floor chars over + num@ ; ( a n1 -- a n2)
\ is it a valid permutation?
: perm? ( n -- a f)
#floor base ! 0 swap s>d <# #floor 0 ?do # loop #>
over >r bounds do 1 i num@ lshift + loop
31 = r> swap decimal \ create binary mask and check
;
\ test a solution
: solution? ( a -- a f)
baker floor top <> \ baker on top floor?
if cooper floor bottom <> \ cooper on the bottom floor?
if fletcher floor dup bottom <> swap top <> and
if cooper floor swap miller floor rot >
if smith floor swap fletcher floor rot - abs 1 <>
if cooper floor swap fletcher floor rot - abs 1 <>
if true exit then \ we found a solution!
then
then
then
then
then false \ nice try, no cigar..
;
( a --)
: .solution #floor 0 do i names i chars over + c@ 1+ emit cr loop drop ;
\ main routine
: dinesman ( --)
2932 194 do
i perm? if solution? if .solution leave else drop then else drop then
loop
; \ show the solution
dinesman |
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
| #Eiffel | Eiffel | class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
print(dot_product(<<1, 3, -5>>, <<4, -2, -1>>).out)
end
feature -- Access
dot_product (a, b: ARRAY[INTEGER]): INTEGER
-- Dot product of vectors `a' and `b'.
require
a.lower = b.lower
a.upper = b.upper
local
i: INTEGER
do
from
i := a.lower
until
i > a.upper
loop
Result := Result + a[i] * b[i]
i := i + 1
end
end
end |
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
| #APL | APL | task←{
⍝ Squeeze a string
squeeze ← ⊢(/⍨)≠∨1,1↓⊣≠¯1⌽⊢
⍝ Display string and length in the manner given in the task
display ← {(¯2↑⍕≢⍵),' «««',⍵,'»»»'}
⍝ Squeeze string and display output
show ← {
r← ⊂'chr: ''',⍺,''''
r←r,⊂' in: ',display ⍵
r←r,⊂'out: ',display ⍺ squeeze ⍵
↑r,⊂''
}
⍝ Strings from the task
s1←''
s2←'"If I were two-faced, would I be wearing this one?"'
s2←s2,' --- Abraham Lincoln '
s3←'..1111111111111111111111111111111111111111111111111'
s3←s3,'111111111111117777888'
s4←'I never give ''em hell, I just tell the truth, and t'
s4←s4,'hey think it''s hell. '
s5←' '
s5←s5,' --- Harry S Truman '
⎕←' ' show s1
⎕←'-' show s2
⎕←'7' show s3
⎕←'.' show s4
{⎕←⍵ show s5}¨' -r' ⍝⍝ note use of 'show' here in a lambda (dfn)
} |
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
| #AutoHotkey | AutoHotkey | squeezable_string(str, char){
for i, ch in StrSplit(str){
if (ch <> prev) || !InStr(ch, char)
res .= ch
prev := ch
}
result := "
(ltrim
Original string:`t" StrLen(str) " characters`t«««" str "»»»
Squeezable Character «««" char "»»»
Resultant string:`t" StrLen(res) " characters`t«««" res "»»»
)"
return result
} |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Scheme | Scheme | (cond-expand
(r7rs)
(chicken (import r7rs)))
(import (scheme base))
(import (scheme write))
(import (scheme case-lambda))
(import (scheme process-context))
;; A doubly-linked list will be represented by a reference to any of
;; its nodes. This is possible because the "root node" is marked as
;; such.
(define-record-type <dllist>
(%dllist root? prev next element)
dllist?
(root? dllist-root?)
(prev dllist-prev %dllist-set-prev!)
(next dllist-next %dllist-set-next!)
(element %dllist-element))
(define (dllist-element node)
;; Get the element in a node. It is an error if the node is the
;; root.
(when (dllist-root? node)
(display "dllist-element of a root node\n" (current-error-port))
(exit 1))
(%dllist-element node))
(define (dllist . elements)
;; Make a doubly-linked list from the given elements.
(list->dllist elements))
(define (make-dllist)
;; Return a node marked as being a root, and which points to itself.
(let ((root (%dllist #t #f #f #f)))
(%dllist-set-prev! root root)
(%dllist-set-next! root root)
root))
(define (dllist-root node)
;; Given a reference to any node of a <dllist>, return a reference
;; to the list's root node.
(if (dllist-root? node)
node
(dllist-root (dllist-prev node))))
(define (dllist-insert-after! node element)
;; Insert an element after the given node, which may be either the
;; root or some other node.
(let* ((next-node (dllist-next node))
(new-node (%dllist #f node next-node element)))
(%dllist-set-next! node new-node)
(%dllist-set-prev! next-node new-node)))
(define (dllist-insert-before! node element)
;; Insert an element before the given node, which may be either the
;; root or some other node.
(let* ((prev-node (dllist-prev node))
(new-node (%dllist #f prev-node node element)))
(%dllist-set-next! prev-node new-node)
(%dllist-set-prev! node new-node)))
(define (dllist-remove! node)
;; Remove a node from a <dllist>. It is an error if the node is the
;; root.
(when (dllist-root? node)
(display "dllist-remove! of a root node\n" (current-error-port))
(exit 1))
(let ((prev (dllist-prev node))
(next (dllist-next node)))
(%dllist-set-next! prev next)
(%dllist-set-prev! next prev)))
(define dllist-make-generator
;; Make a thunk that returns the elements of the list, starting at
;; the root and going in either direction.
(case-lambda
((node) (dllist-make-generator node 1))
((node direction)
(if (negative? direction)
(let ((p (dllist-prev (dllist-root node))))
(lambda ()
(and (not (dllist-root? p))
(let ((element (dllist-element p)))
(set! p (dllist-prev p))
element))))
(let ((p (dllist-next (dllist-root node))))
(lambda ()
(and (not (dllist-root? p))
(let ((element (dllist-element p)))
(set! p (dllist-next p))
element))))))))
(define (list->dllist lst)
;; Make a doubly-linked list from the elements of an ordinary list.
(let loop ((node (make-dllist))
(lst lst))
(if (null? lst)
(dllist-next node)
(begin
(dllist-insert-after! node (car lst))
(loop (dllist-next node) (cdr lst))))))
(define (dllist->list node)
;; Make an ordinary list from the elements of a doubly-linked list.
(let loop ((lst '())
(node (dllist-prev (dllist-root node))))
(if (dllist-root? node)
lst
(loop (cons (dllist-element node) lst) (dllist-prev node)))))
;;;
;;; Some demonstration.
;;;
(define (print-it node)
(let ((gen (dllist-make-generator node)))
(do ((x (gen) (gen)))
((not x))
(display " ")
(write x))
(newline)))
(define dl (dllist 10 20 30 40 50))
(let ((gen (dllist-make-generator dl)))
(display "forwards generator: ")
(do ((x (gen) (gen)))
((not x))
(display " ")
(write x))
(newline))
(let ((gen (dllist-make-generator dl -1)))
(display "backwards generator:")
(do ((x (gen) (gen)))
((not x))
(display " ")
(write x))
(newline))
(display "insertion after the root: ")
(dllist-insert-after! dl 5)
(print-it dl)
(display "insertion before the root:")
(dllist-insert-before! dl 55)
(print-it dl)
(display "insertion after the second element:")
(dllist-insert-after! (dllist-next (dllist-next dl)) 15)
(print-it dl)
(display "insertion before the second from last element:")
(dllist-insert-before! (dllist-prev (dllist-prev dl)) 45)
(print-it dl)
(display "removal of the element 30:")
(let ((node (let loop ((node (dllist-next dl)))
(if (= (dllist-element node) 30)
node
(loop (dllist-next node))))))
(dllist-remove! node))
(print-it dl)
(display "any node can be used for the generator:")
(print-it (dllist-next (dllist-next (dllist-next dl))))
(display "conversion to a list: ")
(display (dllist->list dl))
(newline)
(display "conversion from a list:")
(print-it (list->dllist (list "a" "b" "c"))) |
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
| #8080_Assembly | 8080 Assembly | bdos: equ 5
puts: equ 9
org 100h
jmp main
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Collapse the $-terminated string at [HL]
colaps: mov b,m ; B = last character seen
inx h ; First character never collapses
mov d,h ; DE = output pointer
mov e,l
mov a,b ; Empty string?
cpi '$'
rz ; Then do nothing
cloop: mov a,m ; Get character
inx h ; Advance pointer
cmp b ; Same as last one?
jz cloop ; Then keep scanning
mov b,a ; Otherwise, it is a new one
stax d ; Store it,
inx d ; and increment output pointer.
cpi '$' ; Reached the end?
jnz cloop ; If not, next character
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code to print the output in the required format
main: lxi h,strs ; List of string pointers
loop: mov e,m ; DE = string pointer
inx h
mov d,m
inx h
mov a,e ; If zero, end
ora d
rz
push h ; Keep the list pointer
push d ; Keep the string pointer
call brstr ; Print original string in brackets
pop h ; Retrieve string pointer
push h
call colaps ; Collapse the string
pop d ; Retrieve string pointer
call brstr ; Print the collapsed string in brackets
pop h ; Retrieve the list pointer
jmp loop ; Next string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print string at DE in brackets with length
brstr: push d ; Store string pointer
mvi c,puts ; Print opening brackets
lxi d,open
call bdos
pop d ; Print original string
push d
mvi c,puts
call bdos
mvi c,puts ; Print closing brackets
lxi d,close
call bdos
pop h
call strlen ; Find string length
mov a,b
jmp prnum ; Print string length
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Figure out the length of a string (max 255)
strlen: mvi b,0 ; Counter
mvi a,'$' ; Terminator
sloop: cmp m ; Reached the end yet?
rz ; If so, stop
inr b ; If not, increment counter,
inx h ; and pointer,
jmp sloop ; and check next byte.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Print number in A as decimal
prnum: lxi d,num ; End of number string
prdgt: mvi b,-1 ; Quotient
ploop: inr b ; Increment quotient
sui 10 ; Subtract 10
jnc ploop ; Subtract until negative
adi '0'+10 ; Make ASCII digit
dcx d ; Store in number string
stax d
mov a,b ; If more digits,
ana a
jnz prdgt ; find next digit
mvi c,puts ; When done, print string
jmp bdos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Formatting strings
open: db '<<<$'
close: db '>>> $'
db '***'
num: db 13,10,'$'
;;; Input strings
strs: dw str1,str2,str3,str4,str5,0
str1: db '$' ; Empty string
str2: db '"If I were two-faced, would I be wearing '
db 'this one?" --- Abraham Lincoln $'
str3: db '..111111111111111111111111111111111111111'
db '1111111111111111111111117777888$'
str4: db 'I never give ',39,'em hell, I just tell the truth, '
db 'and they think it',39,'s hell. $'
str5: db ' '
db ' --- Harry S Truman $' |
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
| #Action.21 | Action! | PROC Collapse(CHAR ARRAY in,out)
BYTE i,j
CHAR c
j=1 c=0
FOR i=1 TO in(0)
DO
IF in(i)#c THEN
c=in(i)
out(j)=c
j==+1
FI
OD
out(0)=j-1
RETURN
PROC Test(CHAR ARRAY s)
CHAR ARRAY c(100)
BYTE CH=$02FC ;Internal hardware value for last key pressed
Collapse(s,c)
PrintF("<<<%S>>> (len=%B)%E",s,s(0))
PrintF("<<<%S>>> (len=%B)%E",c,c(0))
PutE()
PrintE("Press any key to continue")
PutE()
DO UNTIL CH#$FF OD
CH=$FF
RETURN
PROC Main()
Test("")
Test("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ")
Test("..1111111111111111111111111111111111111111111111111111111111111117777888")
Test("I never give 'em hell, I just tell the truth, and they think it's hell. ")
Test(" --- Harry S Truman ")
RETURN |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #Phix | Phix | with javascript_semantics
function throwDie(integer nSides, nDice, s, sequence counts)
if nDice == 0 then
counts[s] += 1
else
for i=1 to nSides do
counts = throwDie(nSides, nDice-1, s+i, counts)
end for
end if
return counts
end function
function beatingProbability(integer nSides1, nDice1, nSides2, nDice2)
integer len1 := (nSides1 + 1) * nDice1,
len2 := (nSides2 + 1) * nDice2
sequence c1 = throwDie(nSides1, nDice1, 0, repeat(0,len1)),
c2 = throwDie(nSides2, nDice2, 0, repeat(0,len2))
atom p12 := power(nSides1, nDice1) * power(nSides2, nDice2),
tot := 0.0
for i=1 to len1 do
for j=1 to min(i-1,len2) do
tot += (c1[i] * c2[j]) / p12
end for
end for
return tot
end function
printf(1,"%0.16f\n",beatingProbability(4, 9, 6, 6))
printf(1,"%0.16f\n",beatingProbability(10, 5, 7, 6))
|
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Action.21 | Action! | PROC PrintBH(BYTE a)
BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]
Put(hex(a RSH 4))
Put(hex(a&$0F))
RETURN
PROC Test(CHAR ARRAY s)
BYTE i,pos
pos=0
FOR i=2 TO s(0)
DO
IF s(i)#s(1) THEN
pos=i
EXIT
FI
OD
PrintF("""%S"" (len=%B) -> ",s,s(0))
IF pos=0 THEN
PrintE("all characters are the same.")
ELSE
PrintF("""%C"" (hex=$",s(pos))
PrintBH(s(pos))
PrintF(") is the first difference at pos. %B.%E",pos)
FI
PutE()
RETURN
PROC Main()
Test("")
Test(" ")
Test("2")
Test("333")
Test(".55")
Test("tttTTT")
Test("4444 444k")
RETURN |
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
| #Ada | Ada | with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Are_Same is
procedure All_Chars_Are_Same (S : in String) is
First_Diff : Natural := 0;
begin
Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
for I in S'First + 1 .. S'Last loop
if S(I) /= S(S'First) then
First_Diff := I;
exit;
end if;
end loop;
if First_Diff = 0 then
Put_Line (" All characters are the same.");
else
Put (" First difference at position" & First_Diff'Image &
", character = '" & S(First_Diff) &
"', hex = ");
Put (Character'Pos (S(First_Diff)), Width => 0, Base => 16);
New_Line;
end if;
end All_Chars_Are_Same;
begin
All_Chars_Are_Same ("");
All_Chars_Are_Same (" ");
All_Chars_Are_Same ("2");
All_Chars_Are_Same ("333");
All_Chars_Are_Same (".55");
All_Chars_Are_Same ("tttTTT");
All_Chars_Are_Same ("4444 444k");
end Test_All_Chars_Are_Same; |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #PicoLisp | PicoLisp | $ cat myScript
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(wait 120000)
(bye) |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #PowerShell | PowerShell |
if (Get-Process -Name "notepad" -ErrorAction SilentlyContinue)
{
Write-Warning -Message "notepad is already running."
}
else
{
Start-Process -FilePath C:\Windows\notepad.exe
}
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #PureBasic | PureBasic | #MyApp="MyLittleApp"
Mutex=CreateMutex_(0,1,#MyApp)
If GetLastError_()=#ERROR_ALREADY_EXISTS
MessageRequester(#MyApp,"One instance is already started.")
End
EndIf
; Main code executes here
ReleaseMutex_(Mutex)
End |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Python | Python | import __main__, os
def isOnlyInstance():
# Determine if there are more than the current instance of the application
# running at the current time.
return os.system("(( $(ps -ef | grep python | grep '[" +
__main__.__file__[0] + "]" + __main__.__file__[1:] +
"' | wc -l) > 1 ))") != 0 |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Euphoria | Euphoria | constant FREE = 0, LOCKED = 1
sequence forks
forks = repeat(FREE,5)
procedure person(sequence name, integer left_fork, integer right_fork)
while 1 do
while forks[left_fork] = LOCKED or forks[right_fork] = LOCKED do
if forks[left_fork] = FREE then
puts(1, name & " hasn't right fork.\n")
elsif forks[right_fork] = FREE then
puts(1, name & " hasn't left fork.\n")
else
puts(1, name & " hasn't both forks.\n")
end if
puts(1, name & " is waiting.\n")
task_yield()
end while
puts(1, name & " grabs forks.\n")
forks[left_fork] = LOCKED
forks[right_fork] = LOCKED
for i = 1 to rand(10) do
puts(1, name & " is eating.\n")
task_yield()
end for
puts(1, name & " puts forks down and leaves the dinning room.\n")
forks[left_fork] = FREE
forks[right_fork] = FREE
for i = 1 to rand(10) do
puts(1, name & " is thinking.\n")
task_yield()
end for
puts(1, name & " becomes hungry.\n")
end while
end procedure
integer rid
atom taskid
rid = routine_id("person")
taskid = task_create(rid,{"Aristotle",1,2})
task_schedule(taskid,{1,2})
taskid = task_create(rid,{"Kant",2,3})
task_schedule(taskid,{1,2})
taskid = task_create(rid,{"Spinoza",3,4})
task_schedule(taskid,{1,2})
taskid = task_create(rid,{"Marx",4,5})
task_schedule(taskid,{1,2})
taskid = task_create(rid,{"Russell",5,1})
task_schedule(taskid,{1,2})
while get_key() = -1 do
task_yield()
end while |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Euphoria | Euphoria | function isLeapYear(integer year)
return remainder(year,4)=0 and remainder(year,100)!=0 or remainder(year,400)=0
end function
constant YEAR = 1, MONTH = 2, DAY = 3, DAY_OF_YEAR = 8
constant month_lengths = {31,28,31,30,31,30,31,31,30,31,30,31}
function dayOfYear(sequence Date)
integer d
if length(Date) = DAY_OF_YEAR then
d = Date[DAY_OF_YEAR]
else
d = Date[DAY]
for i = Date[MONTH]-1 to 1 by -1 do
d += month_lengths[i]
if i = 2 and isLeapYear(Date[YEAR]) then
d += 1
end if
end for
end if
return d
end function
constant seasons = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}
constant weekday = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"}
constant apostle = {"Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"}
constant holiday = {"Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"}
function discordianDate(sequence Date)
sequence dyear, dseas, dwday
integer leap, doy, dsday
dyear = sprintf("%d",Date[YEAR]+1166)
leap = isLeapYear(Date[YEAR])
if leap and Date[MONTH] = 2 and Date[DAY] = 29 then
return "St. Tib's Day, in the YOLD " & dyear
end if
doy = dayOfYear(Date)
if leap and doy >= 60 then
doy -= 1
end if
dsday = remainder(doy,73)
if dsday = 5 then
return apostle[doy/73+1] & ", in the YOLD " & dyear
elsif dsday = 50 then
return holiday[doy/73+1] & ", in the YOLD " & dyear
end if
dseas = seasons[doy/73+1]
dwday = weekday[remainder(doy-1,5)+1]
return sprintf("%s, day %d of %s in the YOLD %s", {dwday, dsday, dseas, dyear})
end function
sequence today
today = date()
today[YEAR] += 1900
puts(1, discordianDate(today)) |
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)
| #Haskell | Haskell |
{-# LANGUAGE FlexibleContexts #-}
import Data.Array
import Data.Array.MArray
import Data.Array.ST
import Control.Monad.ST
import Control.Monad (foldM)
import Data.Set as S
dijkstra :: (Ix v, Num w, Ord w, Bounded w) => v -> v -> Array v [(v,w)] -> (Array v w, Array v v)
dijkstra src invalid_index adj_list = runST $ do
min_distance <- newSTArray b maxBound
writeArray min_distance src 0
previous <- newSTArray b invalid_index
let aux vertex_queue =
case S.minView vertex_queue of
Nothing -> return ()
Just ((dist, u), vertex_queue') ->
let edges = adj_list ! u
f vertex_queue (v, weight) = do
let dist_thru_u = dist + weight
old_dist <- readArray min_distance v
if dist_thru_u >= old_dist then
return vertex_queue
else do
let vertex_queue' = S.delete (old_dist, v) vertex_queue
writeArray min_distance v dist_thru_u
writeArray previous v u
return $ S.insert (dist_thru_u, v) vertex_queue'
in
foldM f vertex_queue' edges >>= aux -- note that aux is being called within its own definition (i.e. aux is recursive). The foldM only iterates on the neighbours of v, it does not execute the while loop itself in Dijkstra's
aux (S.singleton (0, src))
m <- freeze min_distance
p <- freeze previous
return (m, p)
where b = bounds adj_list
newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
newSTArray = newArray
shortest_path_to :: (Ix v) => v -> v -> Array v v -> [v]
shortest_path_to target invalid_index previous =
aux target [] where
aux vertex acc | vertex == invalid_index = acc
| otherwise = aux (previous ! vertex) (vertex : acc)
adj_list :: Array Char [(Char, Int)]
adj_list = listArray ('a', 'f') [ [('b',7), ('c',9), ('f',14)],
[('a',7), ('c',10), ('d',15)],
[('a',9), ('b',10), ('d',11), ('f',2)],
[('b',15), ('c',11), ('e',6)],
[('d',6), ('f',9)],
[('a',14), ('c',2), ('e',9)] ]
main :: IO ()
main = do
let (min_distance, previous) = dijkstra 'a' ' ' adj_list
putStrLn $ "Distance from a to e: " ++ show (min_distance ! 'e')
let path = shortest_path_to 'e' ' ' previous
putStrLn $ "Path: " ++ show path |
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
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. DIGITAL-ROOT.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 INPUT-NUMBER PIC 9(16).
03 INPUT-DIGITS REDEFINES INPUT-NUMBER,
PIC 9 OCCURS 16 TIMES.
03 DIGIT-SUM PIC 999.
03 DIGIT-NO PIC 99.
03 PERSISTENCE PIC 9.
01 OUTPUT-FORMAT.
03 O-NUMBER PIC Z(15)9.
03 FILLER PIC X(16) VALUE ': PERSISTENCE = '.
03 O-PERSISTENCE PIC Z9.
03 FILLER PIC X(9) VALUE ', ROOT = '.
03 O-ROOT PIC Z9.
PROCEDURE DIVISION.
BEGIN.
MOVE 627615 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.
MOVE 39390 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.
MOVE 588225 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.
MOVE 393900588225 TO INPUT-NUMBER, PERFORM FIND-DIGITAL-ROOT.
STOP RUN.
FIND-DIGITAL-ROOT.
MOVE ZERO TO PERSISTENCE.
MOVE INPUT-NUMBER TO O-NUMBER.
PERFORM SUMMATION UNTIL INPUT-NUMBER IS LESS THAN 10.
MOVE INPUT-NUMBER TO O-ROOT.
MOVE PERSISTENCE TO O-PERSISTENCE.
DISPLAY OUTPUT-FORMAT.
SUMMATION.
MOVE ZERO TO DIGIT-SUM.
ADD 1 TO PERSISTENCE.
PERFORM ADD-DIGIT VARYING DIGIT-NO FROM 1 BY 1
UNTIL DIGIT-NO IS GREATER THAN 16.
MOVE DIGIT-SUM TO INPUT-NUMBER.
ADD-DIGIT.
ADD INPUT-DIGITS(DIGIT-NO) TO DIGIT-SUM. |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #M2000_Interpreter | M2000 Interpreter | multDigitalRoot=lambda (n as decimal) ->{
if n<0 then error "Negative numbers not allowed"
def decimal mdr, mp, nn
nn=n
do
mdr=IF(nn>0->1@, 0@)
while nn>0
mdr*=nn mod 10@
nn|div 10@
end while
mp++
nn=mdr
when mdr>=10
=(mdr, mp)
}
Document doc$
ia=(123321, 7739, 893, 899998)
in_ia=each(ia)
while in_ia
(mdr, mp)=multDigitalRoot(array(in_ia))
doc$=format$("{0::-9} mdr = {1} MP = {2}", array(in_ia), mdr, mp)+{
}
end while
let n=0@, count=0&
dim ia2(0 to 9, 0 to 5)
do
mdr=multDigitalRoot(n)#val(0)
if ia2(mdr, 0)<5 then
ia2(mdr, 0)++
ia2(mdr, ia2(mdr, 0))=n
count++
end if
n++
when count<50
doc$={MDR n0 n1 n2 n3 n4
}
doc$={=== ============================
}
for i=0 to 9
doc$=format$("{0}: ", i)
for j=1 to 5
doc$=format$("{0::-6}", ia2(i, j))
next
doc$={
}
next
Clipboard doc$
// Print like in a file (-2 is for console):
Print #-2, doc$
|
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?
| #Go | Go | package main
import "fmt"
// The program here is restricted to finding assignments of tenants (or more
// generally variables with distinct names) to floors (or more generally
// integer values.) It finds a solution assigning all tenants and assigning
// them to different floors.
// Change number and names of tenants here. Adding or removing names is
// allowed but the names should be distinct; the code is not written to handle
// duplicate names.
var tenants = []string{"Baker", "Cooper", "Fletcher", "Miller", "Smith"}
// Change the range of floors here. The bottom floor does not have to be 1.
// These should remain non-negative integers though.
const bottom = 1
const top = 5
// A type definition for readability. Do not change.
type assignments map[string]int
// Change rules defining the problem here. Change, add, or remove rules as
// desired. Each rule should first be commented as human readable text, then
// coded as a function. The function takes a tentative partial list of
// assignments of tenants to floors and is free to compute anything it wants
// with this information. Other information available to the function are
// package level defintions, such as top and bottom. A function returns false
// to say the assignments are invalid.
var rules = []func(assignments) bool{
// Baker does not live on the top floor
func(a assignments) bool {
floor, assigned := a["Baker"]
return !assigned || floor != top
},
// Cooper does not live on the bottom floor
func(a assignments) bool {
floor, assigned := a["Cooper"]
return !assigned || floor != bottom
},
// Fletcher does not live on either the top or the bottom floor
func(a assignments) bool {
floor, assigned := a["Fletcher"]
return !assigned || (floor != top && floor != bottom)
},
// Miller lives on a higher floor than does Cooper
func(a assignments) bool {
if m, assigned := a["Miller"]; assigned {
c, assigned := a["Cooper"]
return !assigned || m > c
}
return true
},
// Smith does not live on a floor adjacent to Fletcher's
func(a assignments) bool {
if s, assigned := a["Smith"]; assigned {
if f, assigned := a["Fletcher"]; assigned {
d := s - f
return d*d > 1
}
}
return true
},
// Fletcher does not live on a floor adjacent to Cooper's
func(a assignments) bool {
if f, assigned := a["Fletcher"]; assigned {
if c, assigned := a["Cooper"]; assigned {
d := f - c
return d*d > 1
}
}
return true
},
}
// Assignment program, do not change. The algorithm is a depth first search,
// tentatively assigning each tenant in order, and for each tenant trying each
// unassigned floor in order. For each tentative assignment, it evaluates all
// rules in the rules list and backtracks as soon as any one of them fails.
//
// This algorithm ensures that the tenative assignments have only names in the
// tenants list, only floor numbers from bottom to top, and that tentants are
// assigned to different floors. These rules are hard coded here and do not
// need to be coded in the the rules list above.
func main() {
a := assignments{}
var occ [top + 1]bool
var df func([]string) bool
df = func(u []string) bool {
if len(u) == 0 {
return true
}
tn := u[0]
u = u[1:]
f:
for f := bottom; f <= top; f++ {
if !occ[f] {
a[tn] = f
for _, r := range rules {
if !r(a) {
delete(a, tn)
continue f
}
}
occ[f] = true
if df(u) {
return true
}
occ[f] = false
delete(a, tn)
}
}
return false
}
if !df(tenants) {
fmt.Println("no solution")
return
}
for t, f := range a {
fmt.Println(t, f)
}
} |
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
| #Ela | Ela | open list
dotp a b | length a == length b = sum (zipWith (*) a b)
| else = fail "Vector sizes must match."
dotp [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
| #Elena | Elena | import extensions;
import system'routines;
extension op
{
method dotProduct(int[] array)
= self.zipBy(array, (x,y => x * y)).summarize();
}
public program()
{
console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{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
| #AWK | AWK |
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_SQUEEZABLE.AWK
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..1111111111111111111111111111111111111111111111111111111111111117777888" ; arr2[n] = "7"
arr[++n] = "I never give 'em hell, I just tell the truth, and they think it's hell. " ; arr2[n] = "."
arr[++n] = " --- Harry S Truman " ; arr2[n] = " -r"
arr[++n] = "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" ; arr2[n] = "e"
arr[++n] = "headmistressship" ; arr2[n] = "s"
for (i=1; i<=n; i++) {
for (j=1; j<=length(arr2[i]); j++) {
main(arr[i],substr(arr2[i],j,1))
}
}
exit(0)
}
function main(str,chr, c,i,new_str,prev_c) {
for (i=1; i<=length(str); i++) {
c = substr(str,i,1)
if (!(prev_c == c && c == chr)) {
prev_c = c
new_str = new_str c
}
}
printf("use: '%s'\n",chr)
printf("old: %2d <<<%s>>>\n",length(str),str)
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
|
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
| #6502_Assembly | 6502 Assembly |
macro loadpair,regs,addr
lda #<\addr
sta \regs
lda #>\addr
sta \regs+1
endm
macro pushY
tya
pha
endm
macro popY
pla
tay
endm
|
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Swift | Swift | typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>
class Node<T> {
var value: T
fileprivate var prev: NodePtr<T>?
fileprivate var next: NodePtr<T>?
init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) {
self.value = value
self.prev = prev
self.next = next
}
}
struct DoublyLinkedList<T> {
fileprivate var head: NodePtr<T>?
fileprivate var tail: NodePtr<T>?
@discardableResult
mutating func insert(_ val: T, at: InsertLoc<T> = .last) -> Node<T> {
let node = NodePtr<T>.allocate(capacity: 1)
node.initialize(to: Node(value: val))
if head == nil && tail == nil {
head = node
tail = node
return node.pointee
}
switch at {
case .first:
node.pointee.next = head
head?.pointee.prev = node
head = node
case .last:
node.pointee.prev = tail
tail?.pointee.next = node
tail = node
case let .after(insertNode):
var n = head
while n != nil {
if n!.pointee !== insertNode {
n = n?.pointee.next
continue
}
node.pointee.prev = n
node.pointee.next = n!.pointee.next
n!.pointee.next = node
if n == tail {
tail = node
}
break
}
}
return node.pointee
}
@discardableResult
mutating func remove(_ node: Node<T>) -> T? {
var n = head
while n != nil {
if n!.pointee !== node {
n = n?.pointee.next
continue
}
if n == head {
n?.pointee.next?.pointee.prev = nil
head = n?.pointee.next
} else if n == tail {
n?.pointee.prev?.pointee.next = nil
tail = n?.pointee.prev
} else {
n?.pointee.prev?.pointee.next = n?.pointee.next
n?.pointee.next?.pointee.prev = n?.pointee.prev
}
break
}
if n == nil {
return nil
}
defer {
n?.deinitialize(count: 1)
n?.deallocate()
}
return n?.pointee.value
}
enum InsertLoc<T> {
case first
case last
case after(Node<T>)
}
}
extension DoublyLinkedList: CustomStringConvertible {
var description: String {
var res = "["
var node = head
while node != nil {
res += "\(node!.pointee.value), "
node = node?.pointee.next
}
return (res.count > 1 ? String(res.dropLast(2)) : res) + "]"
}
}
var list = DoublyLinkedList<Int>()
var node: Node<Int>!
for i in 0..<10 {
let insertedNode = list.insert(i)
if i == 5 {
node = insertedNode
}
}
print(list)
list.insert(100, at: .after(node!))
print(list)
list.remove(node!)
print(list) |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Collapsible is
procedure Collapse (S : in String) is
Res : String (1 .. S'Length);
Len : Natural := 0;
begin
Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image);
for I in S'Range loop
if Len = 0 or else S(I) /= Res(Len) then
Len := Len + 1;
Res(Len) := S(I);
end if;
end loop;
Put_Line ("Output = <<<" & Res (1 .. Len) & ">>>, length =" & Len'Image);
end Collapse;
begin
Collapse ("");
Collapse ("""If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln ");
Collapse ("..1111111111111111111111111111111111111111111111111111111111111117777888");
Collapse ("I never give 'em hell, I just tell the truth, and they think it's hell. ");
Collapse (" --- Harry S Truman ");
end Test_Collapsible;
|
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
| #ALGOL_68 | ALGOL 68 | BEGIN
# returns a collapsed version of s #
# i.e. s with adjacent duplicate characters removed #
PROC collapse = ( STRING s )STRING:
IF s = ""
THEN "" # empty string #
ELSE # non-empty string #
[ LWB s : UPB s ]CHAR result;
INT r pos := LWB result;
result[ r pos ] := s[ LWB s ];
FOR s pos FROM LWB s + 1 TO UPB s DO
IF result[ r pos ] /= s[ s pos ] THEN
r pos +:= 1;
result[ r pos ] := s[ s pos ]
FI
OD;
result[ LWB result : r pos ]
FI # callapse # ;
# task test cases #
[]STRING tests = ( ""
, """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
, "..1111111111111111111111111111111111111111111111111111111111111117777888"
, "I never give 'em hell, I just tell the truth, and they think it's hell. "
, " --- Harry S Truman "
);
FOR t pos FROM LWB tests TO UPB tests DO
STRING s = tests[ t pos ];
STRING c = collapse( s );
print( ( " <<<", s, ">>> (length ", whole( ( UPB s + 1 ) - LWB s, 0 ), ")", newline ) );
print( ( "result <<<", c, ">>> (length ", whole( ( UPB c + 1 ) - LWB c, 0 ), ")", newline ) )
OD
END
|
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?
Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?
This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205
| #PL.2FI | PL/I | *process source attributes xref;
dicegame: Proc Options(main);
Call test(9, 4,6,6);
Call test(5,10,6,7);
test: Proc(w1,s1,w2,s2);
Dcl (w1,s1,w2,s2,x,y) Bin Fixed(31);
Dcl p1(100) Dec Float(18) Init((100)0);
Dcl p2(100) Dec Float(18) Init((100)0);
Dcl p2low(100) Dec Float(18) Init((100)0);
Call pp(w1,s1,p1);
Call pp(w2,s2,p2);
Do x=w1 To w1*s1;
Do y=0 To x-1;
p2low(x)+=p2(y);
End;
End;
pwin1=0;
Do x=w1 To w1*s1;
pwin1+=p1(x)*p2low(x);
End;
Put Edit('Player 1 has ',w1,' dice with ',s1,' sides each')
(Skip,3(a,f(2)));
Put Edit('Player 2 has ',w2,' dice with ',s2,' sides each')
(Skip,3(a,f(2)));
Put Edit('Probability for player 1 to win: ',pwin1)(Skip,a,f(20,18));
Put Edit('')(Skip,a);
End;
pp: Proc(w,s,p);
/*--------------------------------------------------------------------
* Compute and assign probabilities to get a sum x
* when throwing w dice each having s sides (marked from 1 to s)
*-------------------------------------------------------------------*/
Dcl (w,s) Bin Fixed(31);
Dcl p(100) Dec Float(18);
Dcl cnt(100) Bin Fixed(31);
Dcl (a(12),e(12),v(12),sum,i,n) Bin Fixed(31);
a=0;
e=0;
Do i=1 To w;
a(i)=1;
e(i)=s;
End;
n=0;
cnt=0;
Do v(1)=a(1) To e(1);
Do v(2)=a(2) To e(2);
Do v(3)=a(3) To e(3);
Do v(4)=a(4) To e(4);
Do v(5)=a(5) To e(5);
Do v(6)=a(6) To e(6);
Do v(7)=a(7) To e(7);
Do v(8)=a(8) To e(8);
Do v(9)=a(9) To e(9);
Do v(10)=a(10) To e(10);
sum=0;
Do i=1 To 10;
sum=sum+v(i);
End;
cnt(sum)+=1;
n+=1;
End;
End;
End;
End;
End;
End;
End;
End;
End;
End;
Do k=w To w*s;
p(k)=divide(cnt(k),n,18,16);
End;
End;
End; |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | BEGIN
# return the position of the first different character in s #
# or UPB s + 1 if all the characters are the same #
OP FIRSTDIFF = ( STRING s )INT:
IF UPB s <= LWB s
THEN
# 0 or 1 character #
UPB s + 1
ELSE
# two or more characters #
INT result := LWB s + 1;
CHAR c1 = s[ LWB s ];
FOR s pos FROM LWB s + 1 TO UPB s WHILE s[ s pos ] = c1 DO result +:= 1 OD;
result
FI # FIRSTDIFF # ;
# convert a character to a hex string #
PROC hex = ( CHAR c )STRING:
BEGIN
STRING result := "";
INT n := ABS c;
IF n = 0
THEN
result := "0"
ELSE
WHILE n > 0 DO
INT d = n MOD 16;
n OVERAB 16;
IF d < 10
THEN REPR ( d + ABS "0" )
ELSE REPR ( ( d - 10 ) + ABS "a" )
FI +=: result
OD
FI;
result
END # hex # ;
# show whether s contains all the same character of the first diff #
PROC show first diff = ( STRING s )VOID:
IF print( ( """", s, """ (length ", whole( ( UPB s + 1 ) - LWB s, 0 ), "): " ) );
INT diff pos = FIRSTDIFF s;
diff pos > UPB s
THEN
# all characters the same #
print( ( "all characters are the same", newline ) )
ELSE
# not all characters are the same #
print( ( "first different character """
, s[ diff pos ]
, """(0x", hex( s[ diff pos ] )
, ") at position: "
, whole( diff pos, 0 )
, newline
)
)
FI # show first diff # ;
# task test cases #
show first diff( "" );
show first diff( " " );
show first diff( "2" );
show first diff( "333" );
show first diff( ".55" );
show first diff( "tttTTT" );
show first diff( "4444 444k" );
show first diff( "4444|444k" )
END |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Racket | Racket |
#lang racket
(define *port* 12345) ; random large port number
(define listener-handler
(with-handlers ([exn? (λ(e) (printf "Already running, bye.\n") (exit))])
(tcp-listen *port*)))
(printf "Working...\n")
(sleep 10)
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Raku | Raku | my $name = $*PROGRAM-NAME;
my $pid = $*PID;
my $lockdir = "/tmp";
my $lockfile = "$lockdir/$name.pid";
my $lockpid = "$lockfile$pid";
my $havelock = False;
END {
unlink $lockfile if $havelock;
try unlink $lockpid;
}
my $pidfile = open "$lockpid", :w orelse .die;
$pidfile.say($pid);
$pidfile.close;
if try link($lockpid, $lockfile) {
$havelock = True;
}
else {
shell "kill -CONT `cat $lockfile` || rm $lockfile";
if try link($lockfile, $lockpid) {
$havelock = True;
}
else {
die "You can't run right now!";
}
}
note "Got lock!";
unlink $lockpid; |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #REXX | REXX | /* Simple ARexx program to open a port after checking if it's already open */
IF Show('PORTS','ROSETTA') THEN DO /* Port is already open; exit */
SAY 'This program may only be run in a single instance at a time.'
EXIT 5 /* Exit with a mild warning */
END
/* Open rexxsupport.library so that ports can be opened */
IF ~Show('LIBRARIES','rexxsupport.library')
THEN CALL AddLib('rexxsupport.library',0,-30,0)
IF ~OpenPort('ROSETTA') THEN EXIT 10 /* Open port, end if it fails */
SAY 'Program is now running.'
DO FOREVER /* Busyloop */
/* Program stuff here */
END
EXIT 0 |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #F.23 | F# |
open System
let flip f x y = f y x
let rec cycle s = seq { yield! s; yield! cycle s }
type Agent<'T> = MailboxProcessor<'T>
type Message = Waiting of (Set<int> * AsyncReplyChannel<unit>) | Done of Set<int>
let reply (c: AsyncReplyChannel<_>) = c.Reply()
let strategy forks waiting =
let aux, waiting = List.partition (fst >> flip Set.isSubset forks) waiting
let forks = aux |> List.map fst |> List.fold (-) forks
List.iter (snd >> reply) aux
forks, waiting
let waiter strategy forkCount =
Agent<_>.Start(fun inbox ->
let rec loop forks waiting =
async { let forks, waiting = strategy forks waiting
let! msg = inbox.Receive()
match msg with
| Waiting r -> return! loop forks (waiting @ [r])
| Done f -> return! loop (forks + f) waiting }
loop (Set.ofList (List.init forkCount id)) [])
let philosopher (waiter: Agent<_>) name forks =
let rng = new Random()
let forks = Set.ofArray forks
Agent<_>.Start(fun inbox ->
let rec loop () =
async { printfn "%s is thinking" name
do! Async.Sleep(rng.Next(100, 500))
printfn "%s is hungry" name
do! waiter.PostAndAsyncReply(fun c -> Waiting (forks, c))
printfn "%s is eating" name
do! Async.Sleep(rng.Next(100, 500))
printfn "%s is done eating" name
waiter.Post(Done (forks))
return! loop () }
loop ())
[<EntryPoint>]
let main args =
let forks = Seq.init 5 id |> cycle |> Seq.windowed 2 |> Seq.take 5 |> Seq.toList
let names = ["plato"; "aristotel"; "kant"; "nietzsche"; "russel"]
let waiter = waiter strategy 5
List.map2 (philosopher waiter) names forks |> ignore
Console.ReadLine() |> ignore
0
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #F.23 | F# | open System
let seasons = [| "Chaos"; "Discord"; "Confusion"; "Bureaucracy"; "The Aftermath" |]
let ddate (date:DateTime) =
let dyear = date.Year + 1166
let leapYear = DateTime.IsLeapYear(date.Year)
if leapYear && date.Month = 2 && date.Day = 29 then
sprintf "St. Tib's Day, %i YOLD" dyear
else
// compensate for St. Tib's Day
let dayOfYear = (if leapYear && date.DayOfYear >= 60 then date.DayOfYear - 1 else date.DayOfYear) - 1
let season, dday = Math.DivRem(dayOfYear, 73)
sprintf "%s %i, %i YOLD" seasons.[season] (dday+1) dyear
[<EntryPoint>]
let main argv =
let p = Int32.Parse
Seq.ofArray("2012-02-28 2012-02-29 2012-03-01 2010-07-22 2015-10-19 2015-10-20".Split())
|> Seq.map(fun (s:string) ->
let d = s.Split('-')
(s, DateTime(p(d.[0]),p(d.[1]),p(d.[2]))))
|> Seq.iter(fun (s,d) -> printfn "%s is %s" s (ddate d))
0
|
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)
| #Huginn | Huginn | import Algorithms as algo;
import Mathematics as math;
import Text as text;
class Edge {
_to = none;
_name = none;
_cost = none;
constructor( to_, name_, cost_ ) {
_to = to_;
_name = name_;
_cost = real( cost_ );
}
to_string() {
return ( "{}<{}>".format( _name, _cost ) );
}
}
class Path {
_id = none;
_from = none;
_cost = none;
_names = none;
constructor( toName_, ids_, names_ ) {
_id = ids_[toName_];
_names = names_;
_cost = math.INFINITY;
}
less( other_ ) {
return ( _cost < other_._cost );
}
update( from_, cost_ ) {
_from = from_;
_cost = cost_;
}
to_string() {
return ( "{} via {} at cost {}".format( _names[_id], _from != none ? _names[_from] : none, _cost ) );
}
}
class Graph {
_neighbours = [];
_ids = {};
_names = [];
add_node( name_ ) {
if ( name_ ∉ _ids ) {
_ids[name_] = size( _names );
_names.push( name_ );
}
}
add_edge( from_, to_, cost_ ) {
assert( ( from_ ∈ _ids ) && ( to_ ∈ _ids ) );
from = _ids[from_];
to = _ids[to_];
if ( from >= size( _neighbours ) ) {
_neighbours.resize( from + 1, [] );
}
_neighbours[from].push( Edge( to, to_, cost_ ) );
}
shortest_paths( from_ ) {
assert( from_ ∈ _ids );
from = _ids[from_];
paths = algo.materialize( algo.map( _names, @[_ids, _names]( name ) { Path( name, _ids, _names ); } ), list );
paths[from].update( none, 0.0 );
todo = algo.sorted( paths, @(x){-x._cost;} );
while ( size( todo ) > 0 ) {
node = todo[-1]._id;
todo.resize( size( todo ) - 1, none );
if ( node >= size( _neighbours ) ) {
continue;
}
neighbours = _neighbours[node];
for ( n : neighbours ) {
newCost = n._cost + paths[node]._cost;
if ( newCost < paths[n._to]._cost ) {
paths[n._to].update( node, newCost );
}
}
todo = algo.sorted( todo, @(x){-x._cost;} );
}
return ( paths );
}
path( paths_, to_ ) {
assert( to_ ∈ _ids );
to = _ids[to_];
p = [to_];
while ( paths_[to]._from != none ) {
to = paths_[to]._from;
p.push( _names[to] );
}
return ( algo.materialize( algo.reversed( p ), list ) );
}
to_string() {
s = "";
for ( i, n : algo.enumerate( _neighbours ) ) {
s += "{} -> {}\n".format( _names[i], n );
}
}
}
main() {
g = Graph();
confStr = input();
if ( confStr == none ) {
return ( 1 );
}
conf = algo.materialize( algo.map( text.split( confStr ), integer ), tuple );
assert( size( conf ) == 2 );
for ( _ : algo.range( conf[0] ) ) {
line = input();
if ( line == none ) {
return ( 1 );
}
g.add_node( line.strip() );
}
for ( _ : algo.range( conf[1] ) ) {
line = input();
if ( line == none ) {
return ( 1 );
}
g.add_edge( algo.materialize( text.split( line.strip() ), tuple )... );
}
print( string( g ) );
paths = g.shortest_paths( "a" );
for ( p : paths ) {
print( "{}\n".format( p ) );
}
print( "{}\n".format( g.path( paths, "e" ) ) );
print( "{}\n".format( g.path( paths, "f" ) ) );
} |
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
| #Cowgol | Cowgol | include "cowgol.coh";
# Calculate the digital root and additive persistance of a number
# in a given base
sub digital_root(n: uint32, base: uint32): (root: uint32, pers: uint8) is
pers := 0;
while base < n loop
var step: uint32 := 0;
while n > 0 loop
step := step + (n % base);
n := n / base;
end loop;
pers := pers + 1;
n := step;
end loop;
root := n;
end sub;
# Print digital root and persistence (in base 10)
sub test(n: uint32) is
var root: uint32;
var pers: uint8;
(root, pers) := digital_root(n, 10);
print_i32(n);
print(": root = ");
print_i32(root);
print(", persistence = ");
print_i8(pers);
print_nl();
end sub;
test(4);
test(627615);
test(39390);
test(588225);
test(9992); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.