task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Clojure | Clojure |
(defn squeeze [s c]
(let [spans (partition-by #(= c %) s)
span-out (fn [span]
(if (= c (first span))
(str c)
(apply str span)))]
(apply str (map span-out spans))))
(defn test-squeeze [s c]
(let [out (squeeze s c)]
(println (format "Inp... |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
sub squeeze(ch: uint8, str: [uint8], buf: [uint8]): (r: [uint8]) is
r := buf;
var prev: uint8 := 0;
while [str] != 0 loop
if prev != ch or [str] != ch then
prev := [str];
[buf] := prev;
buf := @next buf;
end i... |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Arturo | Arturo | descending: @[
loop 1..9 'a [
loop 1..dec a 'b [
loop 1..dec b 'c [
loop 1..dec c 'd [
loop 1..dec d 'e [
loop 1..dec e 'f [
loop 1..dec f 'g [
loop 1..dec g 'h [
... |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #AWK | AWK |
# syntax: GAWK -f DESCENDING_PRIMES.AWK
BEGIN {
start = 1
stop = 99999999
for (i=start; i<=stop; i++) {
leng = length(i)
flag = 1
for (j=1; j<leng; j++) {
if (substr(i,j,1) <= substr(i,j+1,1)) {
flag = 0
break
}
}
if (flag) {
if (is... |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #AutoHotkey | AutoHotkey | TrianglesIntersect(T1, T2){ ; T1 := [[x1,y1],[x2,y2],[x3,y3]] , T2 :=[[x4,y4],[x5,y5],[x6,y6]]
counter := 0
for i, Pt in T1
counter += PointInTriangle(Pt, T2) ; check if any coordinate of triangle 1 is inside triangle 2
for i, Pt in T2
counter += PointInTriangle(Pt, T1) ; check if any coordinate of triangle 2 ... |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #C.2B.2B | C++ | #include <iostream>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << ... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #ALGOL_68 | ALGOL 68 | PROC raise exception= ([]STRING args)VOID: (
put(stand error, ("Exception: ",args, newline));
stop
);
PROC raise zero division error := VOID:
raise exception("integer division or modulo by zero");
PROC int div = (INT a,b)REAL: a/b;
PROC int over = (INT a,b)INT: a%b;
PROC int mod = (INT a,b)INT: a%*b;
BE... |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #ALGOL_W | ALGOL W | begin
% determnines whether the string contains an integer, real or imaginary %
% number. Returns true if it does, false otherwise %
logical procedure isNumeric( string(32) value text ) ;
begin
logical ok;
% the "number" cannot be blank ... |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Apex | Apex |
String numericString = '123456';
String partlyNumericString = '123DMS';
String decimalString = '123.456';
System.debug(numericString.isNumeric()); // this will be true
System.debug(partlyNumericString.isNumeric()); // this will be false
System.debug(decimalString.isNumeric()); // this will be false
System.debug(dec... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Arturo | Arturo | strings: [
"", ".", "abcABC", "XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"hétérogénéité",
"🎆🎃🎇🎈", "😍😀🙌💃😍🙌", "🐠🐟🐡🦈🐬🐳🐋🐡"
]
loop strings 'str [
chars: split str
prints ["\"" ++ str ++ "\"" ~"(size |size str|):"]
if? ch... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #AutoHotkey | AutoHotkey | unique_characters(str){
arr := [], res := ""
for i, v in StrSplit(str)
arr[v] := arr[v] ? arr[v] "," i : i
for i, v in Arr
if InStr(v, ",")
res .= v "|" i " @ " v "`tHex = " format("{1:X}", Asc(i)) "`n"
Sort, res, N
res := RegExReplace(res, "`am)^[\d,]+\|")
res := StrSplit(res, "`n").1
return """" str """... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #C.23 | C# | using System;
using static System.Linq.Enumerable;
public class Program
{
static void Main()
{
string[] input = {
"",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"\"If I were two-faced, would I ... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #C.2B.2B | C++ | #include <string>
#include <iostream>
#include <algorithm>
template<typename char_type>
std::basic_string<char_type> collapse(std::basic_string<char_type> str) {
auto i = std::unique(str.begin(), str.end());
str.erase(i, str.end());
return str;
}
void test(const std::string& str) {
std::cout << "ori... |
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 (i... | #Ruby | Ruby | def roll_dice(n_dice, n_faces)
return [[0,1]] if n_dice.zero?
one = [1] * n_faces
zero = [0] * (n_faces-1)
(1...n_dice).inject(one){|ary,_|
(zero + ary + zero).each_cons(n_faces).map{|a| a.inject(:+)}
}.map.with_index(n_dice){|n,sum| [sum,n]} # sum: total of the faces
end
def game(dice1, faces1, dice2... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #C.23 | C# | using System;
namespace AllSame {
class Program {
static void Analyze(string s) {
Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length);
if (s.Length > 1) {
var b = s[0];
for (int i = 1; i < s.Length; i++) {
... |
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 rou... | #J | J | ". noun define -. CRLF NB. Fixed tacit simulation code...
simulate=.
''"_@:((<@:(1 -~ 1&({::)) 1} ])@:(([ 0 0&$@(1!:2&2)@:(((6j3 ": 9&({::)) , ':
'"_) , ' starts waiting and thinking about hunger.' ,~ 8&({::) {:: 0&({::)))@
:(<@:(6&({::) , 8&({::)) 6} ])@:((<@:((0 (0 {:: ])`(<@:(1 {:: ]))`(2 {:: ])}
])@:(3 8 2&... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
Demo(2010,1,1)
Demo(2010,7,22)
Demo(2012,2,28)
Demo(2012,2,29)
Demo(2012,3,1)
Demo(2010,1,5)
Demo(2011,5,3)
Demo(2012,2,28)
Demo(2012,2,29)
Demo(2012,3,1)
Demo(2010,7,22)
Demo(2012,12,22)
end
procedure Demo(y,m,d) #: demo display
printf("%i-%... |
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 pro... | #jq | jq | # (*) If using gojq, uncomment the following line:
# def keys_unsorted: keys;
# remove the first occurrence of $x from the input array
def rm($x):
index($x) as $ix
| if $ix then .[:$ix] + .[$ix+1:] else . end;
# Input: a Graph
# Output: a (possibly empty) stream of the neighbors of $node
# that are also in the... |
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
{\displ... | #Elena | Elena | import extensions;
import system'routines;
import system'collections;
extension op
{
get DigitalRoot()
{
int additivepersistence := 0;
long num := self;
while (num > 9)
{
num := num.toPrintable().toArray().selectBy:(ch => ch.toInt() - 48).summarize(new LongIntege... |
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
{\displ... | #Elixir | Elixir | defmodule Digital do
def root(n, base\\10), do: root(n, base, 0)
defp root(n, base, ap) when n < base, do: {n, ap}
defp root(n, base, ap) do
Integer.digits(n, base) |> Enum.sum |> root(base, ap+1)
end
end
data = [627615, 39390, 588225, 393900588225]
Enum.each(data, fn n ->
{dr, ap} = Digital.root(n)
... |
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
... | #PicoLisp | PicoLisp | (de mdr-mp (N)
"Returns the solutions in a list, i.e., '(MDR MP)"
(let MP 0
(while (< 1 (length N))
(setq N (apply * (mapcar format (chop N))))
(inc 'MP) )
(list N MP) ) )
# Get the MDR/MP of these nums.
(setq Test-nums '(123321 7739 893 899998))
(let Fmt (6 5 5)
(tab Fmt ... |
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
... | #Phix | Phix | with javascript_semantics
function mdr_mp(integer m)
integer mp = 0
while m>9 do
integer newm = 1
while m do
newm *= remainder(m,10)
m = floor(m/10)
end while
m = newm
mp += 1
end while
return {m,mp}
end function
constant tests = {123321,... |
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... | #jq | jq | # Input: an array representing the apartment house, with null at a
# particular position signifying that the identity of the occupant
# there has not yet been determined.
# Output: an elaboration of the input array but including person, and
# satisfying cond, where . in cond refers to the placement of person
de... |
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 ... | #Factor | Factor | USING: kernel math.vectors sequences ;
: dot-product ( u v -- w )
2dup [ length ] bi@ =
[ v. ] [ "Vector lengths must be equal" throw ] if ; |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #FALSE | FALSE | [[\1-$0=~][$d;2*1+\-ø\$d;2+\-ø@*@+]#]p:
3d: {Vectors' length}
1 3 5_ 4 2_ 1_ d;$1+ø@*p;!%. {Output: 3} |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #D | D | import std.stdio;
void squeezable(string s, char rune) {
writeln("squeeze: '", rune, "'");
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last || c != rune) {
write(c);
len++;
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Delphi | Delphi |
program Determine_if_a_string_is_squeezable;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
var
TestStrings: TArray<string> = ['',
'''If I were two-faced, would I be wearing this one?'' --- Abraham Lincoln ',
'..1111111111111111111111111111111111111111111111111111111111111117777888',
'I never give ''e... |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ... | #11l | 11l | V dxs = [-0.533, 0.27, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251,
-0.231, -0.401, 0.269, 0.491, 0.951, 1.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213, -0.423,... |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #F.23 | F# |
// Descending primes. Nigel Galloway: April 19th., 2022
[2;3;5;7]::List.unfold(fun(n,i)->match n with []->None |_->let n=n|>List.map(fun(n,g)->[for n in n..9->(n+1,i*n+g)])|>List.concat in Some(n|>List.choose(fun(_,n)->if isPrime n then Some n else None),(n|>List.filter(fst>>(>)10),i*10)))([(4,3);(2,1);(8,7)],10)
|... |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Factor | Factor | USING: grouping grouping.extras math math.combinatorics
math.functions math.primes math.ranges prettyprint sequences
sequences.extras ;
9 1 [a,b] all-subsets [ reverse 0 [ 10^ * + ] reduce-index ]
[ prime? ] map-filter 10 "" pad-groups 10 group simple-table. |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #FreeBASIC | FreeBASIC | #include "isprime.bas"
#include "sort.bas"
Dim As Double t0 = Timer
Dim As Integer i, n, tmp, num, cant
Dim Shared As Integer matriz(512)
For i = 0 To 511
n = 0
tmp = i
num = 9
While tmp
If tmp And 1 Then n = n * 10 + num
tmp = tmp Shr 1
num -= 1
Wend
matriz(i) = n
Next... |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #C | C | #include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double x, y;
} Point;
double det2D(const Point * const p1, const Point * const p2, const Point * const p3) {
return p1->x * (p2->y - p3->y)
+ p2->x * (p3->y - p1->y)
+ p3->x * (p1->y - p2->y);
}
... |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #Common_Lisp | Common Lisp |
(defun determinant (rows &optional (skip-cols nil))
(let* ((result 0) (sgn -1))
(dotimes (col (length (car rows)) result)
(unless (member col skip-cols)
(if (null (cdr rows))
(return-from determinant (elt (car rows) col))
(incf result (* (setq sgn (- sgn)) (elt (car rows) col) ... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #ALGOL_W | ALGOL W | begin
% integer division procedure %
% sets c to a divided by b, returns true if the division was OK, %
% false if there was division by zero %
logical procedure divideI ( integer value a, b; integer resul... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Arturo | Arturo | try? -> 3/0
else -> print "division by zero" |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #APL | APL | ⊃⎕VFI{w←⍵⋄((w='-')/w)←'¯'⋄w}'152 -3.1415926 Foo123'
1 1 0 |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #AppleScript | AppleScript |
-- isNumString :: String -> Bool
on isNumString(s)
try
if class of s is string then
set c to class of (s as number)
c is real or c is integer
else
false
end if
on error
false
end try
end isNumString
-- TEST
on run
map(isNumStr... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #AWK | AWK |
# syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_UNIQUE_CHARACTERS.AWK
BEGIN {
for (i=0; i<=255; i++) { ord_arr[sprintf("%c",i)] = i } # build array[character]=ordinal_value
n = split(",.,abcABC,XYZ ZYX,1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",arr,",")
for (i in arr) {
width = max(width,length(arr[i]))
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #Clojure | Clojure |
(defn collapse [s]
(let [runs (partition-by identity s)]
(apply str (map first runs))))
(defn run-test [s]
(let [out (collapse s)]
(str (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)\n" out (count out)))))
|
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #CLU | CLU | % Collapse a string
collapse = proc (s: string) returns (string)
out: array[char] := array[char]$[]
last: char := '\000'
for c: char in string$chars(s) do
if c ~= last then
last := c
array[char]$addh(out,c)
end
end
return (string$ac2s(out))
end collapse
%... |
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 (i... | #Rust | Rust | // Returns a vector containing the number of ways each possible sum of face
// values can occur.
fn get_totals(dice: usize, faces: usize) -> Vec<f64> {
let mut result = vec![1.0; faces + 1];
for d in 2..=dice {
let mut tmp = vec![0.0; d * faces + 1];
for i in d - 1..result.len() {
fo... |
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 (i... | #Sidef | Sidef | func combos(sides, n) {
n || return [1]
var ret = ([0] * (n*sides.max + 1))
combos(sides, n-1).each_kv { |i,v|
v && for s in sides { ret[i + s] += v }
}
return ret
}
func winning(sides1, n1, sides2, n2) {
var (p1, p2) = (combos(sides1, n1), combos(sides2, n2))
var (win,loss,tie) = ... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #C.2B.2B | C++ | #include <iostream>
#include <string>
void all_characters_are_the_same(const std::string& str) {
size_t len = str.length();
std::cout << "input: \"" << str << "\", length: " << len << '\n';
if (len > 0) {
char ch = str[0];
for (size_t i = 1; i < len; ++i) {
if (str[i] != ch) {
... |
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 rou... | #Java | Java |
package diningphilosophers;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
enum PhilosopherState { Get, Eat, Pon }
class Fork {
public static final int ON_TABLE = -1;
static int instances = 0;
p... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #J | J | require'dates'
leap=: _1j1 * 0 -/@:= 4 100 400 |/ {.@]
bs=: ((#:{.) + 0 j. *@[ * {:@]) +.
disc=: ((1+0 73 bs[ +^:(58<]) -/@todayno@(,: 1 1,~{.)@]) ,~1166+{.@])~ leap |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #Julia | Julia | struct Digraph{T <: Real,U}
edges::Dict{Tuple{U,U},T}
verts::Set{U}
end
function Digraph(edges::Vector{Tuple{U,U,T}}) where {T <: Real,U}
vnames = Set{U}(v for edge in edges for v in edge[1:2])
adjmat = Dict((edge[1], edge[2]) => edge[3] for edge in edges)
return Digraph(adjmat, vnames)
end
vert... |
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
{\displ... | #Erlang | Erlang | -module( digital_root ).
-export( [task/0] ).
task() ->
Ns = [N || N <- [627615, 39390, 588225, 393900588225]],
Persistances = [persistance_root(X) || X <- Ns],
[io:fwrite("~p has additive persistence ~p and digital root of ~p~n", [X, Y, Z]) || {X, {Y, Z}} <- lists:zip(Ns, Persistances)].
persistanc... |
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
... | #PL.2FI | PL/I | multiple: procedure options (main); /* 29 April 2014 */
declare n fixed binary (31);
find_mdr: procedure;
declare (mdr, mp, p) fixed binary (31);
mdr = n;
do mp = 1 by 1 until (p <= 9);
p = 1;
do until (mdr = 0); /* Form product of the digits in mdr. */
p = mod(mdr, 10) * p;
... |
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... | #Julia | Julia | using Combinatorics
function solve(n::Vector{<:AbstractString}, pred::Vector{<:Function})
rst = Vector{typeof(n)}(0)
for candidate in permutations(n)
if all(p(candidate) for p in predicates)
push!(rst, candidate)
end
end
return rst
end
Names = ["Baker", "Cooper", "Fletche... |
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 ... | #Fantom | Fantom | class DotProduct
{
static Int dotProduct (Int[] a, Int[] b)
{
Int result := 0
[a.size,b.size].min.times |i|
{
result += a[i] * b[i]
}
return result
}
public static Void main ()
{
Int[] x := [1,2,3,4]
Int[] y := [2,3,4]
echo ("Dot product of $x and $y is ${dotProduct(x... |
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 ... | #Forth | Forth | : vector create cells allot ;
: th cells + ;
3 constant /vector
/vector vector a
/vector vector b
: dotproduct ( a1 a2 -- n)
0 tuck ?do -rot over i th @ over i th @ * >r rot r> + loop nip nip
;
: vector! cells over + swap ?do i ! 1 cells +loop ;
-5 3 1 a /vector vector!
-1 -2 4 b /v... |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #F.23 | F# |
// Determine if a string is squeezable. Nigel Galloway: June 9th., 2020
let squeeze n i=if String.length n=0 then None else
let fN=let mutable g=n.[0] in (fun n->if n=i && n=g then false else g<-n; true)
let fG=n.[0..0]+System.String(n.[1..].ToCharArray()|>Array.filter fN)
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Factor | Factor | USING: formatting fry io kernel math sbufs sequences strings ;
IN: rosetta-code.squeeze
: (squeeze) ( str c -- new-str )
[ unclip-slice 1string >sbuf ] dip
'[ over last over [ _ = ] both? [ drop ] [ suffix! ] if ]
reduce >string ;
: squeeze ( str c -- new-str )
over empty? [ 2drop "" ] [ (squeeze) ]... |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ... | #Ada | Ada | with Ada.Numerics.Elementary_Functions;
with Ada.Text_IO;
procedure Demings_Funnel is
type Float_List is array (Positive range <>) of Float;
Dxs : constant Float_List :=
(-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001... |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Forth | Forth | : is-prime? \ n -- f ; \ Fast enough for this application
DUP 1 AND IF \ n is odd
DUP 3 DO
DUP I DUP * < IF DROP -1 LEAVE THEN \ Leave loop if I**2 > n
DUP I MOD 0= IF DROP 0 LEAVE THEN \ Leave loop if n%I is zero
2 +LOOP \ iterate over odd I only
ELSE \ n is even
... |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Go | Go | package main
import (
"fmt"
"rcu"
"sort"
"strconv"
)
func combinations(a []int, k int) [][]int {
n := len(a)
c := make([]int, k)
var combs [][]int
var combine func(start, end, index int)
combine = func(start, end, index int) {
if index == k {
t := make([]int, ... |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #C.23 | C# | using System;
using System.Collections.Generic;
namespace TriangleOverlap {
class Triangle {
public Tuple<double, double> P1 { get; set; }
public Tuple<double, double> P2 { get; set; }
public Tuple<double, double> P3 { get; set; }
public Triangle(Tuple<double, double> p1, Tuple<d... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #11l | 11l | fs:remove_file(‘output.txt’)
fs:remove_dir(‘docs’)
fs:remove_file(‘/output.txt’)
fs:remove_dir(‘/docs’) |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #D | D | import std.algorithm, std.range, std.traits, permutations2,
permutations_by_swapping1;
auto prod(Range)(Range r) nothrow @safe @nogc {
return reduce!q{a * b}(ForeachType!Range(1), r);
}
T permanent(T)(in T[][] a) nothrow @safe
in {
assert(a.all!(row => row.length == a[0].length));
} body {
auto r... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #AutoHotkey | AutoHotkey | ZeroDiv(num1, num2) {
If ((num1/num2) != "")
MsgBox % num1/num2
Else
MsgBox, 48, Warning, The result is not valid (Divide By Zero).
}
ZeroDiv(0, 3) ; is ok
ZeroDiv(3, 0) ; divize by zero alert |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #BASIC | BASIC | 100 REM TRY
110 ONERR GOTO 200
120 D = - 44 / 0
190 END
200 REM CATCH
210 E = PEEK (222) < > 133
220 POKE 216,0: REM ONERR OFF
230 IF E THEN RESUME
240 CALL - 3288: REM RECOVER
250 PRINT "DIVISION BY ZERO"
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program strNumber.s */
/* Constantes */
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #C | C |
#include<stdbool.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
typedef struct positionList{
int position;
struct positionList *next;
}positionList;
typedef struct letterList{
char letter;
int repititions;
positionList* positions;
struct letterList *next;
}letterList;
letterL... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #Cowgol | Cowgol | include "cowgol.coh";
include "strings.coh";
# Collapse the string at in, and store the result in the given buffer
sub collapse(in: [uint8], out: [uint8]) is
var ch := [in];
in := @next in;
loop
if ch == 0 then
[out] := 0;
return;
elseif [in] != ch then
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #D | D | import std.stdio;
void collapsible(string s) {
writeln("old: <<<", s, ">>>, length = ", s.length);
write("new: <<<");
char last = '\0';
int len = 0;
foreach (c; s) {
if (c != last) {
write(c);
len++;
}
last = c;
}
writeln(">>>, length = ", ... |
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 (i... | #Tcl | Tcl | foreach d0 {1 2 3 4 5 6} {
foreach d1 {1 2 3 4 5 6} {
...
foreach dN {1 2 3 4 5 6} {
dict incr sum [::tcl::mathop::+ $n $d0 $d1 ... $DN]
}
...
}
} |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #Vlang | Vlang | import math
fn min_of(x int, y int) int {
if x < y {
return x
}
return y
}
fn throw_die(n_sides int, n_dice int, s int, mut counts []int) {
if n_dice == 0 {
counts[s]++
return
}
for i := int(1); i <= n_sides; i++ {
throw_die(n_sides, n_dice - 1, s + i, mut cou... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Clojure | Clojure |
(defn check-all-chars-same [s]
(println (format "String (%s) of len: %d" s (count s)))
(let [num-same (-> (take-while #(= (first s) %) s)
count)]
(if (= num-same (count s))
(println "...all characters the same")
(println (format "...character %d differs - it is 0x%x"
... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Common_Lisp | Common Lisp | (defun strequ (&rest str)
(if (not str) (setf str (list "" " " "2" "333" ".55" "tttTTT" "4444 444k")))
(dolist (s str)
(do ((i 0 (1+ i)))
((cond
((= i (length s))
(format t "\"~a\" [~d] : All characters are identical.~%" s (length s)) t)
... |
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 rou... | #JoCaml | JoCaml | let random_wait n = Unix.sleep (Random.int n);;
let print s m = Printf.printf "philosopher %s is %s\n" s m; flush(stdout);;
let will_eat s = print s "eating"; random_wait 10;;
let will_think s = print s "thinking"; random_wait 20; print s "hungry";;
(* a,b,c,d,e are thinking philosophers; ah,bh,ch,dh,eh are the sam... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Java | Java | import java.util.Calendar;
import java.util.GregorianCalendar;
public class DiscordianDate {
final static String[] seasons = {"Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"};
final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting O... |
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 pro... | #Kotlin | Kotlin | // version 1.1.51
import java.util.TreeSet
class Edge(val v1: String, val v2: String, val dist: Int)
/** One vertex of the graph, complete with mappings to neighbouring vertices */
class Vertex(val name: String) : Comparable<Vertex> {
var dist = Int.MAX_VALUE // MAX_VALUE assumed to be infinity
var pr... |
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
{\displ... | #F.23 | F# |
//Find the Digital Root of An Integer - Nigel Galloway: February 1st., 2015
//This code will work with any integer type
let inline digitalRoot N BASE =
let rec root(p,n) =
let s = sumDigits n BASE
if s < BASE then (s,p) else root(p+1, s)
root(LanguagePrimitives.GenericZero<_> + 1, N)
|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Factor | Factor | USING: arrays formatting kernel math math.text.utils sequences ;
IN: rosetta-code.digital-root
: digital-root ( n -- persistence root )
0 swap [ 1 digit-groups dup length 1 > ] [ sum [ 1 + ] dip ]
while first ;
: print-root ( n -- )
dup digital-root
"%-12d has additive persistence %d and digital roo... |
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
... | #Python | Python | try:
from functools import reduce
except:
pass
def mdroot(n):
'Multiplicative digital root'
mdr = [n]
while mdr[-1] > 9:
mdr.append(reduce(int.__mul__, (int(dig) for dig in str(mdr[-1])), 1))
return len(mdr) - 1, mdr[-1]
if __name__ == '__main__':
print('Number: (MP, MDR)\n======... |
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... | #K | K |
perm: {x@m@&n=(#?:)'m:!n#n:#x}
filter: {y[& x'y]}
reject: {y[& ~x'y]}
adjacent: {1 = _abs (z?x) - (z?y)}
p: perm[`Baker `Cooper `Fletcher `Miller `Smith]
p: reject[{`Cooper=x[0]}; p]
p: reject[{`Baker=x[4]}; p]
p: filter[{(x ? `Miller) > (x ? `Cooper)}; p]
p: reject[{adjacent[`Smith; `Fletcher; x]}; p]
p: reject[{a... |
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 ... | #Fortran | Fortran | program test_dot_product
write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1])
end program test_dot_product |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Frink | Frink | dotProduct[v1, v2] :=
{
if length[v1] != length[v2]
{
println["dotProduct: vectors are of different lengths."]
return undef
}
return sum[map[{|c1,c2| c1 * c2}, zip[v1, v2]]]
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Fortran | Fortran |
program main
implicit none
character(len=:),allocatable :: strings(:)
strings=[ character(len=72) :: &
'', &
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln', &
'..1111111111111111111111111111111111111111111111111111111111111117777888', &
'I never give ''em hell, I just tell the truth, and... |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ... | #D | D | import std.stdio, std.math, std.algorithm, std.range, std.typecons;
auto mean(T)(in T[] xs) pure nothrow @nogc {
return xs.sum / xs.length;
}
auto stdDev(T)(in T[] xs) pure nothrow {
immutable m = xs.mean;
return sqrt(xs.map!(x => (x - m) ^^ 2).sum / xs.length);
}
alias TF = double function(in double,... |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #11l | 11l | print(‘Police Sanitation Fire’)
print(‘----------------------------------’)
L(police) (2..6).step(2)
L(sanitation) 1..7
L(fire) 1..7
I police!=sanitation & sanitation!=fire & fire!=police & police+fire+sanitation==12
print(police"\t\t"sanitation"\t\t"fire) |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #J | J | extend=: {{ y;y,L:0(1+each i.1-{:y)}}
($~ q:@$)(#~ 1 p: ])10#.&>([:~.@;extend each)^:# >:i.9
2 3 31 43 41 431 421 5 53 541 521 5431 61 653 643 641 631 6521 6421 7 73 71 761 751 743 7643 7621 7541 7321
76543 76541 76421 75431 764321 83 ... |
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Julia | Julia | using Combinatorics
using Primes
function descendingprimes()
return sort!(filter(isprime, [evalpoly(10, x)
for x in powerset([1, 2, 3, 4, 5, 6, 7, 8, 9]) if !isempty(x)]))
end
foreach(p -> print(rpad(p[2], 10), p[1] % 10 == 0 ? "\n" : ""), enumerate(descendingprimes()))
|
http://rosettacode.org/wiki/Descending_primes | Descending primes | Generate and show all primes with strictly descending decimal digits.
See also
OEIS:A052014 - Primes with distinct digits in descending order
Related
Ascending primes
| #Lua | Lua | local function is_prime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
for f = 5, n^0.5, 6 do
if n%f==0 or n%(f+2)==0 then return false end
end
return true
end
local function descending_primes()
local digits, candidates, primes = {9,8,7,6,5,4,... |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #C.2B.2B | C++ | #include <vector>
#include <iostream>
#include <stdexcept>
using namespace std;
typedef std::pair<double, double> TriPoint;
inline double Det2D(TriPoint &p1, TriPoint &p2, TriPoint &p3)
{
return +p1.first*(p2.second-p3.second)
+p2.first*(p3.second-p1.second)
+p3.first*(p1.second-p2.second);
}
void CheckTriW... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #8th | 8th |
"input.txt" f:rm drop
"/input.txt" f:rm drop
"docs" f:rmdir drop
"/docs" f:rmdir drop
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program deleteFic64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesAR... |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #Delphi | Delphi |
program Determinant_and_permanent;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TMatrix = TArray<TArray<Double>>;
function Minor(a: TMatrix; x, y: Integer): TMatrix;
begin
var len := Length(a) - 1;
SetLength(result, len, len);
for var i := 0 to len - 1 do
begin
for var j := 0 to len - 1 do
... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Batch_File | Batch File | @echo off
set /a dummy=5/0 2>nul
if %errorlevel%==1073750993 echo I caught a division by zero operation...
exit /b 0 |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #BQN | BQN | Div ← {∨´"∞"‿"NaN"≡¨<•Fmt𝕩}◶⊢‿"Division by 0"÷
•Show 5 Div 0
•Show 5 Div 5
•Show 0 Div 0 |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Arturo | Arturo | print numeric? "hello world"
print numeric? "1234"
print numeric? "1234 hello world"
print numeric? "12.34"
print numeric? "!#@$"
print numeric? "-1.23" |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #AutoHotkey | AutoHotkey | list = 0 .14 -5.2 ten 0xf
Loop, Parse, list, %A_Space%
MsgBox,% IsNumeric(A_LoopField)
Return
IsNumeric(x) {
If x is number
Return, 1
Else Return, 0
}
;Output: 1 1 1 0 1 |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #C.23 | C# | using System;
using System.Linq;
public class Program
{
static void Main
{
string[] input = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"};
foreach (string s in input) {
Console.WriteLine($"\"{s}\" (Length {s.Length}) " +
string.Join(", ",
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #Delphi | Delphi |
program Determine_if_a_string_is_collapsible;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure collapsible(s: string);
var
c, last: char;
len: Integer;
begin
writeln('old: <<<', s, '>>>, length = ', s.length);
write('new: <<<');
last := #0;
len := 0;
for c in s do
begin
if c <> last then... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #F.23 | F# |
// Collapse a String. Nigel Galloway: June 9th., 2020
//As per the task description a function which 'determines if a character string is collapsible' by testing if any consecutive characters are the same.
let isCollapsible n=n|>Seq.pairwise|>Seq.tryFind(fun(n,g)->n=g)
//As per the task description a function which '... |
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 (i... | #Wren | Wren | var throwDie // recursive
throwDie = Fn.new { |nSides, nDice, s, counts|
if (nDice == 0) {
counts[s] = counts[s] + 1
return
}
for (i in 1..nSides) throwDie.call(nSides, nDice-1, s + i, counts)
}
var beatingProbability = Fn.new { |nSides1, nDice1, nSides2, nDice2|
var len1 = (nSides1 + ... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #D | D | import std.stdio;
void analyze(string s) {
writefln("Examining [%s] which has a length of %d:", s, s.length);
if (s.length > 1) {
auto b = s[0];
foreach (i, c; s[1..$]) {
if (c != b) {
writeln(" Not all characters in the string are the same.");
wr... |
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 rou... | #Julia | Julia |
mutable struct Philosopher
name::String
hungry::Bool
righthanded::Bool
rightforkheld::Channel
leftforkheld::Channel
function Philosopher(name, leftfork, rightfork)
this = new()
this.name = name
this.hungry = rand([false, true]) # not specified so start as either
... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #JavaScript | JavaScript |
/**
* All Hail Discordia! - this script prints Discordian date using system date.
*
* lang: JavaScript
* author: jklu
* contributors: JamesMcGuigan
*
* changelog:
* - Modified to return same output syntax as unix ddate + module.exports - James McGuigan, 2/Chaos/3183
*
* source: https://rosettacode.org/wiki/... |
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 pro... | #Lua | Lua | -- Graph definition
local edges = {
a = {b = 7, c = 9, f = 14},
b = {c = 10, d = 15},
c = {d = 11, f = 2},
d = {e = 6},
e = {f = 9}
}
-- Fill in paths in the opposite direction to the stated edges
function complete (graph)
for node, edges in pairs(graph) do
for edge, distance in pairs(... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.