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/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?
| #C.23 | C# | public class Program
{
public static void Main()
{
const int count = 5;
const int Baker = 0, Cooper = 1, Fletcher = 2, Miller = 3, Smith = 4;
string[] names = { nameof(Baker), nameof(Cooper), nameof(Fletcher), nameof(Miller), nameof(Smith) };
Func<int[], bool>[] constraints = {
floorOf => floorOf[Baker] != count-1,
floorOf => floorOf[Cooper] != 0,
floorOf => floorOf[Fletcher] != count-1 && floorOf[Fletcher] != 0,
floorOf => floorOf[Miller] > floorOf[Cooper],
floorOf => Math.Abs(floorOf[Smith] - floorOf[Fletcher]) > 1,
floorOf => Math.Abs(floorOf[Fletcher] - floorOf[Cooper]) > 1,
};
var solver = new DinesmanSolver();
foreach (var tenants in solver.Solve(count, constraints)) {
Console.WriteLine(string.Join(" ", tenants.Select(t => names[t])));
}
}
}
public class DinesmanSolver
{
public IEnumerable<int[]> Solve(int count, params Func<int[], bool>[] constraints) {
foreach (int[] floorOf in Permutations(count)) {
if (constraints.All(c => c(floorOf))) {
yield return Enumerable.Range(0, count).OrderBy(i => floorOf[i]).ToArray();
}
}
}
static IEnumerable<int[]> Permutations(int length) {
if (length == 0) {
yield return new int[0];
yield break;
}
bool forwards = false;
foreach (var permutation in Permutations(length - 1)) {
for (int i = 0; i < length; i++) {
yield return permutation.InsertAt(forwards ? i : length - i - 1, length - 1).ToArray();
}
forwards = !forwards;
}
}
}
static class Extensions
{
public static IEnumerable<T> InsertAt<T>(this IEnumerable<T> source, int position, T newElement) {
if (source == null) throw new ArgumentNullException(nameof(source));
if (position < 0) throw new ArgumentOutOfRangeException(nameof(position));
return InsertAtIterator(source, position, newElement);
}
private static IEnumerable<T> InsertAtIterator<T>(IEnumerable<T> source, int position, T newElement) {
int index = 0;
foreach (T element in source) {
if (index == position) yield return newElement;
yield return element;
index++;
}
if (index < position) throw new ArgumentOutOfRangeException(nameof(position));
if (index == position) yield return newElement;
}
} |
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
| #CLU | CLU | % Compute the dot product of two sequences
% If the sequences are not the same length, it signals length_mismatch
% Any type may be used as long as it supports addition and multiplication
dot_product = proc [T: type] (a, b: sequence[T])
returns (T) signals (length_mismatch, empty, overflow)
where T has add: proctype (T,T) returns (T) signals (overflow),
mul: proctype (T,T) returns (T) signals (overflow)
sT = sequence[T]
% throw errors if necessary
if sT$size(a) ~= sT$size(b) then signal length_mismatch end
if sT$empty(a) then signal empty end
% because we don't know what type T is yet, we can't instantiate it
% with a default value, so we use the first pair from the sequences
s: T := sT$bottom(a) * sT$bottom(b) resignal overflow
for i: int in int$from_to(2, sT$size(a)) do
s := s + a[i] * b[i] resignal overflow
end
return(s)
end dot_product
% calculate the dot product of the given example
start_up = proc ()
po: stream := stream$primary_output()
a: sequence[int] := sequence[int]$[1, 3, -5]
b: sequence[int] := sequence[int]$[4, -2, -1]
stream$putl(po, int$unparse(dot_product[int](a,b)))
end start_up |
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
| #Oforth | Oforth | Object Class new: DNode(value, mutable prev, mutable next)
DNode method: initialize := next := prev := value ;
DNode method: value @value ;
DNode method: prev @prev ;
DNode method: next @next ;
DNode method: setPrev := prev ;
DNode method: setNext := next ;
DNode method: << @value << ;
DNode method: insertAfter(node)
node setPrev(self)
node setNext(@next)
@next ifNotNull: [ @next setPrev(node) ]
node := next ;
// Double linked list definition
Collection Class new: DList(mutable head, mutable tail)
DList method: head @head ;
DList method: tail @tail ;
DList method: insertFront(v)
| p |
@head ->p
DNode new(v, null, p) := head
p ifNotNull: [ p setPrev(@head) ]
@tail ifNull: [ @head := tail ] ;
DList method: insertBack(v)
| n |
@tail ->n
DNode new(v, n, null) := tail
n ifNotNull: [ n setNext(@tail) ]
@head ifNull: [ @tail := head ] ;
DList method: forEachNext
dup ifNull: [ drop @head ifNull: [ false ] else: [ @head @head true] return ]
next dup ifNull: [ drop false ] else: [ dup true ] ;
DList method: forEachPrev
dup ifNull: [ drop @tail ifNull: [ false ] else: [ @tail @tail true] return ]
prev dup ifNull: [ drop false ] else: [ dup true ] ;
: test // ( -- aDList )
| dl dn |
DList new ->dl
dl insertFront("A")
dl insertBack("B")
dl head insertAfter(DNode new("C", null , null))
dl ; |
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
| #D | D | import std.stdio, std.range, std.algorithm;
void throwDie(in uint nSides, in uint nDice, in uint s, uint[] counts)
pure nothrow @safe @nogc {
if (nDice == 0) {
counts[s]++;
return;
}
foreach (immutable i; 1 .. nSides + 1)
throwDie(nSides, nDice - 1, s + i, counts);
}
real beatingProbability(uint nSides1, uint nDice1,
uint nSides2, uint nDice2)()
pure nothrow @safe /*@nogc*/ {
uint[(nSides1 + 1) * nDice1] C1;
throwDie(nSides1, nDice1, 0, C1);
uint[(nSides2 + 1) * nDice2] C2;
throwDie(nSides2, nDice2, 0, C2);
immutable p12 = real((ulong(nSides1) ^^ nDice1) *
(ulong(nSides2) ^^ nDice2));
return cartesianProduct(C1[].enumerate, C2[].enumerate)
.filter!(p => p[0][0] > p[1][0])
.map!(p => real(p[0][1]) * p[1][1] / p12)
.sum;
}
void main() @safe {
writefln("%1.16f", beatingProbability!(4, 9, 6, 6));
writefln("%1.16f", beatingProbability!(10, 5, 7, 6));
} |
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.
| #C | C | #include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#define N 5
const char *names[N] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" };
pthread_mutex_t forks[N];
#define M 5 /* think bubbles */
const char *topic[M] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" };
#define lock pthread_mutex_lock
#define unlock pthread_mutex_unlock
#define xy(x, y) printf("\033[%d;%dH", x, y)
#define clear_eol(x) print(x, 12, "\033[K")
void print(int y, int x, const char *fmt, ...)
{
static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;
va_list ap;
va_start(ap, fmt);
lock(&screen);
xy(y + 1, x), vprintf(fmt, ap);
xy(N + 1, 1), fflush(stdout);
unlock(&screen);
}
void eat(int id)
{
int f[2], ration, i; /* forks */
f[0] = f[1] = id;
/* make some (but not all) philosophers leftie.
could have been f[!id] = (id + 1) %N; for example */
f[id & 1] = (id + 1) % N;
clear_eol(id);
print(id, 12, "..oO (forks, need forks)");
for (i = 0; i < 2; i++) {
lock(forks + f[i]);
if (!i) clear_eol(id);
print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]);
/* delay 1 sec to clearly show the order of fork acquisition */
sleep(1);
}
for (i = 0, ration = 3 + rand() % 8; i < ration; i++)
print(id, 24 + i * 4, "nom"), sleep(1);
/* done nomming, give up forks (order doesn't matter) */
for (i = 0; i < 2; i++) unlock(forks + f[i]);
}
void think(int id)
{
int i, t;
char buf[64] = {0};
do {
clear_eol(id);
sprintf(buf, "..oO (%s)", topic[t = rand() % M]);
for (i = 0; buf[i]; i++) {
print(id, i+12, "%c", buf[i]);
if (i < 5) usleep(200000);
}
usleep(500000 + rand() % 1000000);
} while (t);
}
void* philosophize(void *a)
{
int id = *(int*)a;
print(id, 1, "%10s", names[id]);
while(1) think(id), eat(id);
}
int main()
{
int i, id[N];
pthread_t tid[N];
for (i = 0; i < N; i++)
pthread_mutex_init(forks + (id[i] = i), 0);
for (i = 0; i < N; i++)
pthread_create(tid + i, 0, philosophize, id + i);
/* wait forever: the threads don't actually stop */
return pthread_join(tid[0], 0);
} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #AWK | AWK |
# DDATE.AWK - Gregorian to Discordian date contributed by Dan Nielsen
# syntax: GAWK -f DDATE.AWK [YYYYMMDD | YYYY-MM-DD | MM-DD-YYYY | DDMMMYYYY | YYYY] ...
# examples:
# GAWK -f DDATE.AWK today
# GAWK -f DDATE.AWK 20110722 one date
# GAWK -f DDATE.AWK 20110722 20120229 two dates
# GAWK -f DDATE.AWK 2012 yearly calendar
BEGIN {
split("Chaos,Discord,Confusion,Bureaucracy,The Aftermath",season_arr,",")
split("Sweetmorn,Boomtime,Pungenday,Prickle-Prickle,Setting Orange",weekday_arr,",")
split("Mungday,Mojoday,Syaday,Zaraday,Maladay",apostle_holyday_arr,",")
split("Chaoflux,Discoflux,Confuflux,Bureflux,Afflux",season_holyday_arr,",")
split("31,28,31,30,31,30,31,31,30,31,30,31",days_in_month,",") # days per month in non leap year
split("0 31 59 90 120 151 181 212 243 273 304 334",rdt," ") # relative day table
mmm = "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC"
# 1 2 3 4 5 6 7 8 9 10 11 12
if (ARGV[1] == "") { # use current date
ARGV[ARGC++] = strftime("%Y%m%d") # GAWK only
# ARGV[ARGC++] = dos_date() # any AWK
# timetab(arr); ARGV[ARGC++] = sprintf("%04d%02d%02d",arr["YEAR"],arr["MONTH"],arr["DAY"]) # TAWK only
}
for (argno=1; argno<=ARGC-1; argno++) { # validate command line arguments
print("")
x = toupper(ARGV[argno])
if (x ~ /^[0-9][0-9][0-9][0-9][01][0-9][0-3][0-9]$/) { # YYYYMMDD
main(x)
}
else if (x ~ /^[0-9][0-9][0-9][0-9]-[01][0-9]-[0-3][0-9]$/) { # YYYY-MM-DD
gsub(/-/,"",x)
main(x)
}
else if (x ~ /^[01][0-9]-[0-3][0-9]-[0-9][0-9][0-9][0-9]$/) { # MM-DD-YYYY
main(substr(x,7,4) substr(x,1,2) substr(x,4,2))
}
else if (x ~ /^[0-3][0-9](JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[0-9][0-9][0-9][0-9]$/) { # DDMMMYYYY
main(sprintf("%04d%02d%02d",substr(x,6,4),int((match(mmm,substr(x,3,3))/4)+1),substr(x,1,2)))
}
else if (x ~ /^[0-9][0-9][0-9][0-9]$/) { # YYYY
yearly_calendar(x)
}
else {
error("begin")
}
}
if (errors == 0) { exit(0) } else { exit(1) }
}
function main(x, d,dyear,m,season_day,season_nbr,text,weekday_nbr,y,year_day) {
y = substr(x,1,4) + 0
m = substr(x,5,2) + 0
d = substr(x,7,2) + 0
days_in_month[2] = (leap_year(y) == 1) ? 29 : 28
if (m < 1 || m > 12 || d < 1 || d > days_in_month[m]+0) {
error("main")
return
}
year_day = rdt[m] + d
dyear = y + 1166 # Discordian year
season_nbr = int((year_day - 1 ) / 73) + 1
season_day = ((year_day - 1) % 73) + 1
weekday_nbr = ((year_day - 1 ) % 5) + 1
if (season_day == 5) {
text = ", " apostle_holyday_arr[season_nbr]
}
else if (season_day == 50) {
text = ", " season_holyday_arr[season_nbr]
}
if (leap_year(y) && m == 2 && d == 29) {
printf("%04d-%02d-%02d is St. Tib's day, Year of Our Lady of Discord %s\n",y,m,d,dyear)
}
else {
printf("%04d-%02d-%02d is %s, %s %s, Year of Our Lady of Discord %s%s\n",
y,m,d,weekday_arr[weekday_nbr],season_arr[season_nbr],season_day,dyear,text)
}
}
function leap_year(y) { # leap year: 0=no, 1=yes
return (y % 400 == 0 || (y % 4 == 0 && y % 100)) ? 1 : 0
}
function yearly_calendar(y, d,m) {
days_in_month[2] = (leap_year(y) == 1) ? 29 : 28
for (m=1; m<=12; m++) {
for (d=1; d<=days_in_month[m]; d++) {
main(sprintf("%04d%02d%02d",y,m,d))
}
}
}
function dos_date( arr,cmd,d,x) { # under Microsoft Windows
# XP - The current date is: MM/DD/YYYY
# 8 - The current date is: DOW MM/DD/YYYY
cmd = "DATE <NUL"
cmd | getline x
close(cmd) # close pipe
d = arr[split(x,arr," ")]
return sprintf("%04d%02d%02d",substr(d,7,4),substr(d,1,2),substr(d,4,2))
}
function error(x) {
printf("error: argument %d is invalid, %s, in %s\n",argno,ARGV[argno],x)
errors++
}
|
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)
| #AutoHotkey | AutoHotkey | Dijkstra(data, start){
nodes := [], dist := [], Distance := [], dist := [], prev := [], Q := [], min := "x"
for each, line in StrSplit(data, "`n" , "`r")
field := StrSplit(line,"`t"), nodes[field.1] := 1, nodes[field.2] := 1
, Distance[field.1,field.2] := field.3, Distance[field.2,field.1] := field.3
dist[start] := 0, prev[start] := ""
for node in nodes {
if (node <> start)
dist[node] := "x"
, prev[node] := ""
Q[node] := 1
}
while % ObjCount(Q) {
u := MinDist(Q, dist).2
for node, val in Q
if (node = u) {
q.Remove(node)
break
}
for v, length in Distance[u] {
alt := dist[u] + length
if (alt < dist[v])
dist[v] := alt
, prev[v] := u
}
}
return [dist, prev]
}
;-----------------------------------------------
MinDist(Q, dist){
for node , val in Q
if A_Index=1
min := dist[node], minNode := node
else
min := min < dist[node] ? min : dist[node] , minNode := min < dist[node] ? minNode : node
return [min,minNode]
}
ObjCount(Obj){
for key, val in Obj
count := A_Index
return count
} |
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
| #AutoHotkey | AutoHotkey | p := {}
for key, val in [30,1597,381947,92524902,448944221089]
{
n := val
while n > 9
{
m := 0
Loop, Parse, n
m += A_LoopField
n := m, i := A_Index
}
p[A_Index] := [val, n, i]
}
for key, val in p
Output .= val[1] ": Digital Root = " val[2] ", Additive Persistence = " val[3] "`n"
MsgBox, 524288, , % Output |
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
| #F.23 | F# |
// mdr. Nigel Galloway: June 29th., 2021
let rec fG n g=if n=0 then g else fG(n/10)(g*(n%10))
let mdr n=let rec mdr n g=if n<10 then (n,g) else mdr(fG n 1)(g+1) in mdr n 0
[123321; 7739; 893; 899998] |> List.iter(fun i->let n,g=mdr i in printfn "%d has mdr=%d with persitance %d" i n g)
let fN g=Seq.initInfinite id|>Seq.filter((mdr>>fst>>(=)g))|>Seq.take 5
seq{0..9}|>Seq.iter(fun n->printf "First 5 numbers with mdr %d -> " n; Seq.initInfinite id|>Seq.filter((mdr>>fst>>(=)n))|>Seq.take 5|>Seq.iter(printf "%d ");printfn "")
|
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.
| #LaTeX | LaTeX | \documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{lindenmayersystems}
\pgfdeclarelindenmayersystem{Dragon curve}{
\symbol{S}{\pgflsystemdrawforward}
\rule{F -> -F++S-}
\rule{S -> +F--S+}
}
\foreach \i in {1,...,8} {
\hbox{
order=\i
\hspace{.5em}
\begin{tikzpicture}[baseline=0pt]
\draw
[lindenmayer system={Dragon curve, step=10pt,angle=45, axiom=F, order=\i}]
lindenmayer system;
\end{tikzpicture}
\hspace{1em}
}
\vspace{.5ex}
}
\begin{document}
\end{document} |
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?
| #Ceylon | Ceylon | shared void run() {
function notAdjacent(Integer a, Integer b) => (a - b).magnitude >= 2;
function allDifferent(Integer* ints) => ints.distinct.size == ints.size;
value solutions = [
for (baker in 1..4)
for (cooper in 2..5)
for (fletcher in 2..4)
for (miller in 2..5)
for (smith in 1..5)
if (miller > cooper &&
notAdjacent(smith, fletcher) &&
notAdjacent(fletcher, cooper) &&
allDifferent(baker, cooper, fletcher, miller, smith))
"baker lives on ``baker``
cooper lives on ``cooper``
fletcher lives on ``fletcher``
miller lives on ``miller``
smith lives on ``smith``"
];
print(solutions.first else "No solution!");
} |
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
| #CoffeeScript | CoffeeScript | dot_product = (ary1, ary2) ->
if ary1.length != ary2.length
throw "can't find dot product: arrays have different lengths"
dotprod = 0
for v, i in ary1
dotprod += v * ary2[i]
dotprod
console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1 ]) # 3
try
console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 0 ]) # exception
catch e
console.log e |
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
| #Phix | Phix | +------------> start
|
+--+--+-----+
| | | ---+---> 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
| #Factor | Factor | USING: dice generalizations kernel math prettyprint sequences ;
IN: rosetta-code.dice-probabilities
: winning-prob ( a b c d -- p )
[ [ random-roll ] 2bi@ > ] 4 ncurry [ 100000 ] dip replicate
[ [ t = ] count ] [ length ] bi /f ;
9 4 6 6 winning-prob
5 10 6 7 winning-prob [ . ] bi@ |
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
| #Gambas | Gambas | ' Gambas module file
Public Sub Main()
Dim iSides, iPlayer1, iPlayer2, iTotal1, iTotal2, iCount, iCount0 As Integer
Dim iDice1 As Integer = 9
Dim iDice2 As Integer = 6
Dim iSides1 As Integer = 4
Dim iSides2 As Integer = 6
Randomize
For iCount0 = 0 To 1
For iCount = 1 To 100000
iPlayer1 = Roll(iDice1, iSides1)
iPlayer2 = Roll(iDice2, iSides2)
If iPlayer1 > iPlayer2 Then
iTotal1 += 1
Else If iPlayer1 <> iPlayer2 Then
iTotal2 += 1
Endif
Next
Print "Tested " & Str(iCount - 1) & " times"
Print "Player1 with " & Str(iDice1) & " dice of " & Str(iSides1) & " sides"
Print "Player2 with " & Str(iDice2) & " dice of " & Str(iSides2) & " sides"
Print "Total wins Player1 = " & Str(iTotal1) & " - " & Str(iTotal2 / iTotal1)
Print "Total wins Player2 = " & Str(iTotal2)
Print Str((iCount - 1) - (iTotal1 + iTotal2)) & " draws" & gb.NewLine
iDice1 = 5
iDice2 = 6
iSides1 = 10
iSides2 = 7
iTotal1 = 0
iTotal2 = 0
Next
End
Public Sub Roll(iDice As Integer, iSides As Integer) As Integer
Dim iCount, iTotal As Short
For iCount = 1 To iDice
iTotal += Rand(1, iSides)
Next
Return iTotal
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Single_Instance is
package IO renames Ada.Text_IO;
Lock_File: IO.File_Type;
Lock_File_Name: String := "single_instance.magic_lock";
begin
begin
IO.Open(File => Lock_File, Mode=> IO.In_File, Name => Lock_File_Name);
IO.Close(Lock_File);
IO.Put_Line("I can't -- another instance of me is running ...");
exception
when IO.Name_Error =>
IO.Put_Line("I can run!");
IO.Create(File => Lock_File, Name => Lock_File_Name);
for I in 1 .. 10 loop
IO.Put(Integer'Image(I));
delay 1.0; -- wait one second
end loop;
IO.Delete(Lock_File);
IO.New_Line;
IO.Put_Line("I am done!");
end;
exception
when others => IO.Delete(Lock_File);
end Single_Instance; |
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.
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Dining_Philosophers
{
class Program
{
private const int DinerCount = 5;
private static List<Diner> Diners = new List<Diner>();
private static List<Fork> Forks = new List<Fork>();
private static DateTime TimeToStop;
static void Main(string[] args)
{
Initialize();
WriteHeaderLine();
do
{
WriteStatusLine();
Thread.Sleep(1000);
}
while (DateTime.Now < TimeToStop);
TearDown();
}
private static void Initialize()
{
for (int i = 0; i < DinerCount; i++)
Forks.Add(new Fork());
for (int i = 0; i < DinerCount; i++)
Diners.Add(new Diner(i, Forks[i], Forks[(i + 1) % DinerCount]));
TimeToStop = DateTime.Now.AddSeconds(60);
}
private static void TearDown()
{
foreach (var diner in Diners)
diner.Dispose();
}
private static void WriteHeaderLine()
{
Console.Write("|");
foreach (Diner d in Diners)
Console.Write("D " + d.ID + "|");
Console.Write(" |");
for (int i = 0; i < DinerCount; i++)
Console.Write("F" + i + "|");
Console.WriteLine();
}
private static void WriteStatusLine()
{
Console.Write("|");
foreach (Diner d in Diners)
Console.Write(FormatDinerState(d) + "|");
Console.Write(" |");
foreach (Fork f in Forks)
Console.Write(FormatForkState(f) + "|");
Console.WriteLine();
}
private static string FormatDinerState(Diner diner)
{
switch (diner.State)
{
case Diner.DinerState.Eating:
return "Eat";
case Diner.DinerState.Pondering:
return "Pon";
case Diner.DinerState.TryingToGetForks:
return "Get";
default:
throw new Exception("Unknown diner state.");
}
}
private static string FormatForkState(Fork fork)
{
return (!ForkIsBeingUsed(fork) ? " " : "D" + GetForkHolder(fork));
}
private static bool ForkIsBeingUsed(Fork fork)
{
return Diners.Count(d => d.CurrentlyHeldForks.Contains(fork)) > 0;
}
private static int GetForkHolder(Fork fork)
{
return Diners.Single(d => d.CurrentlyHeldForks.Contains(fork)).ID;
}
}
class Diner : IDisposable
{
private bool IsCurrentlyHoldingLeftFork = false;
private bool IsCurrentlyHoldingRightFork = false;
private const int MaximumWaitTime = 100;
private static Random Randomizer = new Random();
private bool ShouldStopEating = false;
public int ID { get; private set; }
public Fork LeftFork { get; private set; }
public Fork RightFork { get; private set; }
public DinerState State { get; private set; }
public IEnumerable<Fork> CurrentlyHeldForks
{
get
{
var forks = new List<Fork>();
if (IsCurrentlyHoldingLeftFork)
forks.Add(LeftFork);
if (IsCurrentlyHoldingRightFork)
forks.Add(RightFork);
return forks;
}
}
public Diner(int id, Fork leftFork, Fork rightFork)
{
InitializeDinerState(id, leftFork, rightFork);
BeginDinerActivity();
}
private void KeepTryingToEat()
{
do
if (State == DinerState.TryingToGetForks)
{
TryToGetLeftFork();
if (IsCurrentlyHoldingLeftFork)
{
TryToGetRightFork();
if (IsCurrentlyHoldingRightFork)
{
Eat();
DropForks();
Ponder();
}
else
{
DropForks();
WaitForAMoment();
}
}
else
WaitForAMoment();
}
else
State = DinerState.TryingToGetForks;
while (!ShouldStopEating);
}
private void InitializeDinerState(int id, Fork leftFork, Fork rightFork)
{
ID = id;
LeftFork = leftFork;
RightFork = rightFork;
State = DinerState.TryingToGetForks;
}
private async void BeginDinerActivity()
{
await Task.Run(() => KeepTryingToEat());
}
private void TryToGetLeftFork()
{
Monitor.TryEnter(LeftFork, ref IsCurrentlyHoldingLeftFork);
}
private void TryToGetRightFork()
{
Monitor.TryEnter(RightFork, ref IsCurrentlyHoldingRightFork);
}
private void DropForks()
{
DropLeftFork();
DropRightFork();
}
private void DropLeftFork()
{
if (IsCurrentlyHoldingLeftFork)
{
IsCurrentlyHoldingLeftFork = false;
Monitor.Exit(LeftFork);
}
}
private void DropRightFork()
{
if (IsCurrentlyHoldingRightFork)
{
IsCurrentlyHoldingRightFork = false;
Monitor.Exit(RightFork);
}
}
private void Eat()
{
State = DinerState.Eating;
WaitForAMoment();
}
private void Ponder()
{
State = DinerState.Pondering;
WaitForAMoment();
}
private static void WaitForAMoment()
{
Thread.Sleep(Randomizer.Next(MaximumWaitTime));
}
public void Dispose()
{
ShouldStopEating = true;
}
public enum DinerState
{
Eating,
TryingToGetForks,
Pondering
}
}
class Fork { }
}
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #BASIC | BASIC | #INCLUDE "datetime.bi"
DECLARE FUNCTION julian(AS DOUBLE) AS INTEGER
SeasonNames:
DATA "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"
Weekdays:
DATA "Setting Orange", "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle"
DaysPreceding1stOfMonth:
' jan feb mar apr may jun jul aug sep oct nov dec
DATA 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
DIM dyear AS INTEGER, dseason AS STRING, dday AS INTEGER, dweekday AS STRING
DIM tmpdate AS DOUBLE, jday AS INTEGER, result AS STRING
DIM L0 AS INTEGER
IF LEN(COMMAND$) THEN
tmpdate = DATEVALUE(COMMAND$)
ELSE
tmpdate = FIX(NOW())
END IF
dyear = YEAR(tmpdate) + 1166
IF (2 = MONTH(tmpdate)) AND (29 = DAY(tmpdate)) THEN
result = "Saint Tib's Day, " & STR$(dyear) & " YOLD"
ELSE
jday = julian(tmpdate)
RESTORE SeasonNames
FOR L0 = 1 TO ((jday - 1) \ 73) + 1
READ dseason
NEXT
dday = (jday MOD 73)
IF 0 = dday THEN dday = 73
RESTORE Weekdays
FOR L0 = 1 TO (jday MOD 5) + 1
READ dweekday
NEXT
result = dweekday & ", " & dseason & " " & TRIM$(STR$(dday)) & ", " & TRIM$(STR$(dyear)) & " YOLD"
END IF
? result
END
FUNCTION julian(d AS DOUBLE) AS INTEGER
'doesn't account for leap years (not needed for ddate)
DIM tmp AS INTEGER, L1 AS INTEGER
RESTORE DaysPreceding1stOfMonth
FOR L1 = 1 TO MONTH(d)
READ tmp
NEXT
FUNCTION = tmp + DAY(d)
END FUNCTION |
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)
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef struct {
int vertex;
int weight;
} edge_t;
typedef struct {
edge_t **edges;
int edges_len;
int edges_size;
int dist;
int prev;
int visited;
} vertex_t;
typedef struct {
vertex_t **vertices;
int vertices_len;
int vertices_size;
} graph_t;
typedef struct {
int *data;
int *prio;
int *index;
int len;
int size;
} heap_t;
void add_vertex (graph_t *g, int i) {
if (g->vertices_size < i + 1) {
int size = g->vertices_size * 2 > i ? g->vertices_size * 2 : i + 4;
g->vertices = realloc(g->vertices, size * sizeof (vertex_t *));
for (int j = g->vertices_size; j < size; j++)
g->vertices[j] = NULL;
g->vertices_size = size;
}
if (!g->vertices[i]) {
g->vertices[i] = calloc(1, sizeof (vertex_t));
g->vertices_len++;
}
}
void add_edge (graph_t *g, int a, int b, int w) {
a = a - 'a';
b = b - 'a';
add_vertex(g, a);
add_vertex(g, b);
vertex_t *v = g->vertices[a];
if (v->edges_len >= v->edges_size) {
v->edges_size = v->edges_size ? v->edges_size * 2 : 4;
v->edges = realloc(v->edges, v->edges_size * sizeof (edge_t *));
}
edge_t *e = calloc(1, sizeof (edge_t));
e->vertex = b;
e->weight = w;
v->edges[v->edges_len++] = e;
}
heap_t *create_heap (int n) {
heap_t *h = calloc(1, sizeof (heap_t));
h->data = calloc(n + 1, sizeof (int));
h->prio = calloc(n + 1, sizeof (int));
h->index = calloc(n, sizeof (int));
return h;
}
void push_heap (heap_t *h, int v, int p) {
int i = h->index[v] == 0 ? ++h->len : h->index[v];
int j = i / 2;
while (i > 1) {
if (h->prio[j] < p)
break;
h->data[i] = h->data[j];
h->prio[i] = h->prio[j];
h->index[h->data[i]] = i;
i = j;
j = j / 2;
}
h->data[i] = v;
h->prio[i] = p;
h->index[v] = i;
}
int min (heap_t *h, int i, int j, int k) {
int m = i;
if (j <= h->len && h->prio[j] < h->prio[m])
m = j;
if (k <= h->len && h->prio[k] < h->prio[m])
m = k;
return m;
}
int pop_heap (heap_t *h) {
int v = h->data[1];
int i = 1;
while (1) {
int j = min(h, h->len, 2 * i, 2 * i + 1);
if (j == h->len)
break;
h->data[i] = h->data[j];
h->prio[i] = h->prio[j];
h->index[h->data[i]] = i;
i = j;
}
h->data[i] = h->data[h->len];
h->prio[i] = h->prio[h->len];
h->index[h->data[i]] = i;
h->len--;
return v;
}
void dijkstra (graph_t *g, int a, int b) {
int i, j;
a = a - 'a';
b = b - 'a';
for (i = 0; i < g->vertices_len; i++) {
vertex_t *v = g->vertices[i];
v->dist = INT_MAX;
v->prev = 0;
v->visited = 0;
}
vertex_t *v = g->vertices[a];
v->dist = 0;
heap_t *h = create_heap(g->vertices_len);
push_heap(h, a, v->dist);
while (h->len) {
i = pop_heap(h);
if (i == b)
break;
v = g->vertices[i];
v->visited = 1;
for (j = 0; j < v->edges_len; j++) {
edge_t *e = v->edges[j];
vertex_t *u = g->vertices[e->vertex];
if (!u->visited && v->dist + e->weight <= u->dist) {
u->prev = i;
u->dist = v->dist + e->weight;
push_heap(h, e->vertex, u->dist);
}
}
}
}
void print_path (graph_t *g, int i) {
int n, j;
vertex_t *v, *u;
i = i - 'a';
v = g->vertices[i];
if (v->dist == INT_MAX) {
printf("no path\n");
return;
}
for (n = 1, u = v; u->dist; u = g->vertices[u->prev], n++)
;
char *path = malloc(n);
path[n - 1] = 'a' + i;
for (j = 0, u = v; u->dist; u = g->vertices[u->prev], j++)
path[n - j - 2] = 'a' + u->prev;
printf("%d %.*s\n", v->dist, n, path);
}
int main () {
graph_t *g = calloc(1, sizeof (graph_t));
add_edge(g, 'a', 'b', 7);
add_edge(g, 'a', 'c', 9);
add_edge(g, 'a', 'f', 14);
add_edge(g, 'b', 'c', 10);
add_edge(g, 'b', 'd', 15);
add_edge(g, 'c', 'd', 11);
add_edge(g, 'c', 'f', 2);
add_edge(g, 'd', 'e', 6);
add_edge(g, 'e', 'f', 9);
dijkstra(g, 'a', 'e');
print_path(g, 'e');
return 0;
} |
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
| #AWK | AWK | # syntax: GAWK -f DIGITAL_ROOT.AWK
BEGIN {
n = split("627615,39390,588225,393900588225,10,199",arr,",")
for (i=1; i<=n; i++) {
dr = digitalroot(arr[i],10)
printf("%12.0f has additive persistence %d and digital root of %d\n",arr[i],p,dr)
}
exit(0)
}
function digitalroot(n,b) {
p = 0 # global
while (n >= b) {
p++
n = digitsum(n,b)
}
return(n)
}
function digitsum(n,b, q,s) {
while (n != 0) {
q = int(n / b)
s += n - q * b
n = q
}
return(s)
} |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
{\displaystyle 0}
.
While
m
{\displaystyle m}
has more than one digit:
Find a replacement
m
{\displaystyle m}
as the multiplication of the digits of the current value of
m
{\displaystyle m}
.
Increment
i
{\displaystyle i}
.
Return
i
{\displaystyle i}
(= MP) and
m
{\displaystyle m}
(= MDR)
Task
Tabulate the MP and MDR of the numbers 123321, 7739, 893, 899998
Tabulate MDR versus the first five numbers having that MDR, something like:
MDR: [n0..n4]
=== ========
0: [0, 10, 20, 25, 30]
1: [1, 11, 111, 1111, 11111]
2: [2, 12, 21, 26, 34]
3: [3, 13, 31, 113, 131]
4: [4, 14, 22, 27, 39]
5: [5, 15, 35, 51, 53]
6: [6, 16, 23, 28, 32]
7: [7, 17, 71, 117, 171]
8: [8, 18, 24, 29, 36]
9: [9, 19, 33, 91, 119]
Show all output on this page.
Similar
The Product of decimal digits of n page was redirected here, and had the following description
Find the product of the decimal digits of a positive integer n, where n <= 100
The three existing entries for Phix, REXX, and Ring have been moved here, under ===Similar=== headings, feel free to match or ignore them.
References
Multiplicative Digital Root on Wolfram Mathworld.
Multiplicative digital root on The On-Line Encyclopedia of Integer Sequences.
What's special about 277777788888899? - Numberphile video
| #Factor | Factor | USING: arrays formatting fry io kernel lists lists.lazy math
math.text.utils prettyprint sequences ;
IN: rosetta-code.multiplicative-digital-root
: mdr ( n -- {persistence,root} )
0 swap
[ 1 digit-groups dup length 1 > ] [ product [ 1 + ] dip ] while
dup empty? [ drop { 0 } ] when first 2array ;
: print-mdr ( n -- )
dup [ 1array ] dip mdr append
"%-12d has multiplicative persistence %d and MDR %d.\n"
vprintf ;
: first5 ( n -- seq ) ! first 5 numbers with MDR of n
0 lfrom swap '[ mdr second _ = ] lfilter 5 swap ltake list>array ;
: print-first5 ( i n -- )
"%-5d" printf bl first5 [ "%-5d " printf ] each nl ;
: header ( -- )
"MDR | First five numbers with that MDR" print
"--------------------------------------" print ;
: first5-table ( -- )
header 10 iota [ print-first5 ] each-index ;
: main ( -- )
{ 123321 7739 893 899998 } [ print-mdr ] each nl first5-table ;
MAIN: main |
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.
| #TI-89_BASIC | TI-89 BASIC | Define dragon = (iter, xform)
Prgm
Local a,b
If iter > 0 Then
dragon(iter-1, xform*[[.5,.5,0][–.5,.5,0][0,0,1]])
dragon(iter-1, xform*[[–.5,.5,0][–.5,–.5,1][0,0,1]])
Else
xform*[0;0;1]→a
xform*[0;1;1]→b
PxlLine floor(a[1,1]), floor(a[2,1]), floor(b[1,1]), floor(b[2,1])
EndIf
EndPrgm
FnOff
PlotsOff
ClrDraw
dragon(7, [[75,0,26] [0,75,47] [0,0,1]]) |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued.
Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns.
Example output should be shown here, as well as any comments on the examples flexibility.
The problem
Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment house that contains only five floors.
Baker does not live on the top floor.
Cooper does not live on the bottom floor.
Fletcher does not live on either the top or the bottom floor.
Miller lives on a higher floor than does Cooper.
Smith does not live on a floor adjacent to Fletcher's.
Fletcher does not live on a floor adjacent to Cooper's.
Where does everyone live?
| #Clojure | Clojure | (ns rosettacode.dinesman
(:use [clojure.core.logic]
[clojure.tools.macro :as macro]))
; whether x is immediately above (left of) y in list s; uses pattern matching on s
(defne aboveo [x y s]
([_ _ (x y . ?rest)])
([_ _ [_ . ?rest]] (aboveo x y ?rest)))
; whether x is on a higher floor than y
(defne highero [x y s]
([_ _ (x . ?rest)] (membero y ?rest))
([_ _ (_ . ?rest)] (highero x y ?rest)))
; whether x and y are on nonadjacent floors
(defn nonadjacento [x y s]
(conda
((aboveo x y s) fail)
((aboveo y x s) fail)
(succeed)))
(defn dinesmano [rs]
(macro/symbol-macrolet [_ (lvar)]
(all
(permuteo ['Baker 'Cooper 'Fletcher 'Miller 'Smith] rs)
(aboveo _ 'Baker rs) ;someone lives above Baker
(aboveo 'Cooper _ rs) ;Cooper lives above someone
(aboveo 'Fletcher _ rs)
(aboveo _ 'Fletcher rs)
(highero 'Miller 'Cooper rs)
(nonadjacento 'Smith 'Fletcher rs)
(nonadjacento 'Fletcher 'Cooper rs))))
(let [solns (run* [q] (dinesmano q))]
(println "solution count:" (count solns))
(println "solution(s) highest to lowest floor:")
(doseq [soln solns] (println " " soln)))
|
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
| #Common_Lisp | Common Lisp | (defun dot-product (a b)
(apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list)))) |
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
| #PicoLisp | PicoLisp | +------------> start
|
+--+--+-----+
| | | ---+---> 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
| #Go | Go | package main
import(
"math"
"fmt"
)
func minOf(x, y uint) uint {
if x < y {
return x
}
return y
}
func throwDie(nSides, nDice, s uint, counts []uint) {
if nDice == 0 {
counts[s]++
return
}
for i := uint(1); i <= nSides; i++ {
throwDie(nSides, nDice - 1, s + i, counts)
}
}
func beatingProbability(nSides1, nDice1, nSides2, nDice2 uint) float64 {
len1 := (nSides1 + 1) * nDice1
c1 := make([]uint, len1) // all elements zero by default
throwDie(nSides1, nDice1, 0, c1)
len2 := (nSides2 + 1) * nDice2
c2 := make([]uint, len2)
throwDie(nSides2, nDice2, 0, c2)
p12 := math.Pow(float64(nSides1), float64(nDice1)) *
math.Pow(float64(nSides2), float64(nDice2))
tot := 0.0
for i := uint(0); i < len1; i++ {
for j := uint(0); j < minOf(i, len2); j++ {
tot += float64(c1[i] * c2[j]) / p12
}
}
return tot
}
func main() {
fmt.Println(beatingProbability(4, 9, 6, 6))
fmt.Println(beatingProbability(10, 5, 7, 6))
} |
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.
| #AutoHotkey | AutoHotkey | PRAGMA INCLUDE <sys/file.h>
OPTION DEVICE O_NONBLOCK
OPEN ME$ FOR DEVICE AS me
IF flock(me, LOCK_EX | LOCK_NB) <> 0 THEN
PRINT "I am already running, exiting..."
END
ENDIF
PRINT "Running this program, doing things..."
SLEEP 5000
CLOSE DEVICE me |
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.
| #BaCon | BaCon | PRAGMA INCLUDE <sys/file.h>
OPTION DEVICE O_NONBLOCK
OPEN ME$ FOR DEVICE AS me
IF flock(me, LOCK_EX | LOCK_NB) <> 0 THEN
PRINT "I am already running, exiting..."
END
ENDIF
PRINT "Running this program, doing things..."
SLEEP 5000
CLOSE DEVICE me |
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.
| #Bash_Shell | Bash Shell |
local fd=${2:-200}
# create lock file
eval "exec $fd>/tmp/my_lock.lock"
# acquire the lock, or fail
flock -nx $fd \
&& # do something if you got the lock \
|| # do something if you did not get the lock
|
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.
| #BBC_BASIC | BBC BASIC | SYS "CreateMutex", 0, 1, "UniqueLockName" TO Mutex%
SYS "GetLastError" TO lerr%
IF lerr% = 183 THEN
SYS "CloseHandle", Mutex%
SYS "MessageBox", @hwnd%, "I am already running", 0, 0
QUIT
ENDIF
SYS "ReleaseMutex", Mutex%
SYS "CloseHandle", Mutex%
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.
| #C.2B.2B | C++ | #include <algorithm>
#include <array>
#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <string>
#include <string_view>
#include <thread>
const int timeScale = 42; // scale factor for the philosophers task duration
void Message(std::string_view message)
{
// thread safe printing
static std::mutex cout_mutex;
std::scoped_lock cout_lock(cout_mutex);
std::cout << message << std::endl;
}
struct Fork {
std::mutex mutex;
};
struct Dinner {
std::array<Fork, 5> forks;
~Dinner() { Message("Dinner is over"); }
};
class Philosopher
{
// generates random numbers using the Mersenne Twister algorithm
// for task times and messages
std::mt19937 rng{std::random_device {}()};
const std::string name;
Fork& left;
Fork& right;
std::thread worker;
void live();
void dine();
void ponder();
public:
Philosopher(std::string name_, Fork& l, Fork& r)
: name(std::move(name_)), left(l), right(r), worker(&Philosopher::live, this)
{}
~Philosopher()
{
worker.join();
Message(name + " went to sleep.");
}
};
void Philosopher::live()
{
for(;;) // run forever
{
{
//Aquire forks. scoped_lock acquires the mutexes for
//both forks using a deadlock avoidance algorithm
std::scoped_lock dine_lock(left.mutex, right.mutex);
dine();
//The mutexes are released here at the end of the scope
}
ponder();
}
}
void Philosopher::dine()
{
Message(name + " started eating.");
// Print some random messages while the philosopher is eating
thread_local std::array<const char*, 3> foods {"chicken", "rice", "soda"};
thread_local std::array<const char*, 3> reactions {
"I like this %s!", "This %s is good.", "Mmm, %s..."
};
thread_local std::uniform_int_distribution<> dist(1, 6);
std::shuffle( foods.begin(), foods.end(), rng);
std::shuffle(reactions.begin(), reactions.end(), rng);
constexpr size_t buf_size = 64;
char buffer[buf_size];
for(int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng) * timeScale));
snprintf(buffer, buf_size, reactions[i], foods[i]);
Message(name + ": " + buffer);
}
std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)) * timeScale);
Message(name + " finished and left.");
}
void Philosopher::ponder()
{
static constexpr std::array<const char*, 5> topics {{
"politics", "art", "meaning of life", "source of morality", "how many straws makes a bale"
}};
thread_local std::uniform_int_distribution<> wait(1, 6);
thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1);
while(dist(rng) > 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is pondering about " + topics[dist(rng)] + ".");
}
std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng) * 3 * timeScale));
Message(name + " is hungry again!");
}
int main()
{
Dinner dinner;
Message("Dinner started!");
// The philosophers will start as soon as they are created
std::array<Philosopher, 5> philosophers {{
{"Aristotle", dinner.forks[0], dinner.forks[1]},
{"Democritus", dinner.forks[1], dinner.forks[2]},
{"Plato", dinner.forks[2], dinner.forks[3]},
{"Pythagoras", dinner.forks[3], dinner.forks[4]},
{"Socrates", dinner.forks[4], dinner.forks[0]},
}};
Message("It is dark outside...");
} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Batch_File | Batch File | @echo off
goto Parse
Discordian Date Converter:
Usage:
ddate
ddate /v
ddate /d isoDate
ddate /v /d isoDate
:Parse
shift
if "%0"=="" goto Prologue
if "%0"=="/v" set Verbose=1
if "%0"=="/d" set dateToTest=%1
if "%0"=="/d" shift
goto Parse
:Prologue
if "%dateToTest%"=="" set dateToTest=%date%
for %%a in (GYear GMonth GDay GMonthName GWeekday GDayThisYear) do set %%a=fnord
for %%a in (DYear DMonth DDay DMonthName DWeekday) do set %%a=MUNG
goto Start
:Start
for /f "tokens=1,2,3 delims=/:;-. " %%a in ('echo %dateToTest%') do (
set GYear=%%a
set GMonth=%%b
set GDay=%%c
)
goto GMonthName
:GMonthName
if %GMonth% EQU 1 set GMonthName=January
if %GMonth% EQU 2 set GMonthName=February
if %GMonth% EQU 3 set GMonthName=March
if %GMonth% EQU 4 set GMonthName=April
if %GMonth% EQU 5 set GMonthName=May
if %GMonth% EQU 6 set GMonthName=June
if %GMonth% EQU 7 set GMonthName=July
if %GMonth% EQU 8 set GMonthName=August
if %GMonth% EQU 9 set GMonthName=September
if %GMonth% EQU 10 set GMonthName=October
if %GMonth% EQU 11 set GMonthName=November
if %GMonth% EQU 12 set GMonthName=December
goto GLeap
:GLeap
set /a CommonYear=GYear %% 4
set /a CommonCent=GYear %% 100
set /a CommonQuad=GYear %% 400
set GLeap=0
if %CommonYear% EQU 0 set GLeap=1
if %CommonCent% EQU 0 set GLeap=0
if %CommonQuad% EQU 0 set GLeap=1
goto GDayThisYear
:GDayThisYear
set GDayThisYear=%GDay%
if %GMonth% GTR 11 set /a GDayThisYear=%GDayThisYear%+30
if %GMonth% GTR 10 set /a GDayThisYear=%GDayThisYear%+31
if %GMonth% GTR 9 set /a GDayThisYear=%GDayThisYear%+30
if %GMonth% GTR 8 set /a GDayThisYear=%GDayThisYear%+31
if %GMonth% GTR 7 set /a GDayThisYear=%GDayThisYear%+31
if %GMonth% GTR 6 set /a GDayThisYear=%GDayThisYear%+30
if %GMonth% GTR 5 set /a GDayThisYear=%GDayThisYear%+31
if %GMonth% GTR 4 set /a GDayThisYear=%GDayThisYear%+30
if %GMonth% GTR 3 set /a GDayThisYear=%GDayThisYear%+31
if %GMonth% GTR 2 if %GLeap% EQU 1 set /a GDayThisYear=%GDayThisYear%+29
if %GMonth% GTR 2 if %GLeap% EQU 0 set /a GDayThisYear=%GDayThisYear%+28
if %GMonth% GTR 1 set /a GDayThisYear=%GDayThisYear%+31
goto DYear
:DYear
set /a DYear=GYear+1166
goto DMonth
:DMonth
set DMonth=1
set DDay=%GDayThisYear%
if %DDay% GTR 73 (
set /a DDay=%DDay%-73
set /a DMonth=%DMonth%+1
)
if %DDay% GTR 73 (
set /a DDay=%DDay%-73
set /a DMonth=%DMonth%+1
)
if %DDay% GTR 73 (
set /a DDay=%DDay%-73
set /a DMonth=%DMonth%+1
)
if %DDay% GTR 73 (
set /a DDay=%DDay%-73
set /a DMonth=%DMonth%+1
)
goto DDay
:DDay
if %GLeap% EQU 1 (
if %GDayThisYear% GEQ 61 (
set /a DDay=%DDay%-1
)
)
if %DDay% EQU 0 (
set /a DDay=73
set /a DMonth=%DMonth%-1
)
goto DMonthName
:DMonthName
if %DMonth% EQU 1 set DMonthName=Chaos
if %DMonth% EQU 2 set DMonthName=Discord
if %DMonth% EQU 3 set DMonthName=Confusion
if %DMonth% EQU 4 set DMonthName=Bureaucracy
if %DMonth% EQU 5 set DMonthName=Aftermath
goto DTib
:DTib
set DTib=0
if %GDayThisYear% EQU 60 if %GLeap% EQU 1 set DTib=1
if %GLeap% EQU 1 if %GDayThisYear% GTR 60 set /a GDayThisYear=%GDayThisYear%-1
set DWeekday=%GDayThisYear%
goto DWeekday
:DWeekday
if %DWeekday% LEQ 5 goto _DWeekday
set /a DWeekday=%DWeekday%-5
goto DWeekday
:_DWeekday
if %DWeekday% EQU 1 set DWeekday=Sweetmorn
if %DWeekday% EQU 2 set DWeekday=Boomtime
if %DWeekday% EQU 3 set DWeekday=Pungenday
if %DWeekday% EQU 4 set DWeekday=Prickle-Prickle
if %DWeekday% EQU 5 set DWeekday=Setting Orange
goto GWeekday
:GWeekday
goto GEnding
:GEnding
set GEnding=th
for %%a in (1 21 31) do if %GDay% EQU %%a set GEnding=st
for %%a in (2 22) do if %GDay% EQU %%a set GEnding=nd
for %%a in (3 23) do if %GDay% EQU %%a set GEnding=rd
goto DEnding
:DEnding
set DEnding=th
for %%a in (1 21 31 41 51 61 71) do if %Dday% EQU %%a set DEnding=st
for %%a in (2 22 32 42 52 62 72) do if %Dday% EQU %%a set DEnding=nd
for %%a in (3 23 33 43 53 63 73) do if %Dday% EQU %%a set DEnding=rd
goto Display
:Display
if "%Verbose%"=="1" goto Display2
echo.
if %DTib% EQU 1 (
echo St. Tib's Day, %DYear%
) else echo %DWeekday%, %DMonthName% %DDay%%DEnding%, %DYear%
goto Epilogue
:Display2
echo.
echo Gregorian: %GMonthName% %GDay%%GEnding%, %GYear%
if %DTib% EQU 1 (
echo Discordian: St. Tib's Day, %DYear%
) else echo Discordian: %DWeekday%, %DMonthName% %DDay%%DEnding%, %DYear%
goto Epilogue
:Epilogue
set Verbose=
set dateToTest=
echo.
: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)
| #C.23 | C# | using static System.Linq.Enumerable;
using static System.String;
using static System.Console;
using System.Collections.Generic;
using System;
using EdgeList = System.Collections.Generic.List<(int node, double weight)>;
public static class Dijkstra
{
public static void Main() {
Graph graph = new Graph(6);
Func<char, int> id = c => c - 'a';
Func<int , char> name = i => (char)(i + 'a');
foreach (var (start, end, cost) in new [] {
('a', 'b', 7),
('a', 'c', 9),
('a', 'f', 14),
('b', 'c', 10),
('b', 'd', 15),
('c', 'd', 11),
('c', 'f', 2),
('d', 'e', 6),
('e', 'f', 9),
}) {
graph.AddEdge(id(start), id(end), cost);
}
var path = graph.FindPath(id('a'));
for (int d = id('b'); d <= id('f'); d++) {
WriteLine(Join(" -> ", Path(id('a'), d).Select(p => $"{name(p.node)}({p.distance})").Reverse()));
}
IEnumerable<(double distance, int node)> Path(int start, int destination) {
yield return (path[destination].distance, destination);
for (int i = destination; i != start; i = path[i].prev) {
yield return (path[path[i].prev].distance, path[i].prev);
}
}
}
}
sealed class Graph
{
private readonly List<EdgeList> adjacency;
public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();
public int Count => adjacency.Count;
public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);
public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;
public bool AddEdge(int s, int e, double weight) {
if (HasEdge(s, e)) return false;
adjacency[s].Add((e, weight));
return true;
}
public (double distance, int prev)[] FindPath(int start) {
var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();
info[start].distance = 0;
var visited = new System.Collections.BitArray(adjacency.Count);
var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));
heap.Push((start, 0));
while (heap.Count > 0) {
var current = heap.Pop();
if (visited[current.node]) continue;
var edges = adjacency[current.node];
for (int n = 0; n < edges.Count; n++) {
int v = edges[n].node;
if (visited[v]) continue;
double alt = info[current.node].distance + edges[n].weight;
if (alt < info[v].distance) {
info[v] = (alt, current.node);
heap.Push((v, alt));
}
}
visited[current.node] = true;
}
return info;
}
}
sealed class Heap<T>
{
private readonly IComparer<T> comparer;
private readonly List<T> list = new List<T> { default };
public Heap() : this(default(IComparer<T>)) { }
public Heap(IComparer<T> comparer) {
this.comparer = comparer ?? Comparer<T>.Default;
}
public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }
public int Count => list.Count - 1;
public void Push(T element) {
list.Add(element);
SiftUp(list.Count - 1);
}
public T Pop() {
T result = list[1];
list[1] = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
SiftDown(1);
return result;
}
private static int Parent(int i) => i / 2;
private static int Left(int i) => i * 2;
private static int Right(int i) => i * 2 + 1;
private void SiftUp(int i) {
while (i > 1) {
int parent = Parent(i);
if (comparer.Compare(list[i], list[parent]) > 0) return;
(list[parent], list[i]) = (list[i], list[parent]);
i = parent;
}
}
private void SiftDown(int i) {
for (int left = Left(i); left < list.Count; left = Left(i)) {
int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;
int right = Right(i);
if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;
if (smallest == i) return;
(list[i], list[smallest]) = (list[smallest], list[i]);
i = smallest;
}
}
} |
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
| #BASIC | BASIC | DECLARE SUB digitalRoot (what AS LONG)
'test inputs:
digitalRoot 627615
digitalRoot 39390
digitalRoot 588225
SUB digitalRoot (what AS LONG)
DIM w AS LONG, t AS LONG, c AS INTEGER
w = ABS(what)
IF w > 10 THEN
DO
c = c + 1
WHILE w
t = t + (w MOD (10))
w = w \ 10
WEND
w = t
t = 0
LOOP WHILE w > 9
END IF
PRINT what; ": additive persistance "; c; ", digital root "; w
END SUB |
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
| #Fortran | Fortran |
!Implemented by Anant Dixit (Oct, 2014)
program mdr
implicit none
integer :: i, mdr, mp, n, j
character(len=*), parameter :: hfmt = '(A18)', nfmt = '(I6)'
character(len=*), parameter :: cfmt = '(A3)', rfmt = '(I3)', ffmt = '(I9)'
write(*,hfmt) 'Number MDR MP '
write(*,*) '------------------'
i = 123321
call root_pers(i,mdr,mp)
write(*,nfmt,advance='no') i
write(*,cfmt,advance='no') ' '
write(*,rfmt,advance='no') mdr
write(*,cfmt,advance='no') ' '
write(*,rfmt) mp
i = 3939
call root_pers(i,mdr,mp)
write(*,nfmt,advance='no') i
write(*,cfmt,advance='no') ' '
write(*,rfmt,advance='no') mdr
write(*,cfmt,advance='no') ' '
write(*,rfmt) mp
i = 8822
call root_pers(i,mdr,mp)
write(*,nfmt,advance='no') i
write(*,cfmt,advance='no') ' '
write(*,rfmt,advance='no') mdr
write(*,cfmt,advance='no') ' '
write(*,rfmt) mp
i = 39398
call root_pers(i,mdr,mp)
write(*,nfmt,advance='no') i
write(*,cfmt,advance='no') ' '
write(*,rfmt,advance='no') mdr
write(*,cfmt,advance='no') ' '
write(*,rfmt) mp
write(*,*)
write(*,*)
write(*,*) 'First five numbers with MDR in first column: '
write(*,*) '---------------------------------------------'
do i = 0,9
n = 0
j = 0
write(*,rfmt,advance='no') i
do
call root_pers(j,mdr,mp)
if(mdr.eq.i) then
n = n+1
if(n.eq.5) then
write(*,ffmt) j
exit
else
write(*,ffmt,advance='no') j
end if
end if
j = j+1
end do
end do
end program
subroutine root_pers(i,mdr,mp)
implicit none
integer :: N, s, a, i, mdr, mp
n = i
a = 0
if(n.lt.10) then
mdr = n
mp = 0
return
end if
do while(n.ge.10)
a = a + 1
s = 1
do while(n.gt.0)
s = s * mod(n,10)
n = int(real(n)/10.0D0)
end do
n = s
end do
mdr = s
mp = a
end subroutine
|
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.
| #Vedit_macro_language | Vedit macro language | File_Open("|(USER_MACRO)\dragon.bmp", OVERWRITE+NOEVENT)
BOF Del_Char(ALL)
#11 = 640 // width of the image
#12 = 480 // height of the image
Call("CREATE_BMP")
#1 = 384 // dx
#2 = 0 // dy
#3 = 6 // depth of recursion
#4 = 1 // flip
#5 = 150 // x
#6 = 300 // y
Call("DRAGON")
Buf_Close(NOMSG)
Sys(`start "" "|(USER_MACRO)\dragon.bmp"`, DOS+SUPPRESS+SIMPLE+NOWAIT)
return
/////////////////////////////////////////////////////////////////////
//
// Dragon fractal, recursive
//
:DRAGON:
if (#3 == 0) {
Call("DRAW_LINE")
} else {
#1 /= 2
#2 /= 2
#3--
if (#4) {
Num_Push(1,4) #4=1; #7=#1; #1=#2; #2=-#7; Call("DRAGON") Num_Pop(1,4)
Num_Push(1,4) #4=0; Call("DRAGON") Num_Pop(1,4)
Num_Push(1,4) #4=1; #7=#1; #1=-#2; #2=#7; Call("DRAGON") Num_Pop(1,4)
Num_Push(1,4) #4=0; Call("DRAGON") Num_Pop(1,4)
} else {
Num_Push(1,4) #4=1; Call("DRAGON") Num_Pop(1,4)
Num_Push(1,4) #4=0; #7=#1; #1=-#2; #2=#7; Call("DRAGON") Num_Pop(1,4)
Num_Push(1,4) #4=1; Call("DRAGON") Num_Pop(1,4)
Num_Push(1,4) #4=0; #7=#1; #1=#2; #2=-#7; Call("DRAGON") Num_Pop(1,4)
}
}
return
/////////////////////////////////////////////////////////////////////
//
// Daw a horizontal, vertical or diagonal line. #1 = dx, #2 = dy
//
:DRAW_LINE:
while (#1 || #2 ) {
#21 = (#1>0) - (#1<0)
#22 = (#2>0) - (#2<0)
#5 += #21; #1 -= #21
#6 += #22; #2 -= #22
Goto_Pos(1078 + #5 + #6*#11)
IC(255, OVERWRITE) // plot a pixel
}
return
/////////////////////////////////////////////////////////////////////
//
// Create a bitmap file
//
:CREATE_BMP:
// BITMAPFILEHEADER:
IT("BM") // bfType
#10 = 1078+#11*#12 // file size
Call("INS_4BYTES")
IC(0, COUNT, 4) // reserved
#10 = 1078; Call("INS_4BYTES") // offset to bitmap data
// BITMAPINFOHEADER:
#10 = 40; Call("INS_4BYTES") // size of BITMAPINFOHEADER
#10 = #11; Call("INS_4BYTES") // width of image
#10 = #12; Call("INS_4BYTES") // height of image
IC(1) IC(0) // number of bitplanes = 1
IC(8) IC(0) // bits/pixel = 8
IC(0, COUNT, 24) // compression, number of colors etc.
// Color table - create greyscale palette
for (#1 = 0; #1 < 256; #1++) {
IC(#1) IC(#1) IC(#1) IC(0)
}
// Pixel data - init to black
for (#1 = 0; #1 < #12; #1++) {
IC(0, COUNT, #11)
}
return
//
// Write 32 bit binary value from #10 in the file
//
:INS_4BYTES:
for (#1 = 0; #1 < 4; #1++) {
Ins_Char(#10 & 0xff)
#10 = #10 >> 8
}
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?
| #Common_Lisp | Common Lisp |
(defpackage :dinesman
(:use :cl
:screamer)
(:export :dinesman :dinesman-list))
(in-package :dinesman)
(defun distinctp (list)
(equal list (remove-duplicates list)))
(defun dinesman ()
(all-values
(let ((baker (an-integer-between 1 5))
(cooper (an-integer-between 1 5))
(fletcher (an-integer-between 1 5))
(miller (an-integer-between 1 5))
(smith (an-integer-between 1 5)))
(unless (distinctp (list baker cooper fletcher miller smith)) (fail))
(when (= 5 baker) (fail))
(when (= 1 cooper) (fail))
(when (or (= 1 fletcher) (= 5 fletcher)) (fail))
(unless (> miller cooper) (fail))
(when (= 1 (abs (- fletcher smith))) (fail))
(when (= 1 (abs (- fletcher cooper))) (fail))
(format t "~{~A: ~A~%~}" (list 'baker baker 'cooper cooper 'fletcher fletcher 'miller miller 'smith smith)))))
(defun dinesman-list ()
(all-values
(let* ((men '(baker cooper fletcher miller smith))
(building (list (a-member-of men) (a-member-of men) (a-member-of men) (a-member-of men) (a-member-of men))))
(unless (distinctp building) (fail))
(when (eql (car (last building)) 'baker) (fail))
(when (eql (first building) 'cooper) (fail))
(when (or (eql (car (last building)) 'fletcher)
(eql (first building) 'fletcher))
(fail))
(unless (> (position 'miller building)
(position 'cooper building))
(fail))
(when (= 1 (abs (- (position 'fletcher building) (position 'smith building))))
(fail))
(when (= 1 (abs (- (position 'fletcher building) (position 'cooper building))))
(fail))
(format t "(~{~A~^ ~})~%" building))))
|
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
| #Component_Pascal | Component Pascal |
MODULE DotProduct;
IMPORT StdLog;
PROCEDURE Calculate*(x,y: ARRAY OF INTEGER): INTEGER;
VAR
i,sum: INTEGER;
BEGIN
sum := 0;
FOR i:= 0 TO LEN(x) - 1 DO
INC(sum,x[i] * y[i]);
END;
RETURN sum
END Calculate;
PROCEDURE Test*;
VAR
i,sum: INTEGER;
v1,v2: ARRAY 3 OF INTEGER;
BEGIN
v1[0] := 1;v1[1] := 3;v1[2] := -5;
v2[0] := 4;v2[1] := -2;v2[2] := -1;
StdLog.Int(Calculate(v1,v2));StdLog.Ln
END Test;
END DotProduct.
|
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
| #PL.2FI | PL/I |
define structure
1 Node,
2 value fixed decimal,
2 back_pointer handle(Node),
2 fwd_pointer handle(Node);
|
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
| #Haskell | Haskell | import Control.Monad (replicateM)
import Data.List (group, sort)
succeeds :: (Int, Int) -> (Int, Int) -> Double
succeeds p1 p2 =
sum
[ realToFrac (c1 * c2) / totalOutcomes
| (s1, c1) <- countSums p1
, (s2, c2) <- countSums p2
, s1 > s2 ]
where
totalOutcomes = realToFrac $ uncurry (^) p1 * uncurry (^) p2
countSums (nFaces, nDice) = f [1 .. nFaces]
where
f =
fmap (((,) . head) <*> (pred . length)) .
group . sort . fmap sum . replicateM nDice
main :: IO ()
main = do
print $ (4, 9) `succeeds` (6, 6)
print $ (10, 5) `succeeds` (7, 6) |
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.
| #C | C | #include <fcntl.h> /* fcntl, open */
#include <stdlib.h> /* atexit, getenv, malloc */
#include <stdio.h> /* fputs, printf, puts, snprintf */
#include <string.h> /* memcpy */
#include <unistd.h> /* sleep, unlink */
/* Filename for only_one_instance() lock. */
#define INSTANCE_LOCK "rosetta-code-lock"
void
fail(const char *message)
{
perror(message);
exit(1);
}
/* Path to only_one_instance() lock. */
static char *ooi_path;
void
ooi_unlink(void)
{
unlink(ooi_path);
}
/* Exit if another instance of this program is running. */
void
only_one_instance(void)
{
struct flock fl;
size_t dirlen;
int fd;
char *dir;
/*
* Place the lock in the home directory of this user;
* therefore we only check for other instances by the same
* user (and the user can trick us by changing HOME).
*/
dir = getenv("HOME");
if (dir == NULL || dir[0] != '/') {
fputs("Bad home directory.\n", stderr);
exit(1);
}
dirlen = strlen(dir);
ooi_path = malloc(dirlen + sizeof("/" INSTANCE_LOCK));
if (ooi_path == NULL)
fail("malloc");
memcpy(ooi_path, dir, dirlen);
memcpy(ooi_path + dirlen, "/" INSTANCE_LOCK,
sizeof("/" INSTANCE_LOCK)); /* copies '\0' */
fd = open(ooi_path, O_RDWR | O_CREAT, 0600);
if (fd < 0)
fail(ooi_path);
fl.l_start = 0;
fl.l_len = 0;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &fl) < 0) {
fputs("Another instance of this program is running.\n",
stderr);
exit(1);
}
/*
* Run unlink(ooi_path) when the program exits. The program
* always releases locks when it exits.
*/
atexit(ooi_unlink);
}
/*
* Demo for Rosetta Code.
* http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
*/
int
main()
{
int i;
only_one_instance();
/* Play for 10 seconds. */
for(i = 10; i > 0; i--) {
printf("%d...%s", i, i % 5 == 1 ? "\n" : " ");
fflush(stdout);
sleep(1);
}
puts("Fin!");
return 0;
} |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a round table with five individual seats. For eating each philosopher needs two forks (the resources). There are five forks on the table, one left and one right of each seat. When a philosopher cannot grab both forks it sits and waits. Eating takes random time, then the philosopher puts the forks down and leaves the dining room. After spending some random time thinking about the nature of the universe, he again becomes hungry, and the circle repeats itself.
It can be observed that a straightforward solution, when forks are implemented by semaphores, is exposed to deadlock. There exist two deadlock states when all five philosophers are sitting at the table holding one fork each. One deadlock state is when each philosopher has grabbed the fork left of him, and another is when each has the fork on his right.
There are many solutions of the problem, program at least one, and explain how the deadlock is prevented.
| #Clojure | Clojure | (defn make-fork []
(ref true))
(defn make-philosopher [name forks food-amt]
(ref {:name name :forks forks :eating? false :food food-amt}))
(defn start-eating [phil]
(dosync
(if (every? true? (map ensure (:forks @phil))) ; <-- the essential solution
(do
(doseq [f (:forks @phil)] (alter f not))
(alter phil assoc :eating? true)
(alter phil update-in [:food] dec)
true)
false)))
(defn stop-eating [phil]
(dosync
(when (:eating? @phil)
(alter phil assoc :eating? false)
(doseq [f (:forks @phil)] (alter f not)))))
(defn dine [phil retry-interval max-eat-duration max-think-duration]
(while (pos? (:food @phil))
(if (start-eating phil)
(do
(Thread/sleep (rand-int max-eat-duration))
(stop-eating phil)
(Thread/sleep (rand-int max-think-duration)))
(Thread/sleep retry-interval)))) |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"DATELIB"
PRINT "01/01/2011 -> " FNdiscordian("01/01/2011")
PRINT "05/01/2011 -> " FNdiscordian("05/01/2011")
PRINT "28/02/2011 -> " FNdiscordian("28/02/2011")
PRINT "01/03/2011 -> " FNdiscordian("01/03/2011")
PRINT "22/07/2011 -> " FNdiscordian("22/07/2011")
PRINT "31/12/2011 -> " FNdiscordian("31/12/2011")
PRINT "01/01/2012 -> " FNdiscordian("01/01/2012")
PRINT "05/01/2012 -> " FNdiscordian("05/01/2012")
PRINT "28/02/2012 -> " FNdiscordian("28/02/2012")
PRINT "29/02/2012 -> " FNdiscordian("29/02/2012")
PRINT "01/03/2012 -> " FNdiscordian("01/03/2012")
PRINT "22/07/2012 -> " FNdiscordian("22/07/2012")
PRINT "31/12/2012 -> " FNdiscordian("31/12/2012")
END
DEF FNdiscordian(date$)
LOCAL Season$(), Weekday$(), mjd%, year%, day%
DIM Season$(4), Weekday$(4)
Season$() = "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"
Weekday$() = "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"
mjd% = FN_readdate(date$, "dmy", 2000)
year% = FN_year(mjd%)
IF FN_month(mjd%)=2 AND FN_day(mjd%)=29 THEN
= "St. Tib's Day, YOLD " + STR$(year% + 1166)
ENDIF
IF FN_month(mjd%) < 3 THEN
day% = mjd% - FN_mjd(1, 1, year%)
ELSE
day% = mjd% - FN_mjd(1, 3, year%) + 59
ENDIF
= Weekday$(day% MOD 5) + ", " + STR$(day% MOD 73 + 1) + " " + \
\ Season$(day% DIV 73) + ", YOLD " + STR$(year% + 1166) |
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)
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <string>
#include <list>
#include <limits> // for numeric_limits
#include <set>
#include <utility> // for pair
#include <algorithm>
#include <iterator>
typedef int vertex_t;
typedef double weight_t;
const weight_t max_weight = std::numeric_limits<double>::infinity();
struct neighbor {
vertex_t target;
weight_t weight;
neighbor(vertex_t arg_target, weight_t arg_weight)
: target(arg_target), weight(arg_weight) { }
};
typedef std::vector<std::vector<neighbor> > adjacency_list_t;
void DijkstraComputePaths(vertex_t source,
const adjacency_list_t &adjacency_list,
std::vector<weight_t> &min_distance,
std::vector<vertex_t> &previous)
{
int n = adjacency_list.size();
min_distance.clear();
min_distance.resize(n, max_weight);
min_distance[source] = 0;
previous.clear();
previous.resize(n, -1);
std::set<std::pair<weight_t, vertex_t> > vertex_queue;
vertex_queue.insert(std::make_pair(min_distance[source], source));
while (!vertex_queue.empty())
{
weight_t dist = vertex_queue.begin()->first;
vertex_t u = vertex_queue.begin()->second;
vertex_queue.erase(vertex_queue.begin());
// Visit each edge exiting u
const std::vector<neighbor> &neighbors = adjacency_list[u];
for (std::vector<neighbor>::const_iterator neighbor_iter = neighbors.begin();
neighbor_iter != neighbors.end();
neighbor_iter++)
{
vertex_t v = neighbor_iter->target;
weight_t weight = neighbor_iter->weight;
weight_t distance_through_u = dist + weight;
if (distance_through_u < min_distance[v]) {
vertex_queue.erase(std::make_pair(min_distance[v], v));
min_distance[v] = distance_through_u;
previous[v] = u;
vertex_queue.insert(std::make_pair(min_distance[v], v));
}
}
}
}
std::list<vertex_t> DijkstraGetShortestPathTo(
vertex_t vertex, const std::vector<vertex_t> &previous)
{
std::list<vertex_t> path;
for ( ; vertex != -1; vertex = previous[vertex])
path.push_front(vertex);
return path;
}
int main()
{
// remember to insert edges both ways for an undirected graph
adjacency_list_t adjacency_list(6);
// 0 = a
adjacency_list[0].push_back(neighbor(1, 7));
adjacency_list[0].push_back(neighbor(2, 9));
adjacency_list[0].push_back(neighbor(5, 14));
// 1 = b
adjacency_list[1].push_back(neighbor(0, 7));
adjacency_list[1].push_back(neighbor(2, 10));
adjacency_list[1].push_back(neighbor(3, 15));
// 2 = c
adjacency_list[2].push_back(neighbor(0, 9));
adjacency_list[2].push_back(neighbor(1, 10));
adjacency_list[2].push_back(neighbor(3, 11));
adjacency_list[2].push_back(neighbor(5, 2));
// 3 = d
adjacency_list[3].push_back(neighbor(1, 15));
adjacency_list[3].push_back(neighbor(2, 11));
adjacency_list[3].push_back(neighbor(4, 6));
// 4 = e
adjacency_list[4].push_back(neighbor(3, 6));
adjacency_list[4].push_back(neighbor(5, 9));
// 5 = f
adjacency_list[5].push_back(neighbor(0, 14));
adjacency_list[5].push_back(neighbor(2, 2));
adjacency_list[5].push_back(neighbor(4, 9));
std::vector<weight_t> min_distance;
std::vector<vertex_t> previous;
DijkstraComputePaths(0, adjacency_list, min_distance, previous);
std::cout << "Distance from 0 to 4: " << min_distance[4] << std::endl;
std::list<vertex_t> path = DijkstraGetShortestPathTo(4, previous);
std::cout << "Path : ";
std::copy(path.begin(), path.end(), std::ostream_iterator<vertex_t>(std::cout, " "));
std::cout << std::endl;
return 0;
} |
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
| #Batch_File | Batch File | :: Digital Root Task from Rosetta Code Wiki
:: Batch File Implementation
:: (Base 10)
@echo off
setlocal enabledelayedexpansion
:: THE MAIN THING
for %%x in (9876543214 393900588225 1985989328582 34559) do call :droot %%x
echo(
pause
exit /b
:: /THE MAIN THING
:: THE FUNCTION
:droot
set inp2sum=%1
set persist=1
:cyc1
set sum=0
set scan_digit=0
:cyc2
set digit=!inp2sum:~%scan_digit%,1!
if "%digit%"=="" (goto :sumdone)
set /a sum+=%digit%
set /a scan_digit+=1
goto :cyc2
:sumdone
if %sum% lss 10 (
echo(
echo ^(%1^)
echo Additive Persistence=%persist% Digital Root=%sum%.
goto :EOF
)
set /a persist+=1
set inp2sum=%sum%
goto :cyc1
:: /THE FUNCTION |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function multDigitalRoot(n As UInteger, ByRef mp As Integer, base_ As Integer = 10) As Integer
Dim mdr As Integer
mp = 0
Do
mdr = IIf(n > 0, 1, 0)
While n > 0
mdr *= n Mod base_
n = n \ base_
Wend
mp += 1
n = mdr
Loop until mdr < base_
Return mdr
End Function
Dim As Integer mdr, mp
Dim a(3) As UInteger = {123321, 7739, 893, 899998}
For i As UInteger = 0 To 3
mp = 0
mdr = multDigitalRoot(a(i), mp)
Print a(i); Tab(10); "MDR ="; mdr; Tab(20); "MP ="; mp
Print
Next
Print
Print "MDR 1 2 3 4 5"
Print "=== ==========================="
Print
Dim num(0 To 9, 0 To 5) As UInteger '' all zero by default
Dim As UInteger n = 0, count = 0
Do
mdr = multDigitalRoot(n, mp)
If num(mdr, 0) < 5 Then
num(mdr, 0) += 1
num(mdr, num(mdr, 0)) = n
count += 1
End If
n += 1
Loop Until count = 50
For i As UInteger = 0 To 9
Print i; ":" ;
For j As UInteger = 1 To 5
Print Using "######"; num(i, j);
Next j
Print
Next i
Print
Print "Press any key to quit"
Sleep |
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.
| #Visual_Basic | Visual Basic | Option Explicit
Const Pi As Double = 3.14159265358979
Dim angle As Double
Dim nDepth As Integer
Dim nColor As Long
Private Sub Form_Load()
nColor = vbBlack
nDepth = 12
DragonCurve
End Sub
Sub DragonProc(size As Double, ByVal split As Integer, d As Integer)
If split = 0 Then
xForm.Line -Step(-Cos(angle) * size, Sin(angle) * size), nColor
Else
angle = angle + d * Pi / 4
Call DragonProc(size / Sqr(2), split - 1, 1)
angle = angle - d * Pi / 2
Call DragonProc(size / Sqr(2), split - 1, -1)
angle = angle + d * Pi / 4
End If
End Sub
Sub DragonCurve()
Const xcoefi = 0.74
Const xcoefl = 0.59
xForm.PSet (xForm.Width * xcoefi, xForm.Height / 3), nColor
Call DragonProc(xForm.Width * xcoefl, nDepth, 1)
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?
| #Crystal | Crystal | module Enumerable(T)
def index!(element)
index(element).not_nil!
end
end
residents = [:Baker, :Cooper, :Fletcher, :Miller, :Smith]
predicates = [
->(p : Array(Symbol)){ :Baker != p.last },
->(p : Array(Symbol)){ :Cooper != p.first },
->(p : Array(Symbol)){ :Fletcher != p.first && :Fletcher != p.last },
->(p : Array(Symbol)){ p.index!(:Miller) > p.index!(:Cooper) },
->(p : Array(Symbol)){ (p.index!(:Smith) - p.index!(:Fletcher)).abs != 1 },
->(p : Array(Symbol)){ (p.index!(:Cooper) - p.index!(:Fletcher)).abs != 1}
]
puts residents.permutations.find { |p| predicates.all? &.call p } |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #Cowgol | Cowgol | include "cowgol.coh";
sub dotproduct(a: [int32], b: [int32], len: intptr): (n: int32) is
n := 0;
while len > 0 loop
n := n + [a] * [b];
a := @next a;
b := @next b;
len := len - 1;
end loop;
end sub;
sub printsgn(n: int32) is
if n<0 then
print_char('-');
n := -n;
end if;
print_i32(n as uint32);
end sub;
var A: int32[] := {1, 3, -5};
var B: int32[] := {4, -2, -1};
printsgn(dotproduct(&A[0], &B[0], @sizeof A));
print_nl(); |
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
| #PowerShell | PowerShell |
$list = New-Object -TypeName 'Collections.Generic.LinkedList[PSCustomObject]'
for($i=1; $i -lt 10; $i++)
{
$list.AddLast([PSCustomObject]@{ID=$i; X=100+$i;Y=200+$i}) | Out-Null
}
$list
|
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
| #J | J | gen_dict =: (({. , #)/.~@:,@:(+/&>)@:{@:(# <@:>:@:i.)~ ; ^)&x:
beating_probability =: dyad define
'C0 P0' =. gen_dict/ x
'C1 P1' =. gen_dict/ y
(C0 +/@:,@:(>/&:({."1) * */&:({:"1)) C1) % (P0 * P1)
) |
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
| #Java | Java | import java.util.Random;
public class Dice{
private static int roll(int nDice, int nSides){
int sum = 0;
Random rand = new Random();
for(int i = 0; i < nDice; i++){
sum += rand.nextInt(nSides) + 1;
}
return sum;
}
private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int rolls){
int p1Wins = 0;
for(int i = 0; i < rolls; i++){
int p1Roll = roll(p1Dice, p1Sides);
int p2Roll = roll(p2Dice, p2Sides);
if(p1Roll > p2Roll) p1Wins++;
}
return p1Wins;
}
public static void main(String[] args){
int p1Dice = 9; int p1Sides = 4;
int p2Dice = 6; int p2Sides = 6;
int rolls = 10000;
int p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 10000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 9; p1Sides = 4;
p2Dice = 6; p2Sides = 6;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
System.out.println();
p1Dice = 5; p1Sides = 10;
p2Dice = 6; p2Sides = 7;
rolls = 1000000;
p1Wins = diceGame(p1Dice, p1Sides, p2Dice, p2Sides, rolls);
System.out.println(rolls + " rolls, p1 = " + p1Dice + "d" + p1Sides + ", p2 = " + p2Dice + "d" + p2Sides);
System.out.println("p1 wins " + (100.0 * p1Wins / rolls) + "% of the time");
}
} |
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.
| #C.23 | C# | using System;
using System.Net;
using System.Net.Sockets;
class Program {
static void Main(string[] args) {
try {
TcpListener server = new TcpListener(IPAddress.Any, 12345);
server.Start();
}
catch (SocketException e) {
if (e.SocketErrorCode == SocketError.AddressAlreadyInUse) {
Console.Error.WriteLine("Already running.");
}
}
}
} |
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.
| #C.2B.2B | C++ | #include <afx.h> |
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.
| #Clojure | Clojure | (import (java.net ServerSocket InetAddress))
(def *port* 12345) ; random large port number
(try (new ServerSocket *port* 10 (. InetAddress getLocalHost))
(catch IOException e (System/exit 0))) ; port taken, so app is already running |
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.
| #Common_Lisp | Common Lisp | (in-package :common-lisp-user)
;;
;; FLAG -- if using quicklisp, you can get bordeaux-threads loaded up
;; with: (ql:quickload :bordeaux-threads)
;;
(defvar *philosophers* '(Aristotle Kant Spinoza Marx Russell))
(defclass philosopher ()
((name :initarg :name :reader name-of)
(left-fork :initarg :left-fork :accessor left-fork-of)
(right-fork :initarg :right-fork :accessor right-fork-of)
(meals-left :initarg :meals-left :accessor meals-left-of)))
(defclass fork ()
((lock :initform (bt:make-lock "fork") :reader lock-of)))
(defun random-normal (&optional (mean 0.0) (sd 1.0))
(do* ((x1 #1=(1- (* 2.0d0 (random 1d0))) #1#)
(x2 #2=(1- (* 2.0d0 (random 1d0))) #2#)
(w #3=(+ (* x1 x1) (* x2 x2)) #3#))
((< w 1d0) (+ (* (* x1 (sqrt (/ (* -2d0 (log w)) w))) sd) mean))))
(defun sleep* (time) (sleep (max time (/ (expt 10 7)))))
(defun dining-philosophers (&key (philosopher-names *philosophers*)
(meals 30)
(dining-time'(1 2))
(thinking-time '(1 2))
((stream e) *error-output*))
(let* ((count (length philosopher-names))
(forks (loop repeat count collect (make-instance 'fork)))
(philosophers (loop for i from 0
for name in philosopher-names collect
(make-instance 'philosopher
:left-fork (nth (mod i count) forks)
:right-fork (nth (mod (1+ i) count) forks)
:name name
:meals-left meals)))
(condition (bt:make-condition-variable))
(lock (bt:make-lock "main loop"))
(output-lock (bt:make-lock "output lock")))
(dolist (p philosophers)
(labels ((think ()
(/me "is now thinking")
(sleep* (apply #'random-normal thinking-time))
(/me "is now hungry")
(dine))
(dine ()
(bt:with-lock-held ((lock-of (left-fork-of p)))
(or (bt:acquire-lock (lock-of (right-fork-of p)) nil)
(progn (/me "couldn't get a fork and ~
returns to thinking")
(bt:release-lock (lock-of (left-fork-of p)))
(return-from dine (think))))
(/me "is eating")
(sleep* (apply #'random-normal dining-time))
(bt:release-lock (lock-of (right-fork-of p)))
(/me "is done eating (~A meals left)"
(decf (meals-left-of p))))
(cond ((<= (meals-left-of p) 0)
(/me "leaves the dining room")
(bt:with-lock-held (lock)
(setq philosophers (delete p philosophers))
(bt:condition-notify condition)))
(t (think))))
(/me (control &rest args)
(bt:with-lock-held (output-lock)
(write-sequence (string (name-of p)) e)
(write-char #\Space e)
(apply #'format e (concatenate 'string control "~%")
args))))
(bt:make-thread #'think)))
(loop (bt:with-lock-held (lock)
(when (endp philosophers)
(format e "all philosophers are done dining~%")
(return)))
(bt:with-lock-held (lock)
(bt:condition-wait condition lock)))))
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Befunge | Befunge | 0" :raeY">:#,_&>\" :htnoM">:#,_&>04p" :yaD">:#,_$&>55+,1-:47*v
v"f I".+1%,,,,"Day I":$_:#<0#!4#:p#-4#1g4-#0+#<<_v#!*!-2g40!-<
>"o",,,/:5+*66++:4>g#<:#44#:9#+*#1-#,_$$0 v_v#!< >$ 0 "yaD " v
@,+55.+*+92"j"$_,#!>#:<", in the YOLD"*84 <.>,:^ :"St. Tib's"<
$# #"#"##"#"Chaos$Discord$Confusion$Bureaucracy$The Aftermath$ |
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)
| #Clojure | Clojure |
(declare neighbours
process-neighbour
prepare-costs
get-next-node
unwind-path
all-shortest-paths)
;; Main algorithm
(defn dijkstra
"Given two nodes A and B, and graph, finds shortest path from point A to point B.
Given one node and graph, finds all shortest paths to all other nodes.
Graph example: {1 {2 7 3 9 6 14}
2 {1 7 3 10 4 15}
3 {1 9 2 10 4 11 6 2}
4 {2 15 3 11 5 6}
5 {6 9 4 6}
6 {1 14 3 2 5 9}}
^ ^ ^
| | |
node label | |
neighbour label--- |
edge cost------
From example in Wikipedia: https://en.wikipedia.org/wiki/Dijkstra's_algorithm
Output example: [20 [1 3 6 5]]
^ ^
| |
shortest path cost |
shortest path---"
([a b graph]
(loop [costs (prepare-costs a graph)
unvisited (set (keys graph))]
(let [current-node (get-next-node costs unvisited)
current-cost (first (costs current-node))]
(cond (nil? current-node)
(all-shortest-paths a costs)
(= current-node b)
[current-cost (unwind-path a b costs)]
:else
(recur (reduce (partial process-neighbour
current-node
current-cost)
costs
(filter (comp unvisited first)
(neighbours current-node graph costs)))
(disj unvisited current-node))))))
([a graph] (dijkstra a nil graph)))
;; Implementation details
(defn prepare-costs
"For given start node A ang graph prepare map of costs to start with
(assign maximum value for all nodes and zero for starting one).
Also save info about most advantageous parent.
Example output: {2 [2147483647 7], 6 [2147483647 14]}
^ ^ ^
| | |
node | |
cost----- |
parent---------------"
[start graph]
(assoc (zipmap (keys graph)
(repeat [Integer/MAX_VALUE nil]))
start [0 start]))
(defn neighbours
"Get given node's neighbours along with their own costs and costs of corresponding edges.
Example output is: {1 [7 10] 2 [4 15]}
^ ^ ^
| | |
neighbour node label | |
neighbour cost --- |
edge cost ------"
[node graph costs]
(->> (graph node)
(map (fn [[neighbour edge-cost]]
[neighbour [(first (costs neighbour)) edge-cost]]))
(into {})))
(defn process-neighbour
[parent
parent-cost
costs
[neighbour [old-cost edge-cost]]]
(let [new-cost (+ parent-cost edge-cost)]
(if (< new-cost old-cost)
(assoc costs
neighbour
[new-cost parent])
costs)))
(defn get-next-node [costs unvisited]
(->> costs
(filter (comp unvisited first))
(sort-by (comp first second))
ffirst))
(defn unwind-path
"Restore path from A to B based on costs data"
[a b costs]
(letfn [(f [a b costs]
(when-not (= a b)
(cons b (f a (second (costs b)) costs))))]
(cons a (reverse (f a b costs)))))
(defn all-shortest-paths
"Get shortest paths for all nodes, along with their costs"
[start costs]
(let [paths (->> (keys costs)
(remove #{start})
(map (fn [n] [n (unwind-path start n costs)])))]
(into (hash-map)
(map (fn [[n p]]
[n [(first (costs n)) p]])
paths))))
;; Utils
(require '[clojure.pprint :refer [print-table]])
(defn print-solution [solution]
(print-table
(map (fn [[node [cost path]]]
{'node node 'cost cost 'path path})
solution)))
;; Solutions
;; Task 1. Implement a version of Dijkstra's algorithm that outputs a set of edges depicting the shortest path to each reachable node from an origin.
;; see above
;; Task 2. Run your program with the following directed graph starting at node a.
;; 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
(def rosetta-graph
'{a {b 7 c 9 f 14}
b {c 10 d 15}
c {d 11 f 2}
d {e 6}
e {f 9}
f {}})
(def task-2-solution
(dijkstra 'a rosetta-graph))
(print-solution task-2-solution)
;; Output:
;; | node | cost | path |
;; |------+------+-----------|
;; | b | 7 | (a b) |
;; | c | 9 | (a c) |
;; | d | 20 | (a c d) |
;; | e | 26 | (a c d e) |
;; | f | 11 | (a c f) |
;; Task 3. 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
(print-solution (select-keys task-2-solution '[e f]))
;; Output:
;; | node | cost | path |
;; |------+------+-----------|
;; | e | 26 | (a c d e) |
;; | f | 11 | (a c 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
| #BBC_BASIC | BBC BASIC | *FLOAT64
PRINT "Digital root of 627615 is "; FNdigitalroot(627615, 10, p) ;
PRINT " (additive persistence " ; p ")"
PRINT "Digital root of 39390 is "; FNdigitalroot(39390, 10, p) ;
PRINT " (additive persistence " ; p ")"
PRINT "Digital root of 588225 is "; FNdigitalroot(588225, 10, p) ;
PRINT " (additive persistence " ; p ")"
PRINT "Digital root of 393900588225 is "; FNdigitalroot(393900588225, 10, p) ;
PRINT " (additive persistence " ; p ")"
PRINT "Digital root of 9992 is "; FNdigitalroot(9992, 10, p) ;
PRINT " (additive persistence " ; p ")"
END
DEF FNdigitalroot(n, b, RETURN c)
c = 0
WHILE n >= b
c += 1
n = FNdigitsum(n, b)
ENDWHILE
= n
DEF FNdigitsum(n, b)
LOCAL q, s
WHILE n <> 0
q = INT(n / b)
s += n - q * b
n = q
ENDWHILE
= s |
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
| #Befunge | Befunge | 0" :rebmun retnE">:#,_0 0v
v\1:/+55p00<v\`\0::-"0"<~<
#>:55+%00g+^>9`+#v_+\ 1+\^
>|`9:p000<_v#`1\$< v"gi"<
|> \ 1 + \ >0" :toor lat"^
>$$00g\1+^@,+<v"Di",>#+ 5<
>:#,_$ . 5 5 ^>:#,_\.55+,v
^"Additive Persistence: "< |
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
| #Go | Go | package main
import "fmt"
// Only valid for n > 0 && base >= 2
func mult(n uint64, base int) (mult uint64) {
for mult = 1; mult > 0 && n > 0; n /= uint64(base) {
mult *= n % uint64(base)
}
return
}
// Only valid for n >= 0 && base >= 2
func MultDigitalRoot(n uint64, base int) (mp, mdr int) {
var m uint64
for m = n; m >= uint64(base); mp++ {
m = mult(m, base)
}
return mp, int(m)
}
func main() {
const base = 10
const size = 5
const testFmt = "%20v %3v %3v\n"
fmt.Printf(testFmt, "Number", "MDR", "MP")
for _, n := range [...]uint64{
123321, 7739, 893, 899998,
18446743999999999999,
// From http://mathworld.wolfram.com/MultiplicativePersistence.html
3778888999, 277777788888899,
} {
mp, mdr := MultDigitalRoot(n, base)
fmt.Printf(testFmt, n, mdr, mp)
}
fmt.Println()
var list [base][]uint64
for i := range list {
list[i] = make([]uint64, 0, size)
}
for cnt, n := size*base, uint64(0); cnt > 0; n++ {
_, mdr := MultDigitalRoot(n, base)
if len(list[mdr]) < size {
list[mdr] = append(list[mdr], n)
cnt--
}
}
const tableFmt = "%3v: %v\n"
fmt.Printf(tableFmt, "MDR", "First")
for i, l := range list {
fmt.Printf(tableFmt, i, l)
}
} |
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.
| #Visual_Basic_.NET | Visual Basic .NET | Option Explicit On
Imports System.Math
Public Class DragonCurve
Dim nDepth As Integer = 12
Dim angle As Double
Dim MouseX, MouseY As Integer
Dim CurrentX, CurrentY As Integer
Dim nColor As Color = Color.Black
Private Sub DragonCurve_Click(sender As Object, e As EventArgs) Handles Me.Click
SubDragonCurve()
End Sub
Sub DrawClear()
Me.CreateGraphics.Clear(Color.White)
End Sub
Sub DrawMove(ByVal X As Double, ByVal Y As Double)
CurrentX = X
CurrentY = Y
End Sub
Sub DrawLine(ByVal X As Double, ByVal Y As Double)
Dim MyGraph As Graphics = Me.CreateGraphics
Dim PenColor As Pen = New Pen(nColor)
Dim NextX, NextY As Long
NextX = CurrentX + X
NextY = CurrentY + Y
MyGraph.DrawLine(PenColor, CurrentX, CurrentY, NextX, NextY)
CurrentX = NextX
CurrentY = NextY
End Sub
Sub DragonProc(size As Double, ByVal split As Integer, d As Integer)
If split = 0 Then
DrawLine(-Cos(angle) * size, Sin(angle) * size)
Else
angle = angle + d * PI / 4
DragonProc(size / Sqrt(2), split - 1, 1)
angle = angle - d * PI / 2
DragonProc(size / Sqrt(2), split - 1, -1)
angle = angle + d * PI / 4
End If
End Sub
Sub SubDragonCurve()
Const xcoefi = 0.74, xcoefl = 0.59
DrawClear()
DrawMove(Me.Width * xcoefi, Me.Height / 3)
DragonProc(Me.Width * xcoefl, nDepth, 1)
End Sub
End Class |
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?
| #D | D | import std.stdio, std.math, std.algorithm, std.traits, permutations2;
void main() {
enum Names { Baker, Cooper, Fletcher, Miller, Smith }
immutable(bool function(in Names[]) pure nothrow)[] predicates = [
s => s[Names.Baker] != s.length - 1,
s => s[Names.Cooper] != 0,
s => s[Names.Fletcher] != 0 && s[Names.Fletcher] != s.length-1,
s => s[Names.Miller] > s[Names.Cooper],
s => abs(s[Names.Smith] - s[Names.Fletcher]) != 1,
s => abs(s[Names.Cooper] - s[Names.Fletcher]) != 1];
permutations([EnumMembers!Names])
.filter!(solution => predicates.all!(pred => pred(solution)))
.writeln;
} |
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
| #Crystal | Crystal | class Vector
property x, y, z
def initialize(@x : Int64, @y : Int64, @z : Int64) end
def dot_product(other : Vector)
(self.x * other.x) + (self.y * other.y) + (self.z * other.z)
end
end
puts Vector.new(1, 3, -5).dot_product Vector.new(4, -2, -1) # => 3
class Array
def dot_product(other)
raise "not the same size!" if self.size != other.size
self.zip(other).sum { |(a, b)| a * b }
end
end
p [8, 13, -5].dot_product [4, -7, -11] # => -4 |
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
| #PureBasic | PureBasic | DataSection
;the list of words that will be added to the list
words:
Data.s "One", "Two", "Three", "Four", "Five", "Six", "EndOfData"
EndDataSection
Procedure displayList(List x.s(), title$)
;display all elements from list of strings
Print(title$)
ForEach x()
Print(x() + " ")
Next
PrintN("")
EndProcedure
OpenConsole()
NewList a.s() ;create a new list of strings
;add words to the head of list
Restore words
Repeat
Read.s a$
If a$ <> "EndOfData"
ResetList(a()) ;Move to head of list
AddElement(a())
a() = a$
EndIf
Until a$ = "EndOfData"
displayList(a(),"Insertion at Head: ")
ClearList(a())
;add words to the tail of list
Restore words
LastElement(a()) ;Move to the tail of the list
Repeat
Read.s a$
If a$ <> "EndOfData"
AddElement(a()) ;after insertion the new position is still at the tail
a() = a$
EndIf
Until a$ = "EndOfData"
displayList(a(),"Insertion at Tail: ")
ClearList(a())
;add words to the middle of list
Restore words
ResetList(a()) ;Move to the tail of the list
Repeat
Read.s a$
If a$ <> "EndOfData"
c = CountList(a())
If c > 1
SelectElement(a(),Random(c - 2)) ;insert after a random element but before tail
Else
FirstElement(a())
EndIf
AddElement(a())
a() = a$
EndIf
Until a$ = "EndOfData"
displayList(a(),"Insertion in Middle: ")
Repeat: Until Inkey() <> "" |
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
| #JacaScript | JacaScript |
let Player = function(dice, faces) {
this.dice = dice;
this.faces = faces;
this.roll = function() {
let results = [];
for (let x = 0; x < dice; x++)
results.push(Math.floor(Math.random() * faces +1));
return eval(results.join('+'));
}
}
function contest(player1, player2, rounds) {
let res = [0, 0, 0];
for (let x = 1; x <= rounds; x++) {
let a = player1.roll(),
b = player2.roll();
switch (true) {
case (a > b): res[0]++; break;
case (a < b): res[1]++; break;
case (a == b): res[2]++; break;
}
}
document.write(`
<p>
<b>Player 1</b> (${player1.dice} × d${player1.faces}): ${res[0]} wins<br>
<b>Player 2</b> (${player2.dice} × d${player2.faces}): ${res[1]} wins<br>
<b>Draws:</b> ${res[2]}<br>
Chances for Player 1 to win:
~${Math.round(res[0] / eval(res.join('+')) * 100)} %
</p>
`);
}
let p1, p2;
p1 = new Player(9, 4),
p2 = new Player(6, 6);
contest(p1, p2, 1e6);
p1 = new Player(5, 10);
p2 = new Player(6, 7);
contest(p1, p2, 1e6);
|
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.
| #D | D |
bool is_unique_instance()
{
import std.socket;
auto socket = new Socket(AddressFamily.UNIX, SocketType.STREAM);
auto addr = new UnixAddress("\0/tmp/myapp.uniqueness.sock");
try
{
socket.bind(addr);
return true;
}
catch (SocketOSException e)
{
import core.stdc.errno : EADDRINUSE;
if (e.errorCode == EADDRINUSE)
return false;
else
throw e;
}
}
|
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.
| #Delphi | Delphi | program OneInstance;
{$APPTYPE CONSOLE}
uses SysUtils, Windows;
var
FMutex: THandle;
begin
FMutex := CreateMutex(nil, True, 'OneInstanceMutex');
if FMutex = 0 then
RaiseLastOSError
else
begin
try
if GetLastError = ERROR_ALREADY_EXISTS then
Writeln('Program already running. Closing...')
else
begin
// do stuff ...
Readln;
end;
finally
CloseHandle(FMutex);
end;
end;
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.
| #Erlang | Erlang | 7> erlang:register( aname, erlang:self() ).
true
8> erlang:register( aname, erlang:self() ).
** exception error: bad argument
in function register/2
called as register(aname,<0.42.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.
| #D | D | import std.stdio, std.algorithm, std.string, std.parallelism,
core.sync.mutex;
void eat(in size_t i, in string name, Mutex[] forks) {
writeln(name, " is hungry.");
immutable j = (i + 1) % forks.length;
// Take forks i and j. The lower one first to prevent deadlock.
auto fork1 = forks[min(i, j)];
auto fork2 = forks[max(i, j)];
fork1.lock;
scope(exit) fork1.unlock;
fork2.lock;
scope(exit) fork2.unlock;
writeln(name, " is eating.");
writeln(name, " is full.");
}
void think(in string name) {
writeln(name, " is thinking.");
}
void main() {
const philosophers = "Aristotle Kant Spinoza Marx Russell".split;
Mutex[philosophers.length] forks;
foreach (ref fork; forks)
fork = new Mutex;
defaultPoolThreads = forks.length;
foreach (i, philo; taskPool.parallel(philosophers)) {
foreach (immutable _; 0 .. 100) {
eat(i, philo, forks);
philo.think;
}
}
} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #C | C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\
(x) == 2 ? "Boomtime" :\
(x) == 3 ? "Pungenday" :\
(x) == 4 ? "Prickle-Prickle" :\
"Setting Orange")
#define season( x ) ((x) == 0 ? "Chaos" :\
(x) == 1 ? "Discord" :\
(x) == 2 ? "Confusion" :\
(x) == 3 ? "Bureaucracy" :\
"The Aftermath")
#define date( x ) ((x)%73 == 0 ? 73 : (x)%73)
#define leap_year( x ) ((x) % 400 == 0 || (((x) % 4) == 0 && (x) % 100))
char * ddate( int y, int d ){
int dyear = 1166 + y;
char * result = malloc( 100 * sizeof( char ) );
if( leap_year( y ) ){
if( d == 60 ){
sprintf( result, "St. Tib's Day, YOLD %d", dyear );
return result;
} else if( d >= 60 ){
-- d;
}
}
sprintf( result, "%s, %s %d, YOLD %d",
day_of_week(d%5), season(((d%73)==0?d-1:d)/73 ), date( d ), dyear );
return result;
}
int day_of_year( int y, int m, int d ){
int month_lengths[ 12 ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for( ; m > 1; m -- ){
d += month_lengths[ m - 2 ];
if( m == 3 && leap_year( y ) ){
++ d;
}
}
return d;
}
int main( int argc, char * argv[] ){
time_t now;
struct tm * now_time;
int year, doy;
if( argc == 1 ){
now = time( NULL );
now_time = localtime( &now );
year = now_time->tm_year + 1900; doy = now_time->tm_yday + 1;
} else if( argc == 4 ){
year = atoi( argv[ 1 ] ); doy = day_of_year( atoi( argv[ 1 ] ), atoi( argv[ 2 ] ), atoi( argv[ 3 ] ) );
}
char * result = ddate( year, doy );
puts( result );
free( result );
return 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)
| #Commodore_BASIC | Commodore BASIC | 100 NV=0: REM NUMBER OF VERTICES
110 READ N$:IF N$<>"" THEN NV=NV+1:GOTO 110
120 NE=0: REM NUMBER OF EDGES
130 READ N1:IF N1 >= 0 THEN READ N2,W:NE=NE+1:GOTO 130
140 DIM VN$(NV-1),VD(NV-1,2): REM VERTEX NAMES AND DATA
150 DIM ED(NE-1,2): REM EDGE DATA
160 RESTORE
170 FOR I=0 TO NV-1
180 : READ VN$(I): REM VERTEX NAME
190 : VD(I,0) = -1: REM DISTANCE = INFINITY
200 : VD(I,1) = 0: REM NOT YET VISITED
210 : VD(I,2) = -1: REM NO PREV VERTEX YET
220 NEXT I
230 READ N$: REM SKIP SENTINEL
240 FOR I=0 TO NE-1
250 : READ ED(I,0),ED(I,1),ED(I,2): REM EDGE FROM, TO, WEIGHT
260 NEXT I
270 READ N1: REM SKIP SENTINEL
280 READ O: REM ORIGIN VERTEX
290 :
300 REM BEGIN DIJKSTRA'S
310 VD(O,0) = 0: REM DISTANCE TO ORIGIN IS 0
320 CV = 0: REM CURRENT VERTEX IS ORIGIN
330 FOR I=0 TO NE-1
340 : IF ED(I,0)<>CV THEN 390: REM SKIP EDGES NOT FROM CURRENT
350 : N=ED(I,1): REM NEIGHBOR VERTEX
360 : D=VD(CV,0) + ED(I,2): REM TOTAL DISTANCE TO NEIGHBOR THROUGH THIS PATH
370 : REM IF PATH THRU CV < DISTANCE, UPDATE DISTANCE AND PREV VERTEX
380 : IF (VD(N,0)=-1) OR (D<VD(N,0)) THEN VD(N,0) = D:VD(N,2)=CV
390 NEXT I
400 VD(CV,1)=1: REM CURRENT VERTEX HAS BEEN VISITED
410 MV=-1: REM VERTEX WITH MINIMUM DISTANCE SEEN
420 FOR I=0 TO NV-1
430 : IF VD(I,1) THEN 470: REM SKIP VISITED VERTICES
440 : REM IF THIS IS THE SMALLEST DISTANCE SEEN, REMEMBER IT
450 : MD=-1:IF MV > -1 THEN MD=VD(MV,0)
460 : IF ( VD(I,0)<>-1 ) AND ( ( MD=-1 ) OR ( VD(I,0)<MD ) ) THEN MV=I
470 NEXT I
480 IF MD=-1 THEN 510: REM END IF ALL VERTICES VISITED OR AT INFINITY
490 CV=MV
500 GOTO 330
510 PRINT "SHORTEST PATH TO EACH VERTEX FROM "VN$(O)":";CHR$(13)
520 FOR I=0 TO NV-1
530 : IF I=0 THEN 600
540 : PRINT VN$(I)":"VD(I,0)"(";
550 : IF VD(I,0)=-1 THEN 600
560 : N=I
570 : PRINT VN$(N);
580 : IF N<>O THEN PRINT "←";:N=VD(N,2):GOTO 570
590 : PRINT ")"
600 NEXT I
610 DATA A,B,C,D,E,F,""
620 DATA 0,1,7
630 DATA 0,2,9
640 DATA 0,5,14
650 DATA 1,2,10
660 DATA 1,3,15
670 DATA 2,3,11
680 DATA 2,5,2
690 DATA 3,4,6
700 DATA 4,5,9
710 DATA -1
720 DATA 0 |
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
| #BQN | BQN | DSum ← +´10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
Root ← 0⊸{(×○⌊÷⟜10)◶⟨𝕨‿𝕩,(1+𝕨)⊸𝕊 Dsum⟩𝕩}
P ← •Show ⊢∾Root
P 627615
P 39390
P 588225
P 393900588225 |
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
| #Bracmat | Bracmat | ( root
= sum persistence n d
. !arg:(~>9.?)
| !arg:(?n.?persistence)
& 0:?sum
& ( @( !n
: ?
(#%@?d&!d+!sum:?sum&~)
?
)
| root$(!sum.!persistence+1)
)
)
& ( 627615 39390 588225 393900588225 10 199
: ?
( #%@?N
& root$(!N.0):(?Sum.?Persistence)
& out
$ ( !N
"has additive persistence"
!Persistence
"and digital root of"
!Sum
)
& ~
)
?
| done
); |
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
| #Haskell | Haskell | import Control.Arrow
import Data.Array
import Data.LazyArray
import Data.List (unfoldr)
import Data.Tuple
import Text.Printf
-- The multiplicative persistence (MP) and multiplicative digital root (MDR) of
-- the argument.
mpmdr :: Integer -> (Int, Integer)
mpmdr = (length *** head) . span (> 9) . iterate (product . digits)
-- Pairs (mdr, ns) where mdr is a multiplicative digital root and ns are the
-- first k numbers having that root.
mdrNums :: Int -> [(Integer, [Integer])]
mdrNums k = assocs $ lArrayMap (take k) (0,9) [(snd $ mpmdr n, n) | n <- [0..]]
digits :: Integral t => t -> [t]
digits 0 = [0]
digits n = unfoldr step n
where step 0 = Nothing
step k = Just (swap $ quotRem k 10)
printMpMdrs :: [Integer] -> IO ()
printMpMdrs ns = do
putStrLn "Number MP MDR"
putStrLn "====== == ==="
sequence_ [printf "%6d %2d %2d\n" n p r | n <- ns, let (p,r) = mpmdr n]
printMdrNums:: Int -> IO ()
printMdrNums k = do
putStrLn "MDR Numbers"
putStrLn "=== ======="
let showNums = unwords . map show
sequence_ [printf "%2d %s\n" mdr $ showNums ns | (mdr,ns) <- mdrNums k]
main :: IO ()
main = do
printMpMdrs [123321, 7739, 893, 899998]
putStrLn ""
printMdrNums 5 |
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.
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
class Game {
static init() {
Window.title = "Dragon curve"
Window.resize(800, 600)
Canvas.resize(800, 600)
var iter = 14
var turns = getSequence(iter)
var startingAngle = -iter * Num.pi / 4
var side = 400 / 2.pow(iter/2)
dragon(turns, startingAngle, side)
}
static getSequence(iterations) {
var turnSequence = []
for (i in 0...iterations) {
var copy = []
copy.addAll(turnSequence)
if (copy.count > 1) copy = copy[-1..0]
turnSequence.add(1)
copy.each { |i| turnSequence.add(-i) }
}
return turnSequence
}
static dragon(turns, startingAngle, side) {
var col = Color.blue
var angle = startingAngle
var x1 = 230
var y1 = 350
var x2 = x1 + (angle.cos * side).truncate
var y2 = y1 + (angle.sin * side).truncate
Canvas.line(x1, y1, x2, y2, col)
x1 = x2
y1 = y2
for (turn in turns) {
angle = angle + turn*Num.pi/2
x2 = x1 + (angle.cos * side).truncate
y2 = y1 + (angle.sin * side).truncate
Canvas.line(x1, y1, x2, y2, col)
x1 = x2
y1 = y2
}
}
static update() {}
static draw(alpha) {}
} |
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?
| #EchoLisp | EchoLisp |
(require 'hash)
(require' amb)
;;
;; Solver
;;
(define (dwelling-puzzle context names floors H)
;; each amb calls gives a floor to a name
(for ((name names))
(hash-set H name (amb context floors)))
;; They live on different floors.
(amb-require (distinct? (amb-choices context)))
(constraints floors H) ;; may fail and backtrack
;; result returned to amb-run
(for/list ((name names))
(cons name (hash-ref H name)))
;; (amb-fail) is possible here to see all solutions
)
(define (task names)
(amb-run dwelling-puzzle
(amb-make-context)
names
(iota (length names)) ;; list of floors : 0,1, ....
(make-hash)) ;; hash table : "name" -> floor
)
|
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 | D | void main() {
import std.stdio, std.numeric;
[1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln;
} |
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
| #Python | Python |
from collections import deque
some_list = deque(["a", "b", "c"])
print(some_list)
some_list.appendleft("Z")
print(some_list)
for value in reversed(some_list):
print(value)
|
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
| #jq | jq | # To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
# Input: an array (aka: counts)
def throwDie($nSides; $nDice; $s):
if $nDice == 0
then .[$s] += 1
else reduce range(1; $nSides + 1) as $i (.;
throwDie($nSides; $nDice-1; $s + $i) )
end ;
def beatingProbability(nSides1; nDice1; nSides2; nDice2):
def a: [range(0; .) | 0];
((nSides1 + 1) * nDice1) as $len1
| ($len1 | a | throwDie(nSides1; nDice1; 0)) as $c1
| ((nSides2 + 1) * nDice2) as $len2
| ($len2 | a | throwDie(nSides2; nDice2; 0)) as $c2
|((nSides1|power(nDice1)) * (nSides2|power(nDice2))) as $p12
| reduce range(0; $len1) as $i (0;
reduce range(0; [$i, $len2] | min) as $j (.;
. + ($c1[$i] * $c2[$j] / $p12) ) ) ;
beatingProbability(4; 9; 6; 6),
beatingProbability(10; 5; 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
| #Julia | Julia | play(ndices::Integer, nfaces::Integer) = (nfaces, ndices) ∋ 0 ? 0 : sum(rand(1:nfaces) for i in 1:ndices)
simulate(d1::Integer, f1::Integer, d2::Integer, f2::Integer; nrep::Integer=1_000_000) =
mean(play(d1, f1) > play(d2, f2) for _ in 1:nrep)
println("\nPlayer 1: 9 dices, 4 faces\nPlayer 2: 6 dices, 6 faces\nP(Player1 wins) = ", simulate(9, 4, 6, 6))
println("\nPlayer 1: 5 dices, 10 faces\nPlayer 2: 6 dices, 7 faces\nP(Player1 wins) = ", simulate(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.
| #FreeBASIC | FreeBASIC | Shell("tasklist > temp.txt")
Dim linea As String
Open "temp.txt" For Input As #1
Do While Not Eof(1)
Line Input #1, linea
If Instr(linea, "fbc.exe") = 0 Then Print "Task is Running" : Exit Do
Loop
Close #1
Shell("del temp.txt")
Sleep |
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.
| #Go | Go | package main
import (
"fmt"
"net"
"time"
)
const lNet = "tcp"
const lAddr = ":12345"
func main() {
if _, err := net.Listen(lNet, lAddr); err != nil {
fmt.Println("an instance was already running")
return
}
fmt.Println("single instance started")
time.Sleep(10 * time.Second)
} |
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.
| #Haskell | Haskell | import Control.Concurrent
import System.Directory (doesFileExist, getAppUserDataDirectory,
removeFile)
import System.IO (withFile, Handle, IOMode(WriteMode), hPutStr)
oneInstance :: IO ()
oneInstance = do
-- check if file "$HOME/.myapp.lock" exists
user <- getAppUserDataDirectory "myapp.lock"
locked <- doesFileExist user
if locked
then print "There is already one instance of this program running."
else do
t <- myThreadId
-- this is the entry point to the main program:
-- withFile creates a file, then calls a function,
-- then closes the file
withFile user WriteMode (do_program t)
-- remove the lock when we're done
removeFile user
do_program :: ThreadId -> Handle -> IO ()
do_program t h = do
let s = "Locked by thread: " ++ show t
-- print what thread has acquired the lock
putStrLn s
-- write the same message to the file, to show that the
-- thread "owns" the file
hPutStr h s
-- wait for one second
threadDelay 1000000
main :: IO ()
main = do
-- launch the first thread, which will create the lock file
forkIO oneInstance
-- wait for half a second
threadDelay 500000
-- launch the second thread, which will find the lock file and
-- thus will exit immediately
forkIO oneInstance
return () |
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.
| #Delphi | Delphi |
program dining_philosophers;
uses
Classes,
SysUtils,
SyncObjs;
const
PHIL_COUNT = 5;
LIFESPAN = 7;
DELAY_RANGE = 950;
DELAY_LOW = 50;
PHIL_NAMES: array[1..PHIL_COUNT] of string = ('Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell');
type
TFork = TCriticalSection;
// TPhilosopher = class;
TPhilosopher = class(TThread)
private
FName: string;
FFirstFork, FSecondFork: TFork;
protected
procedure Execute; override;
public
constructor Create(const aName: string; aForkIdx1, aForkIdx2: Integer);
end;
var
Forks: array[1..PHIL_COUNT] of TFork;
Philosophers: array[1..PHIL_COUNT] of TPhilosopher;
procedure TPhilosopher.Execute;
var
LfSpan: Integer;
begin
LfSpan := LIFESPAN;
while LfSpan > 0 do
begin
Dec(LfSpan);
WriteLn(FName, ' sits down at the table');
FFirstFork.Acquire;
FSecondFork.Acquire;
WriteLn(FName, ' eating');
Sleep(Random(DELAY_RANGE) + DELAY_LOW);
FSecondFork.Release;
FFirstFork.Release;
WriteLn(FName, ' is full and leaves the table');
if LfSpan = 0 then
continue;
WriteLn(FName, ' thinking');
Sleep(Random(DELAY_RANGE) + DELAY_LOW);
WriteLn(FName, ' is hungry');
end;
end;
constructor TPhilosopher.Create(const aName: string; aForkIdx1, aForkIdx2: Integer);
begin
inherited Create(True);
FName := aName;
if aForkIdx1 < aForkIdx2 then
begin
FFirstFork := Forks[aForkIdx1];
FSecondFork := Forks[aForkIdx2];
end
else
begin
FFirstFork := Forks[aForkIdx2];
FSecondFork := Forks[aForkIdx1];
end;
end;
procedure DinnerBegin;
var
I: Integer;
Phil: TPhilosopher;
begin
for I := 1 to PHIL_COUNT do
Forks[I] := TFork.Create;
for I := 1 to PHIL_COUNT do
Philosophers[I] := TPhilosopher.Create(PHIL_NAMES[I], I, Succ(I mod PHIL_COUNT));
for Phil in Philosophers do
Phil.Start;
end;
procedure WaitForDinnerOver;
var
Phil: TPhilosopher;
Fork: TFork;
begin
for Phil in Philosophers do
begin
Phil.WaitFor;
Phil.Free;
end;
for Fork in Forks do
Fork.Free;
end;
begin
Randomize;
DinnerBegin;
WaitForDinnerOver;
readln;
end. |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #C.23 | C# | using System;
public static class DiscordianDate
{
static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" };
static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" };
static readonly string[] apostles = { "Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" };
static readonly string[] holidays = { "Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux" };
public static string Discordian(this DateTime date) {
string yold = $" in the YOLD {date.Year + 1166}.";
int dayOfYear = date.DayOfYear;
if (DateTime.IsLeapYear(date.Year)) {
if (dayOfYear == 60) return "St. Tib's day" + yold;
else if (dayOfYear > 60) dayOfYear--;
}
dayOfYear--;
int seasonDay = dayOfYear % 73 + 1;
int seasonNr = dayOfYear / 73;
int weekdayNr = dayOfYear % 5;
string holyday = "";
if (seasonDay == 5) holyday = $" Celebrate {apostles[seasonNr]}!";
else if (seasonDay == 50) holyday = $" Celebrate {holidays[seasonNr]}!";
return $"{weekdays[weekdayNr]}, day {seasonDay} of {seasons[seasonNr]}{yold}{holyday}";
}
public static void Main() {
foreach (var (day, month, year) in new [] {
(1, 1, 2010),
(5, 1, 2010),
(19, 2, 2011),
(28, 2, 2012),
(29, 2, 2012),
(1, 3, 2012),
(19, 3, 2013),
(3, 5, 2014),
(31, 5, 2015),
(22, 6, 2016),
(15, 7, 2016),
(12, 8, 2017),
(19, 9, 2018),
(26, 9, 2018),
(24, 10, 2019),
(8, 12, 2020),
(31, 12, 2020)
})
{
Console.WriteLine($"{day:00}-{month:00}-{year:00} = {new DateTime(year, month, day).Discordian()}");
}
}
} |
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)
| #Common_Lisp | Common Lisp |
(defparameter *w* '((a (a b . 7) (a c . 9) (a f . 14))
(b (b c . 10) (b d . 15))
(c (c d . 11) (c f . 2))
(d (d e . 6))
(e (e f . 9))))
(defvar *r* nil)
(defun dijkstra-short-path (i g)
(setf *r* nil) (paths i g 0 `(,i))
(car (sort *r* #'< :key #'cadr)))
(defun paths (c g z v)
(if (eql c g) (push `(,(reverse v) ,z) *r*)
(loop for a in (nodes c) for b = (cadr a) do
(unless (member b v)
(paths b g (+ (cddr a) z) (cons b v))))))
(defun nodes (c)
(sort (cdr (assoc c *w*)) #'< :key #'cddr))
|
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 | C | #include <stdio.h>
int droot(long long int x, int base, int *pers)
{
int d = 0;
if (pers)
for (*pers = 0; x >= base; x = d, (*pers)++)
for (d = 0; x; d += x % base, x /= base);
else if (x && !(d = x % (base - 1)))
d = base - 1;
return d;
}
int main(void)
{
int i, d, pers;
long long x[] = {627615, 39390, 588225, 393900588225LL};
for (i = 0; i < 4; i++) {
d = droot(x[i], 10, &pers);
printf("%lld: pers %d, root %d\n", x[i], pers, d);
}
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
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
write(right("n",8)," ",right("MP",8),right("MDR",5))
every r := mdr(n := 123321|7739|893|899998) do
write(right(n,8),":",right(r[1],8),right(r[2],5))
write()
write(right("MDR",5)," ","[n0..n4]")
every m := 0 to 9 do {
writes(right(m,5),": [")
every writes(right((m = mdr(n := seq(m))[2],.n)\5,6))
write("]")
}
end
procedure mdr(m)
i := 0
while (.m > 10, m := multd(m), i+:=1)
return [i,m]
end
procedure multd(m)
c := 1
while m > 0 do c *:= 1(m%10, m/:=10)
return c
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.
| #X86_Assembly | X86 Assembly | .model tiny
.code
.486
org 100h ;assume ax=0, bx=0, sp=-2
start: mov al, 13h ;(ah=0) set 320x200 video graphics mode
int 10h
push 0A000h
pop es
mov si, 8000h ;color
mov cx, 75*256+100 ;coordinates of initial horizontal line segment
mov dx, 75*256+164 ;use power of 2 for length
call dragon
mov ah, 0 ;wait for keystroke
int 16h
mov ax, 0003h ;restore normal text mode
int 10h
ret
dragon: cmp sp, -100 ;at maximum recursion depth?
jne drag30 ;skip if not
mov bl, dh ;draw at max depth to get solid image
imul di, bx, 320 ;(bh=0) plot point at X=dl, Y=dh
mov bl, dl
add di, bx
mov ax, si ;color
shr ax, 13
or al, 8 ;use bright colors 8..F
stosb ;es:[di++]:= al
inc si
ret
drag30:
push cx ;preserve points P and Q
push dx
xchg ax, dx ;DX:= Q(0)-P(0);
sub al, cl
sub ah, ch ;DY:= Q(1)-P(1);
mov dx, ax ;new point
sub dl, ah ;R(0):= P(0) + (DX-DY)/2
jns drag40
inc dl
drag40: sar dl, 1 ;dl:= (al-ah)/2 + cl
add dl, cl
add dh, al ;R(1):= P(1) + (DX+DY)/2;
jns drag45
inc dh
drag45: sar dh, 1 ;dh:= (al+ah)/2 + ch
add dh, ch
call dragon ;Dragon(P, R);
pop cx ;get Q
push cx
call dragon ;Dragon(Q, R);
pop dx ;restore points
pop cx
ret
end start |
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?
| #Elixir | Elixir | defmodule Dinesman do
def problem do
names = ~w( Baker Cooper Fletcher Miller Smith )a
predicates = [fn(c)-> :Baker != List.last(c) end,
fn(c)-> :Cooper != List.first(c) end,
fn(c)-> :Fletcher != List.first(c) && :Fletcher != List.last(c) end,
fn(c)-> floor(c, :Miller) > floor(c, :Cooper) end,
fn(c)-> abs(floor(c, :Smith) - floor(c, :Fletcher)) != 1 end,
fn(c)-> abs(floor(c, :Cooper) - floor(c, :Fletcher)) != 1 end]
permutation(names)
|> Enum.filter(fn candidate ->
Enum.all?(predicates, fn predicate -> predicate.(candidate) end)
end)
|> Enum.each(fn name_list ->
Enum.with_index(name_list)
|> Enum.each(fn {name,i} -> IO.puts "#{name} lives on #{i+1}" end)
end)
end
defp floor(c, name), do: Enum.find_index(c, fn x -> x == name end)
defp permutation([]), do: [[]]
defp permutation(list), do: (for x <- list, y <- permutation(list -- [x]), do: [x|y])
end
Dinesman.problem |
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
| #Dart | Dart | num dot(List<num> A, List<num> B){
if (A.length != B.length){
throw new Exception('Vectors must be of equal size');
}
num result = 0;
for (int i = 0; i < A.length; i++){
result += A[i] * B[i];
}
return result;
}
void main(){
var l = [1,3,-5];
var k = [4,-2,-1];
print(dot(l,k));
} |
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
| #Delphi | Delphi | program Project1;
{$APPTYPE CONSOLE}
type
doublearray = array of Double;
function DotProduct(const A, B : doublearray): Double;
var
I: integer;
begin
assert (Length(A) = Length(B), 'Input arrays must be the same length');
Result := 0;
for I := 0 to Length(A) - 1 do
Result := Result + (A[I] * B[I]);
end;
var
x,y: doublearray;
begin
SetLength(x, 3);
SetLength(y, 3);
x[0] := 1; x[1] := 3; x[2] := -5;
y[0] := 4; y[1] :=-2; y[2] := -1;
WriteLn(DotProduct(x,y));
ReadLn;
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
| #Racket | Racket |
#lang racket
(define-struct dlist (head tail) #:mutable #:transparent)
(define-struct dlink (content prev next) #:mutable #:transparent)
(define (insert-between dlist before after data)
; Insert a fresh link containing DATA after existing link
; BEFORE if not nil and before existing link AFTER if not nil
(define new-link (make-dlink data before after))
(if before
(set-dlink-next! before new-link)
(set-dlist-head! dlist new-link))
(if after
(set-dlink-prev! after new-link)
(set-dlist-tail! dlist new-link))
new-link)
(define (insert-before dlist dlink data)
; Insert a fresh link containing DATA before existing link DLINK
(insert-between dlist (dlink-prev dlink) dlink data))
(define (insert-after dlist dlink data)
; Insert a fresh link containing DATA after existing link DLINK
(insert-between dlist dlink (dlink-next dlink) data))
(define (insert-head dlist data)
; Insert a fresh link containing DATA at the head of DLIST
(insert-between dlist #f (dlist-head dlist) data))
(define (insert-tail dlist data)
; Insert a fresh link containing DATA at the tail of DLIST
(insert-between dlist (dlist-tail dlist) #f data))
(define (remove-link dlist dlink)
; Remove link DLINK from DLIST and return its content
(let ((before (dlink-prev dlink))
(after (dlink-next dlink)))
(if before
(set-dlink-next! before after)
(set-dlist-head! dlist after))
(if after
(set-dlink-prev! after before)
(set-dlist-tail! dlist before))))
(define (dlist-elements dlist)
; Returns the elements of DLIST as a list
(define (extract-values dlink acc)
(if dlink
(extract-values (dlink-next dlink) (cons (dlink-content dlink) acc))
acc))
(reverse (extract-values (dlist-head dlist) '())))
(let ((dlist (make-dlist #f #f)))
(insert-head dlist 1)
(insert-tail dlist 4)
(insert-after dlist (dlist-head dlist) 2)
(let* ((next-to-last (insert-before dlist (dlist-tail dlist) 3))
(bad-link (insert-before dlist next-to-last 42)))
(remove-link dlist bad-link))
(dlist-elements dlist))
|
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
| #Kotlin | Kotlin | // version 1.1.2
fun throwDie(nSides: Int, nDice: Int, s: Int, counts: IntArray) {
if (nDice == 0) {
counts[s]++
return
}
for (i in 1..nSides) throwDie(nSides, nDice - 1, s + i, counts)
}
fun beatingProbability(nSides1: Int, nDice1: Int, nSides2: Int, nDice2: Int): Double {
val len1 = (nSides1 + 1) * nDice1
val c1 = IntArray(len1) // all elements zero by default
throwDie(nSides1, nDice1, 0, c1)
val len2 = (nSides2 + 1) * nDice2
val c2 = IntArray(len2)
throwDie(nSides2, nDice2, 0, c2)
val p12 = Math.pow(nSides1.toDouble(), nDice1.toDouble()) *
Math.pow(nSides2.toDouble(), nDice2.toDouble())
var tot = 0.0
for (i in 0 until len1) {
for (j in 0 until minOf(i, len2)) {
tot += c1[i] * c2[j] / p12
}
}
return tot
}
fun main(args: Array<String>) {
println(beatingProbability(4, 9, 6, 6))
println(beatingProbability(10, 5, 7, 6))
} |
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.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
if not open(":"||54321,"na") then stop("Already running")
repeat {} # busy loop
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.
| #Java | Java | import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
public class SingletonApp
{
private static final int PORT = 65000; // random large port number
private static ServerSocket s;
// static initializer
static {
try {
s = new ServerSocket(PORT, 10, InetAddress.getLocalHost());
} catch (UnknownHostException e) {
// shouldn't happen for localhost
} catch (IOException e) {
// port taken, so app is already running
System.out.print("Application is already running,");
System.out.println(" so terminating this instance.");
System.exit(0);
}
}
public static void main(String[] args) {
System.out.print("OK, only this instance is running");
System.out.println(" but will terminate in 10 seconds.");
try {
Thread.sleep(10000);
if (s != null && !s.isClosed()) s.close();
} catch (Exception e) {
System.err.println(e);
}
}
} |
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.
| #E | E |
(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.
| #C.2B.2B | C++ |
#include <iostream>
#include <algorithm>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
class myTuple
{
public:
void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; }
bool operator == ( pair<int, int> p ) { return p.first == t.first.first && p.second == t.first.second; }
string second() { return t.second; }
private:
pair<pair<int, int>, string> t;
};
class discordian
{
public:
discordian() {
myTuple t;
t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t );
t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t );
t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t );
t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t );
t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t );
t.set( 8, 12, "Afflux" ); holyday.push_back( t );
seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" );
seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" );
wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" );
wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" );
}
void convert( int d, int m, int y ) {
if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) {
cout << "\nThis is not a date!";
return;
}
vector<myTuple>::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) );
int dd = d, day, wday, sea, yr = y + 1166;
for( int x = 1; x < m; x++ )
dd += getMaxDay( x, 1 );
day = dd % 73; if( !day ) day = 73;
wday = dd % 5;
sea = ( dd - 1 ) / 73;
if( d == 29 && m == 2 && isLeap( y ) ) {
cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr;
return;
}
cout << wdays[wday] << " " << seasons[sea] << " " << day;
if( day > 10 && day < 14 ) cout << "th";
else switch( day % 10) {
case 1: cout << "st"; break;
case 2: cout << "nd"; break;
case 3: cout << "rd"; break;
default: cout << "th";
}
cout << ", Year of Our Lady of Discord " << yr;
if( f != holyday.end() ) cout << " - " << ( *f ).second();
}
private:
int getMaxDay( int m, int y ) {
int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m];
}
bool isLeap( int y ) {
bool l = false;
if( !( y % 4 ) ) {
if( y % 100 ) l = true;
else if( !( y % 400 ) ) l = true;
}
return l;
}
vector<myTuple> holyday; vector<string> seasons, wdays;
};
int main( int argc, char* argv[] ) {
string date; discordian disc;
while( true ) {
cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break;
if( date.length() == 10 ) {
istringstream iss( date );
vector<string> vc;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( vc ) );
disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) );
cout << "\n\n\n";
} else cout << "\nIs this a date?!\n\n";
}
return 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)
| #D | D | import std.stdio, std.typecons, std.algorithm, std.container;
alias Vertex = string;
alias Weight = int;
struct Neighbor {
Vertex target;
Weight weight;
}
alias AdjacencyMap = Neighbor[][Vertex];
pure dijkstraComputePaths(Vertex source, Vertex target, AdjacencyMap adjacencyMap){
Weight[Vertex] minDistance;
Vertex[Vertex] previous;
foreach(v, neighs; adjacencyMap){
minDistance[v] = Weight.max;
foreach(n; neighs) minDistance[n.target] = Weight.max;
}
minDistance[source] = 0;
auto vertexQueue = redBlackTree(tuple(minDistance[source], source));
foreach(_, u; vertexQueue){
if (u == target)
break;
// Visit each edge exiting u.
foreach(n; adjacencyMap.get(u, null)){
const v = n.target;
const distanceThroughU = minDistance[u] + n.weight;
if(distanceThroughU < minDistance[v]){
vertexQueue.removeKey(tuple(minDistance[v], v));
minDistance[v] = distanceThroughU;
previous[v] = u;
vertexQueue.insert(tuple(minDistance[v], v));
}
}
}
return tuple(minDistance, previous);
}
pure dijkstraGetShortestPathTo(Vertex v, Vertex[Vertex] previous){
Vertex[] path = [v];
while (v in previous) {
v = previous[v];
if (v == path[$ - 1])
break;
path ~= v;
}
path.reverse();
return path;
}
void main() {
immutable arcs = [tuple("a", "b", 7),
tuple("a", "c", 9),
tuple("a", "f", 14),
tuple("b", "c", 10),
tuple("b", "d", 15),
tuple("c", "d", 11),
tuple("c", "f", 2),
tuple("d", "e", 6),
tuple("e", "f", 9)];
AdjacencyMap adj;
foreach (immutable arc; arcs) {
adj[arc[0]] ~= Neighbor(arc[1], arc[2]);
// Add this if you want an undirected graph:
//adj[arc[1]] ~= Neighbor(arc[0], arc[2]);
}
const minDist_prev = dijkstraComputePaths("a", "e", adj);
const minDistance = minDist_prev[0];
const previous = minDist_prev[1];
writeln(`Distance from "a" to "e": `, minDistance["e"]);
writeln("Path: ", dijkstraGetShortestPathTo("e", previous));
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.