task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #Forth | Forth | : (Sdigit) 0 swap begin base @ /mod >r + r> dup 0= until drop ;
: digiroot 0 swap begin (Sdigit) >r 1+ r> dup base @ < until ; |
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
| #Fortran | Fortran |
program prec
implicit none
integer(kind=16) :: i
i = 627615
call root_pers(i)
i = 39390
call root_pers(i)
i = 588225
call root_pers(i)
i = 393900588225
call root_pers(i)
end program
subroutine root_pers(i)
implicit none
integer(kind=16) :: N, s, a, i
write(*,*) 'Number: ', i
n = i
a = 0
do while(n.ge.10)
a = a + 1
s = 0
do while(n.gt.0)
s = s + n-int(real(n,kind=8)/10.0D0,kind=8) * 10_8
n = int(real(n,kind=16)/real(10,kind=8),kind=8)
end do
n = s
end do
write(*,*) 'digital root = ', s
write(*,*) 'additive persistance = ', a
end subroutine
|
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
| #Quackery | Quackery | [ abs 1 swap
[ base share /mod
rot * swap
dup 0 = until ]
drop ] is digitproduct ( n --> n )
[ 0 swap
[ dup base share > while
dip 1+
digitproduct again ] ] is mdr ( n --> n n )
[ dup mdr
rot echo
say ": "
swap echo
say ", "
echo cr ] is task.1 ( n --> )
[ times
[ i^ [] swap dup rot
[ unrot dup mdr nip
swap dip
[ over = ]
swap iff
[ rot over join ]
else rot
dip 1+
dup size 5 = until ]
i^ echo say " : "
echo cr 2drop ] ] is task.2 ( n --> )
' [ 123321 7739 893 899998 ] witheach task.1
cr
10 task.2 |
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
| #Racket | Racket | #lang racket
(define (digital-product n)
(define (inr-d-p m rv)
(cond
[(zero? m) rv]
[else (define-values (q r) (quotient/remainder m 10))
(if (zero? r) 0 (inr-d-p q (* rv r)))])) ; lazy on zero
(inr-d-p n 1))
(define (mdr/mp n)
(define (inr-mdr/mp m i)
(if (< m 10) (values m i) (inr-mdr/mp (digital-product m) (add1 i))))
(inr-mdr/mp n 0))
(printf "Number\tMDR\tmp~%======\t===\t==~%")
(for ((n (in-list '(123321 7739 893 899998))))
(define-values (mdr mp) (mdr/mp n))
(printf "~a\t~a\t~a~%" n mdr mp))
(printf "~%MDR\t[n0..n4]~%===\t========~%")
(for ((MDR (in-range 10)))
(define (has-mdr? n) (define-values (mdr mp) (mdr/mp n)) (= mdr MDR))
(printf "~a\t~a~%" MDR (for/list ((_ 5) (n (sequence-filter has-mdr? (in-naturals)))) 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 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?
| #Kotlin | Kotlin | // version 1.1.3
typealias Predicate = (List<String>) -> Boolean
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
/* looks for for all possible solutions, not just the first */
fun dinesman(occupants: List<String>, predicates: List<Predicate>) =
permute(occupants).filter { perm -> predicates.all { pred -> pred(perm) } }
fun main(args: Array<String>) {
val occupants = listOf("Baker", "Cooper", "Fletcher", "Miller", "Smith")
val predicates = listOf<Predicate>(
{ it.last() != "Baker" },
{ it.first() != "Cooper" },
{ it.last() != "Fletcher" && it.first() != "Fletcher" },
{ it.indexOf("Miller") > it.indexOf("Cooper") },
{ Math.abs(it.indexOf("Smith") - it.indexOf("Fletcher")) > 1 },
{ Math.abs(it.indexOf("Fletcher") - it.indexOf("Cooper")) > 1 }
)
val solutions = dinesman(occupants, predicates)
val size = solutions.size
if (size == 0) {
println("No solutions found")
}
else {
val plural = if (size == 1) "" else "s"
println("$size solution$plural found, namely:\n")
for (solution in solutions) {
for ((i, name) in solution.withIndex()) {
println("Floor ${i + 1} -> $name")
}
println()
}
}
} |
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
| #FunL | FunL | import lists.zipWith
def dot( a, b )
| a.length() == b.length() = sum( zipWith((*), a, b) )
| otherwise = error( "Vector sizes must match" )
println( dot([1, 3, -5], [4, -2, -1]) ) |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #FreeBASIC | FreeBASIC | #define NAN 0.0/0.0 'dot product of different-dimensioned vectors is no more defined than 0/0
function dot( a() as double, b() as double ) as double
if ubound(a)<>ubound(b) then return NAN
dim as uinteger i
dim as double dp = 0.0
for i = 0 to ubound(a)
dp += a(i)*b(i)
next i
return dp
end function
dim as double zero3d(0 to 2) = {0.0, 0.0, 0.0} 'some example vectors
dim as double zero5d(0 to 4) = {0.0, 0.0, 0.0, 0.0, 0.0}
dim as double x(0 to 2) = {1.0, 0.0, 0.0}
dim as double y(0 to 2) = {0.0, 1.0, 0.0}
dim as double z(0 to 2) = {0.0, 0.0, 1.0}
dim as double q(0 to 2) = {1.0, 1.0, 3.14159}
dim as double r(0 to 2) = {-1.0, 2.618033989, 3.0}
print " q dot r = ", dot(q(), r())
print " zero3d dot zero5d = ", dot(zero3d(), zero5d())
print " zero3d dot x = ", dot(zero3d(), x())
print " z dot z = ", dot(z(), z())
print " y dot z = ", dot(y(), z()) |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC |
function squeeze(byval s as string,target as string) as string
dim as string g
dim as long n
for n =0 to len(s)-2
if s[n]=asc(target) then
if s[n]<>s[n+1] then g+=chr(s[n])
else
g+=chr(s[n])
end if
next n
if len(s) then g+=chr(s[n])
return g
end function
dim as string z,o
print "character "" """
o=""
print "original ";o;tab(90);"(";len(o);")"
z=Squeeze("", " ")
print "squeeze "; z;tab(90);"(";len(z);")"
print
print "character ""-"""
o= """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
print "original ";o;tab(90);"(";len(o);")"
z=Squeeze(o,"-")
print "squeeze "; z;tab(90);"(";len(z);")"
print
print "character ""7"""
o="..1111111111111111111111111111111111111111111111111111111111111117777888"
print "original ";o;tab(90);"(";len(o);")"
z=Squeeze(o,"7")
print "squeeze "; z;tab(90);"(";len(z);")"
print
print "character ""."""
o="I never give 'em hell, I just tell the truth, and they think it's hell. "
print "original ";o;tab(90);"(";len(o);")"
z=Squeeze(o,".")
print "squeeze ";z ;tab(90);"(";len(z);")"
print
dim as string s = " --- Harry S Truman "
print "character "" """
o=" --- Harry S Truman "
print "original ";o;tab(90);"(";len(o);")"
z=Squeeze(s, " ")
print "squeeze ";z ;tab(90);"(";len(z);")"
print
print "character ""-"""
o=" --- Harry S Truman "
print "original ";o;tab(90);"(";len(o);")"
z=Squeeze(s, "-")
print "squeeze "; z;tab(90);"(";len(z);")"
print
print "character ""r"""
o=" --- Harry S Truman "
print "original ";o;tab(90);"(";len(o);")"
z=Squeeze(s, "r")
print "squeeze "; z;tab(90);"(";len(z);")"
sleep
|
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Elixir | Elixir | defmodule Deming do
def funnel(dxs, rule) do
{_, rxs} = Enum.reduce(dxs, {0, []}, fn dx,{x,rxs} ->
{rule.(x, dx), [x + dx | rxs]}
end)
rxs
end
def mean(xs), do: Enum.sum(xs) / length(xs)
def stddev(xs) do
m = mean(xs)
Enum.reduce(xs, 0.0, fn x,sum -> sum + (x-m)*(x-m) / length(xs) end)
|> :math.sqrt
end
def experiment(label, dxs, dys, rule) do
{rxs, rys} = {funnel(dxs, rule), funnel(dys, rule)}
IO.puts label
:io.format "Mean x, y : ~7.4f, ~7.4f~n", [mean(rxs), mean(rys)]
:io.format "Std dev x, y : ~7.4f, ~7.4f~n~n", [stddev(rxs), stddev(rys)]
end
end
dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087]
dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032]
Deming.experiment("Rule 1:", dxs, dys, fn _z, _dz -> 0 end)
Deming.experiment("Rule 2:", dxs, dys, fn _z, dz -> -dz end)
Deming.experiment("Rule 3:", dxs, dys, fn z, dz -> -(z+dz) end)
Deming.experiment("Rule 4:", dxs, dys, fn z, dz -> z+dz end) |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Factor | Factor | USING: combinators formatting generalizations grouping.extras io
kernel math math.statistics sequences ;
: show ( seq1 seq2 -- )
[ [ mean ] bi@ ] [ [ population-std ] bi@ ] 2bi
"Mean x, y : %.4f, %.4f\nStd dev x, y : %.4f, %.4f\n"
printf ;
{
-0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275
1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001
-0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014
0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051 0.047
-0.095 0.695 0.340 -0.182 0.287 0.213 -0.423 -0.021
-0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315
0.201 0.034 0.097 -0.170 0.054 -0.553 -0.024 -0.181
-0.700 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658
0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774
-1.043 0.051 0.021 0.247 -0.310 0.171 0.000 0.106
0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017
0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598
0.443 -0.521 -0.799 0.087
}
{
0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395
0.490 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.000
0.426 0.205 -0.765 -2.188 -0.742 -0.010 0.089 0.208
0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096
-0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007
0.009 0.508 -0.790 0.723 0.881 -0.508 0.393 -0.226
0.710 0.038 -0.217 0.831 0.480 0.407 0.447 -0.295
1.126 0.380 0.549 -0.445 -0.046 0.428 -0.074 0.217
-0.822 0.491 1.347 -0.141 1.230 -0.044 0.079 0.219
0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104
-0.729 0.650 -1.103 0.154 -1.720 0.051 -0.385 0.477
1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224
-0.947 -1.424 -0.542 -1.032
}
{
[ "Rule 1:" print ]
[ "Rule 2:" print [ [ [ swap neg + ] 2clump-map ] [ first suffix ] bi ] bi@ ]
[ "Rule 3:" print [ 0 [ - neg ] accumulate* ] bi@ ]
[ "Rule 4:" print [ cum-sum ] bi@ ]
} [ show ] map-compose 2cleave |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #8080_Assembly | 8080 Assembly | org 100h
lxi h,obuf ; HL = output buffer
mvi b,2 ; B = police
pol: mvi c,1 ; C = sanitation
san: mvi d,1 ; D = fire
fire: mov a,b ; Fire equal to police?
cmp d
jz next ; If so, invalid combination
mov a,c ; Fire equal to sanitation?
cmp d
jz next ; If so, invalid combination
mov a,b ; Total equal to 12?
add c
add d
cpi 12
jnz next ; If not, invalid combination
mov a,b ; Combination is valid, add to output
call num
mov a,c
call num
mov a,d
call num
mvi m,13 ; Add a newline to the output
inx h
mvi m,10
inx h
next: mvi a,7 ; Load 7 to compare to
inr d ; Next fire number
cmp d ; Reached the end?
jnc fire ; If not, next fire number
inr c ; Otherwise, next sanitation number
cmp c ; Reached the end?
jnc san ; If not, next sanitation number
inr b ; Increment police number twice
inr b ; (twice, because it must be even)
cmp b ; Reached the end?
jnc pol ; If not, next police number
mvi m,'$' ; If so, we're done - add CP/M string terminator
mvi c,9 ; Print the output string
lxi d,ohdr
jmp 5
num: adi '0' ; Add number A and space to the output
mov m,a
inx h
mvi m,' '
inx h
ret
ohdr: db 'P S F',13,10
obuf: equ $ ; Output buffer goes after program |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Sort[Select[FromDigits/@Subsets[Range[9,1,-1],{1,\[Infinity]}],PrimeQ]] |
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
| #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Descending_primes
use warnings;
use ntheory qw( is_prime );
print join('', sort map { sprintf "%9d", $_ } grep /./ && is_prime($_),
glob join '', map "{$_,}", reverse 1 .. 9) =~ s/.{45}\K/\n/gr; |
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
| #Phix | Phix | with javascript_semantics
function descending_primes(sequence res, atom p=0, max_digit=9)
for d=1 to max_digit do
atom np = p*10+d
if odd(d) and is_prime(np) then res &= np end if
res = descending_primes(res,np,d-1)
end for
return res
end function
sequence r = sort(descending_primes({2})),
--sequence r = descending_primes({2}),
j = join_by(r,1,11," ","\n","%8d")
printf(1,"There are %,d descending primes:\n%s\n",{length(r),j})
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Delegation is
package Things is
-- We need a common root for our stuff
type Object is tagged null record;
type Object_Ptr is access all Object'Class;
-- Objects that have operation thing
type Substantial is new Object with null record;
function Thing (X : Substantial) return String;
-- Delegator objects
type Delegator is new Object with record
Delegate : Object_Ptr;
end record;
function Operation (X : Delegator) return String;
No_Thing : aliased Object; -- Does not have thing
Has_Thing : aliased Substantial; -- Has one
end Things;
package body Things is
function Thing (X : Substantial) return String is
begin
return "delegate implementation";
end Thing;
function Operation (X : Delegator) return String is
begin
if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
return Thing (Substantial'Class (X.Delegate.all));
else
return "default implementation";
end if;
end Operation;
end Things;
use Things;
A : Delegator; -- Without a delegate
begin
Put_Line (A.Operation);
A.Delegate := No_Thing'Access; -- Set no thing
Put_Line (A.Operation);
A.Delegate := Has_Thing'Access; -- Set a thing
Put_Line (A.Operation);
end Delegation; |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #D | D | import std.stdio;
import std.typecons;
alias Pair = Tuple!(real, real);
struct Triangle {
Pair p1;
Pair p2;
Pair p3;
void toString(scope void delegate(const(char)[]) sink) const {
import std.format;
sink("Triangle: ");
formattedWrite!"%s"(sink, p1);
sink(", ");
formattedWrite!"%s"(sink, p2);
sink(", ");
formattedWrite!"%s"(sink, p3);
}
}
auto det2D(Triangle t) {
return t.p1[0] *(t.p2[1] - t.p3[1])
+ t.p2[0] *(t.p3[1] - t.p1[1])
+ t.p3[0] *(t.p1[1] - t.p2[1]);
}
void checkTriWinding(Triangle t, bool allowReversed) {
auto detTri = t.det2D();
if (detTri < 0.0) {
if (allowReversed) {
auto a = t.p3;
t.p3 = t.p2;
t.p2 = a;
} else {
throw new Exception("Triangle has wrong winding direction");
}
}
}
auto boundaryCollideChk(Triangle t, real eps) {
return t.det2D() < eps;
}
auto boundaryDoesntCollideChk(Triangle t, real eps) {
return t.det2D() <= eps;
}
bool triTri2D(Triangle t1, Triangle t2, real eps = 0.0, bool allowReversed = false, bool onBoundary = true) {
// Triangles must be expressed anti-clockwise
checkTriWinding(t1, allowReversed);
checkTriWinding(t2, allowReversed);
// 'onBoundary' determines whether points on boundary are considered as colliding or not
auto chkEdge = onBoundary ? &boundaryCollideChk : &boundaryDoesntCollideChk;
auto lp1 = [t1.p1, t1.p2, t1.p3];
auto lp2 = [t2.p1, t2.p2, t2.p3];
// for each edge E of t1
foreach (i; 0..3) {
auto j = (i + 1) % 3;
// Check all points of t2 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &&
chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &&
chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) {
return false;
}
}
// for each edge E of t2
foreach (i; 0..3) {
auto j = (i + 1) % 3;
// Check all points of t1 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &&
chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &&
chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) {
return false;
}
}
// The triangles overlap
return true;
}
void overlap(Triangle t1, Triangle t2, real eps = 0.0, bool allowReversed = false, bool onBoundary = true) {
if (triTri2D(t1, t2, eps, allowReversed, onBoundary)) {
writeln("overlap");
} else {
writeln("do not overlap");
}
}
void main() {
auto t1 = Triangle(Pair(0.0, 0.0), Pair(5.0, 0.0), Pair(0.0, 5.0));
auto t2 = Triangle(Pair(0.0, 0.0), Pair(5.0, 0.0), Pair(0.0, 6.0));
writeln(t1, " and\n", t2);
overlap(t1, t2);
writeln;
// need to allow reversed for this pair to avoid exception
t1 = Triangle(Pair(0.0, 0.0), Pair(0.0, 5.0), Pair(5.0, 0.0));
t2 = t1;
writeln(t1, " and\n", t2);
overlap(t1, t2, 0.0, true);
writeln;
t1 = Triangle(Pair(0.0, 0.0), Pair(5.0, 0.0), Pair(0.0, 5.0));
t2 = Triangle(Pair(-10.0, 0.0), Pair(-5.0, 0.0), Pair(-1.0, 6.0));
writeln(t1, " and\n", t2);
overlap(t1, t2);
writeln;
t1.p3 = Pair(2.5, 5.0);
t2 = Triangle(Pair(0.0, 4.0), Pair(2.5, -1.0), Pair(5.0, 4.0));
writeln(t1, " and\n", t2);
overlap(t1, t2);
writeln;
t1 = Triangle(Pair(0.0, 0.0), Pair(1.0, 1.0), Pair(0.0, 2.0));
t2 = Triangle(Pair(2.0, 1.0), Pair(3.0, 0.0), Pair(3.0, 2.0));
writeln(t1, " and\n", t2);
overlap(t1, t2);
writeln;
t2 = Triangle(Pair(2.0, 1.0), Pair(3.0, -2.0), Pair(3.0, 4.0));
writeln(t1, " and\n", t2);
overlap(t1, t2);
writeln;
t1 = Triangle(Pair(0.0, 0.0), Pair(1.0, 0.0), Pair(0.0, 1.0));
t2 = Triangle(Pair(1.0, 0.0), Pair(2.0, 0.0), Pair(1.0, 1.1));
writeln(t1, " and\n", t2);
writeln("which have only a single corner in contact, if boundary points collide");
overlap(t1, t2);
writeln;
writeln(t1, " and\n", t2);
writeln("which have only a single corner in contact, if boundary points do not collide");
overlap(t1, t2, 0.0, false, false);
} |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Action.21 | Action! | PROC Dir(CHAR ARRAY filter)
CHAR ARRAY line(255)
BYTE dev=[1]
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
PrintE(line)
IF line(0)=0 THEN
EXIT
FI
OD
Close(dev)
RETURN
PROC DeleteFile(CHAR ARRAY fname)
BYTE dev=[1]
Close(dev)
Xio(dev,0,33,0,0,fname)
RETURN
PROC Main()
CHAR ARRAY filter="D:*.*", fname="D:INPUT.TXT"
PrintF("Dir ""%S""%E",filter)
Dir(filter)
PrintF("Delete file ""%S""%E%E",fname)
DeleteFile(fname)
PrintF("Dir ""%S""%E",filter)
Dir(filter)
RETURN |
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.
| #Ada | Ada | with Ada.Directories; use Ada.Directories; |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #EchoLisp | EchoLisp |
(lib 'list)
(lib 'matrix)
;; adapted from Racket
(define (permanent M)
(let (( n (matrix-row-num M)))
(for/sum ([σ (in-permutations n)])
(for/product ([i n] [σi σ])
(array-ref M i σi)))))
;; output
(define A (list->array '(1 2 3 4) 2 2))
(array-print A)
1 2
3 4
(determinant A) → -2
(permanent A) → 10
(define M (list->array (iota 25) 5 5))
(array-print M)
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
(determinant M) → 0
(permanent M) → 6778800
|
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.
| #C | C | #include <limits.h> /* INT_MIN */
#include <setjmp.h> /* siglongjmp(), sigsetjmp() */
#include <stdio.h> /* perror(), printf() */
#include <stdlib.h> /* exit() */
#include <signal.h> /* sigaction(), sigemptyset() */
static sigjmp_buf fpe_env;
/*
* This SIGFPE handler jumps to fpe_env.
*
* A SIGFPE handler must not return, because the program might retry
* the division, which might cause an infinite loop. The only safe
* options are to _exit() the program or to siglongjmp() out.
*/
static void
fpe_handler(int signal, siginfo_t *w, void *a)
{
siglongjmp(fpe_env, w->si_code);
/* NOTREACHED */
}
/*
* Try to do x / y, but catch attempts to divide by zero.
*/
void
try_division(int x, int y)
{
struct sigaction act, old;
int code;
/*
* The result must be volatile, else C compiler might delay
* division until after sigaction() restores old handler.
*/
volatile int result;
/*
* Save fpe_env so that fpe_handler() can jump back here.
* sigsetjmp() returns zero.
*/
code = sigsetjmp(fpe_env, 1);
if (code == 0) {
/* Install fpe_handler() to trap SIGFPE. */
act.sa_sigaction = fpe_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_SIGINFO;
if (sigaction(SIGFPE, &act, &old) < 0) {
perror("sigaction");
exit(1);
}
/* Do division. */
result = x / y;
/*
* Restore old hander, so that SIGFPE cannot jump out
* of a call to printf(), which might cause trouble.
*/
if (sigaction(SIGFPE, &old, NULL) < 0) {
perror("sigaction");
exit(1);
}
printf("%d / %d is %d\n", x, y, result);
} else {
/*
* We caught SIGFPE. Our fpe_handler() jumped to our
* sigsetjmp() and passes a nonzero code.
*
* But first, restore old handler.
*/
if (sigaction(SIGFPE, &old, NULL) < 0) {
perror("sigaction");
exit(1);
}
/* FPE_FLTDIV should never happen with integers. */
switch (code) {
case FPE_INTDIV: /* integer division by zero */
case FPE_FLTDIV: /* float division by zero */
printf("%d / %d: caught division by zero!\n", x, y);
break;
default:
printf("%d / %d: caught mysterious error!\n", x, y);
break;
}
}
}
/* Try some division. */
int
main()
{
try_division(-44, 0);
try_division(-44, 5);
try_division(0, 5);
try_division(0, 0);
try_division(INT_MIN, -1);
return 0;
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #AWK | AWK |
$ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}'
|
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #C.2B.2B | C++ | #include <iostream>
#include <string>
void string_has_repeated_character(const std::string& str) {
size_t len = str.length();
std::cout << "input: \"" << str << "\", length: " << len << '\n';
for (size_t i = 0; i < len; ++i) {
for (size_t j = i + 1; j < len; ++j) {
if (str[i] == str[j]) {
std::cout << "String contains a repeated character.\n";
std::cout << "Character '" << str[i]
<< "' (hex " << std::hex << static_cast<unsigned int>(str[i])
<< ") occurs at positions " << std::dec << i + 1
<< " and " << j + 1 << ".\n\n";
return;
}
}
}
std::cout << "String contains no repeated characters.\n\n";
}
int main() {
string_has_repeated_character("");
string_has_repeated_character(".");
string_has_repeated_character("abcABC");
string_has_repeated_character("XYZ ZYX");
string_has_repeated_character("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ");
return 0;
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: formatting io kernel sbufs sequences strings ;
IN: rosetta-code.string-collapse
: (collapse) ( str -- str )
unclip-slice 1string >sbuf
[ over last over = [ drop ] [ suffix! ] if ] reduce >string ;
: collapse ( str -- str ) [ "" ] [ (collapse) ] if-empty ;
: .str ( str -- ) dup length "«««%s»»» (length %d)\n" printf ;
: show-collapse ( str -- )
[ "Before collapse: " write .str ]
[ "After collapse: " write collapse .str ] bi nl ;
: collapse-demo ( -- )
{
""
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
"..1111111111111111111111111111111111111111111111111111111111111117777888"
"I never give 'em hell, I just tell the truth, and they think it's hell. "
" --- Harry S Truman "
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!"
"headmistressship"
"aardvark"
"😍😀🙌💃😍😍😍🙌"
} [ show-collapse ] each ;
MAIN: collapse-demo |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | Const numCad = 5
Data ""
Data "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
Data "..1111111111111111111111111111111111111111111111111111111111111117777888"
Data "I never give 'em hell, I just tell the truth, and they think it's hell. "
Data " --- Harry S Truman "
Dim Shared As String cadIN, cadOUT
Sub Collapse
Dim As String a, b
If cadIN = "" Then cadOUT = cadIN: Exit Sub
cadOUT = Space(Len(cadIN))
a = Left(cadIN,1)
Mid(cadOUT,1,1) = a
Dim As Integer txtOUT = 2
For i As Integer = 2 To Len(cadIN)
b = Mid(cadIN,i,1)
If a <> b Then Mid(cadOUT,txtOUT,1) = b: txtOUT += 1: a = b
Next i
cadOUT = Left(cadOUT,txtOUT-1)
End Sub
For j As Integer = 1 To numCad
Read cadIN
Collapse
Print " <<<"; cadIN; ">>> (longitud "; Len(cadIN); _
!")\n se pliega a:\n <<<"; cadOUT; ">>> (longitud "; Len(cadOUT); !")\n"
Next j
Sleep
|
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
| #zkl | zkl | fcn combos(sides, n){
if(not n) return(T(1));
ret:=((0).max(sides)*n + 1).pump(List(),0);
foreach i,v in (combos(sides, n - 1).enumerate()){
if(not v) continue;
foreach s in (sides){ ret[i + s] += v }
}
ret
}
fcn winning(sides1,n1, sides2,n2){
p1, p2 := combos(sides1, n1), combos(sides2, n2);
win,loss,tie := 0,0,0; # 'win' is 1 beating 2
foreach i,x1 in (p1.enumerate()){
# using accumulated sum on p2 could save some time
win += x1*p2[0,i].sum(0);
tie += x1*p2[i,1].sum(0); // i>p2.len() but p2[bigi,?]-->[]
loss+= x1*p2[i+1,*].sum(0);
}
s := p1.sum(0)*p2.sum(0);
return(win.toFloat()/s, tie.toFloat()/s, loss.toFloat()/s);
} |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Delphi | Delphi |
program Determine_if_a_string_has_all_the_same_characters;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure Analyze(s: string);
var
b, c: char;
i: Integer;
begin
writeln(format('Examining [%s] which has a length of %d:', [s, s.Length]));
if s.Length > 1 then
begin
b := s[1];
for i := 2 to s.Length - 1 do
begin
c := s[i];
if c <> b then
begin
writeln(' Not all characters in the string are the same.');
writeln(format(' "%s" 0x%x is different at position %d', [c, Ord(c), i]));
Exit;
end;
end;
end;
writeln(' All characters in the string are the same.');
end;
var
TestCases: array of string = ['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k'];
w: string;
begin
for w in TestCases do
Analyze(w);
Readln;
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.
| #Kotlin | Kotlin | // Version 1.2.31
import java.util.Random
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
val rand = Random()
class Fork(val name: String) {
val lock = ReentrantLock()
fun pickUp(philosopher: String) {
lock.lock()
println(" $philosopher picked up $name")
}
fun putDown(philosopher: String) {
lock.unlock()
println(" $philosopher put down $name")
}
}
class Philosopher(val pname: String, val f1: Fork, val f2: Fork) : Thread() {
override fun run() {
(1..20).forEach {
println("$pname is hungry")
f1.pickUp(pname)
f2.pickUp(pname)
println("$pname is eating bite $it")
Thread.sleep(rand.nextInt(300) + 100L)
f2.putDown(pname)
f1.putDown(pname)
}
}
}
fun diningPhilosophers(names: List<String>) {
val size = names.size
val forks = List(size) { Fork("Fork ${it + 1}") }
val philosophers = mutableListOf<Philosopher>()
names.forEachIndexed { i, n ->
var i1 = i
var i2 = (i + 1) % size
if (i2 < i1) {
i1 = i2
i2 = i
}
val p = Philosopher(n, forks[i1], forks[i2])
p.start()
philosophers.add(p)
}
philosophers.forEach { it.join() }
}
fun main(args: Array<String>) {
val names = listOf("Aristotle", "Kant", "Spinoza", "Marx", "Russell")
diningPhilosophers(names)
} |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #JotaCode | JotaCode | @print(
"Today is ",
@let(1,@add(@switch(@time("mon"),
0,-1,
1,30,
2,58,
3,89,
4,119,
5,150,
6,180,
7,211,
8,242,
9,272,
10,303,
11,333)
,@time("mday")),@switch(@print(@time("mon"),"/",@time("mday")),
"1/29","St. Tib's Day",
@print(@switch(@mod("%1",5),
0,"Sweetmorn",
1,"Boomtime",
2,"Pungenday",
3,"Prickle-Prickle",
4,"Setting Orange"),
", ",
@switch(@idiv("%1",73),
0,"Chaos",
1,"Discord",
2,"Confusion",
3,"Bureaucracy",
4,"The Aftermath"),
" ",
@add(@mod("%1",73),1),
", YOLD ",
@add(@time("year"),3066))
)),".") |
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)
| #M2000_Interpreter | M2000 Interpreter |
Module Dijkstra`s_algorithm {
const max_number=1.E+306
GetArr=lambda (n, val)->{
dim d(n)=val
=d()
}
term=("",0)
Edges=(("a", ("b",7),("c",9),("f",14)),("b",("c",10),("d",15)),("c",("d",11),("f",2)),("d",("e",6)),("e",("f", 9)),("f",term))
Document Doc$="Graph:"+{
}
ShowGraph()
Doc$="Paths"+{
}
Print "Paths"
For from_here=0 to 5
pa=GetArr(len(Edges), -1)
d=GetArr(len(Edges), max_number)
Inventory S=1,2,3,4,5,6
return d, from_here:=0
RemoveMin=Lambda S, d, max_number-> {
ss=each(S)
min=max_number
p=0
while ss
val=d#val(eval(S,ss^)-1)
if min>val then let min=val : p=ss^
end while
=s(p!) ' use p as index not key
Delete S, eval(s,p)
}
Show_Distance_and_Path$=lambda$ d, pa, from_here, max_number (n) -> {
ret1$=chr$(from_here+asc("a"))+" to "+chr$(n+asc("a"))
if d#val(n) =max_number then =ret1$+ " No Path" :exit
let ret$="", mm=n, m=n
repeat
n=m
ret$+=chr$(asc("a")+n)
m=pa#val(n)
until from_here=n
=ret1$+format$("{0::-4} {1}",d#val(mm),strrev$(ret$))
}
while len(s)>0
u=RemoveMin()
rem Print u, chr$(u-1+asc("a"))
Relaxed()
end while
For i=0 to len(d)-1
line$=Show_Distance_and_Path$(i)
Print line$
doc$=line$+{
}
next
next
Clipboard Doc$
End
Sub Relaxed()
local vertex=Edges#val(u-1), i
local e=Len(vertex)-1, edge=(,), val
for i=1 to e
edge=vertex#val(i)
if edge#val$(0)<>"" then
val=Asc(edge#val$(0))-Asc("a")
if d#val(val)>edge#val(1)+d#val(u-1) then return d, val:=edge#val(1)+d#val(u-1) : Return Pa, val:=u-1
end if
next
end sub
Sub ShowGraph()
Print "Graph"
local i
for i=1 to len(Edges)
show_edges(i)
next
end sub
Sub show_edges(n)
n--
local vertex=Edges#val(n), line$
local e=each(vertex 2 to end), v2=(,)
While e
v2=array(e)
line$=vertex#val$(0)+if$(v2#val$(0)<>""->"->"+v2#val$(0)+format$(" {0::-2}",v2#val(1)),"")
Print line$
Doc$=line$+{
}
end while
end sub
}
Dijkstra`s_algorithm
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function digitalRoot(n As UInteger, ByRef ap As Integer, base_ As Integer = 10) As Integer
Dim dr As Integer
ap = 0
Do
dr = 0
While n > 0
dr += n Mod base_
n = n \ base_
Wend
ap += 1
n = dr
Loop until dr < base_
Return dr
End Function
Dim As Integer dr, ap
Dim a(3) As UInteger = {627615, 39390, 588225, 393900588225}
For i As Integer = 0 To 3
ap = 0
dr = digitalRoot(a(i), ap)
Print a(i), "Additive Persistence ="; ap, "Digital root ="; dr
Print
Next
Print "Press any key to quit"
Sleep |
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
| #Raku | Raku | sub multiplicative-digital-root(Int $n) {
return .elems - 1, .[.end]
given cache($n, {[*] .comb} ... *.chars == 1)
}
for 123321, 7739, 893, 899998 {
say "$_: ", .&multiplicative-digital-root;
}
for ^10 -> $d {
say "$d : ", .[^5]
given (1..*).grep: *.&multiplicative-digital-root[1] == $d;
} |
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?
| #Lua | Lua | local wrap, yield = coroutine.wrap, coroutine.yield
local function perm(n)
local r = {}
for i=1,n do r[i]=i end
return wrap(function()
local function swap(m)
if m==0 then
yield(r)
else
for i=m,1,-1 do
r[i],r[m]=r[m],r[i]
swap(m-1)
r[i],r[m]=r[m],r[i]
end
end
end
swap(n)
end)
end
local function iden(...)return ... end
local function imap(t,f)
local r,fn = {m=imap, c=table.concat, u=table.unpack}, f or iden
for i=1,#t do r[i]=fn(t[i])end
return r
end
local tenants = {'Baker', 'Cooper', 'Fletcher', 'Miller', 'Smith'}
local conds = {
'Baker ~= TOP',
'Cooper ~= BOTTOM',
'Fletcher ~= TOP and Fletcher~= BOTTOM',
'Miller > Cooper',
'Smith + 1 ~= Fletcher and Smith - 1 ~= Fletcher',
'Cooper + 1 ~= Fletcher and Cooper - 1 ~= Fletcher',
}
local function makePredicate(conds, tenants)
return load('return function('..imap(tenants):c','..
') return ' ..
imap(conds,function(c)
return string.format("(%s)",c)
end):c"and "..
" end ",'-',nil,{TOP=5, BOTTOM=1})()
end
local function solve (conds, tenants)
local try, pred, upk = perm(#tenants), makePredicate(conds, tenants), table.unpack
local answer = try()
while answer and not pred(upk(answer)) do answer = try()end
if answer then
local floor = 0
return imap(answer, function(person)
floor=floor+1;
return string.format(" %s lives on floor %d",tenants[floor],person)
end):c"\n"
else
return nil, 'no solution'
end
end
print(solve (conds, tenants)) |
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | # Built-in
[1, 3, -5]*[4, -2, -1];
# 3 |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot product of two vectors directly:
each vector must be the same length
multiply corresponding terms from each vector
sum the products (to produce the answer)
Related task
Vector products
| #GAP | GAP | # Built-in
[1, 3, -5]*[4, -2, -1];
# 3 |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Frink | Frink | squeeze[str, ch] :=
{
println["Use: '$ch'"]
println["old: " + length[str] + " <<<$str>>>"]
str =~ subst["($ch)\\1+", "$$1", "g"]
println["new: " + length[str] + " <<<$str>>>"]
}
lines = [["", [""]],
[""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, ["-"]],
["..1111111111111111111111111111111111111111111111111111111111111117777888", ["7"]],
["I never give 'em hell, I just tell the truth, and they think it's hell. ", ["."]],
[" --- Harry S Truman ",[" ", "-", "r"]]]
for [line, chars] = lines
for char = chars
println[squeeze[line, char]] |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import "fmt"
// Returns squeezed string, original and new lengths in
// unicode code points (not normalized).
func squeeze(s string, c rune) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == c && r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings := []string{
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
chars := [][]rune{{' '}, {'-'}, {'7'}, {'.'}, {' ', '-', 'r'}, {'e'}, {'s'}, {'a'}, {'😍'}}
for i, s := range strings {
for _, c := range chars[i] {
ss, olen, slen := squeeze(s, c)
fmt.Printf("specified character = %q\n", c)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("squeezed : length = %2d, string = «««%s»»»\n\n", slen, ss)
}
}
} |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Go | Go | package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087,
}
var dys = []float64{
0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032,
}
func funnel(fa []float64, r rule) []float64 {
x := 0.0
result := make([]float64, len(fa))
for i, f := range fa {
result[i] = x + f
x = r(x, f)
}
return result
}
func mean(fa []float64) float64 {
sum := 0.0
for _, f := range fa {
sum += f
}
return sum / float64(len(fa))
}
func stdDev(fa []float64) float64 {
m := mean(fa)
sum := 0.0
for _, f := range fa {
sum += (f - m) * (f - m)
}
return math.Sqrt(sum / float64(len(fa)))
}
func experiment(label string, r rule) {
rxs := funnel(dxs, r)
rys := funnel(dys, r)
fmt.Println(label, " : x y")
fmt.Printf("Mean : %7.4f, %7.4f\n", mean(rxs), mean(rys))
fmt.Printf("Std Dev : %7.4f, %7.4f\n", stdDev(rxs), stdDev(rys))
fmt.Println()
}
func main() {
experiment("Rule 1", func(_, _ float64) float64 {
return 0.0
})
experiment("Rule 2", func(_, dz float64) float64 {
return -dz
})
experiment("Rule 3", func(z, dz float64) float64 {
return -(z + dz)
})
experiment("Rule 4", func(z, dz float64) float64 {
return z + dz
})
} |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #8086_Assembly | 8086 Assembly | cpu 8086
bits 16
org 100h
section .text
mov di,obuf ; Output buffer
mov bl,2 ; BL = police
pol: mov cl,1 ; CL = sanitation
san: mov dl,1 ; DL = fire
fire: cmp bl,cl ; Police equal to sanitation?
je next ; Invalid combination
cmp bl,dl ; Police equal to fire?
je next ; Invalid combination
cmp cl,dl ; Sanitation equal to fire?
je next ; Invalid combination
mov al,bl ; Total equal to 12?
add al,cl
add al,dl
cmp al,12
jne next ; If not, invalid combination
mov al,bl ; Combination is valid, write the three numbers
call num
mov al,cl
call num
mov al,dl
call num
mov ax,0A0Dh ; And a newline
stosw
next: mov al,7 ; Load 7 to compare to
inc dx ; Increment fire number
cmp al,dl ; If 7 or less,
jae fire ; next fire number.
inc cx ; Otherwise, ncrement sanitation number
cmp al,cl ; If 7 or less,
jae san ; next sanitation number
inc bx ; Increment police number twice
inc bx ; (it must be even)
cmp al,bl ; If 7 or less,
jae pol ; next police number.
mov byte [di],'$' ; At the end, terminate the string
mov dx,ohdr ; Tell MS-DOS to print it
mov ah,9
int 21h
ret
num: mov ah,' ' ; Space
add al,'0' ; Add number to output
stosw ; Store number and space
ret
section .data
ohdr: db 'P S F',13,10 ; Header
obuf: equ $ ; Place to write output |
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
| #Picat | Picat | import util.
main =>
DP = [N : S in power_set("987654321"), S != [], N = S.to_int, prime(N)].sort,
foreach({P,I} in zip(DP,1..DP.len))
printf("%9d%s",P,cond(I mod 10 == 0,"\n",""))
end,
nl,
println(len=DP.len). |
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
| #Python | Python | from sympy import isprime
def descending(xs=range(10)):
for x in xs:
yield x
yield from descending(x*10 + d for d in range(x%10))
for i, p in enumerate(sorted(filter(isprime, descending()))):
print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')
print() |
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
| #Raku | Raku | put (flat 2, 3, 5, 7, sort +*, gather (3..9).map: &recurse ).batch(10)».fmt("%8d").join: "\n";
sub recurse ($str) {
.take for ($str X~ (1, 3, 7)).grep: { .is-prime && [>] .comb };
recurse $str × 10 + $_ for 2 ..^ $str % 10;
} |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Aikido | Aikido |
class Delegator {
public generic delegate = none
public function operation {
if (typeof(delegate) == "none") {
return "default implementation"
}
return delegate()
}
}
function thing {
return "delegate implementation"
}
// default, no delegate
var d = new Delegator()
println (d.operation())
// delegate
var d1 = new Delegator()
d1.delegate = thing
println (d1.operation())
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Aime | Aime | text
thing(void)
{
return "delegate implementation";
}
text
operation(record delegator)
{
text s;
if (r_key(delegator, "delegate")) {
if (r_key(delegator["delegate"], "thing")) {
s = call(r_query(delegator["delegate"], "thing"));
} else {
s = "default implementation";
}
} else {
s = "default implementation";
}
return s;
}
integer
main(void)
{
record delegate, delegator;
o_text(operation(delegator));
o_byte('\n');
r_link(delegator, "delegate", delegate);
o_text(operation(delegator));
o_byte('\n');
r_put(delegate, "thing", thing);
o_text(operation(delegator));
o_byte('\n');
return 0;
} |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #ALGOL_68 | ALGOL 68 | # An Algol 68 approximation of delegates #
# The delegate mode - the delegate is a STRUCT with a single field #
# that is a REF PROC STRING. If this is NIL, it doesn't implement #
# thing #
MODE DELEGATE = STRUCT( REF PROC STRING thing );
# A delegator mode that will invoke the delegate's thing method #
# - if there is a delegate and the delegate has a thing method #
MODE DELEGATOR = STRUCT( REF DELEGATE delegate
, PROC( REF DELEGATE )STRING thing
);
# constructs a new DELEGATE with the specified PROC as its thing #
# Algol 68 HEAP is like "new" in e.g. Java, but it can't take #
# parameters, so this PROC does the equivalent #
PROC new delegate = ( REF PROC STRING thing )REF DELEGATE:
BEGIN
REF DELEGATE result = HEAP DELEGATE;
thing OF result := thing;
result
END # new delegate #
;
# constructs a new DELEGATOR with the specified DELEGATE #
PROC new delegator = ( REF DELEGATE delegate )REF DELEGATOR:
HEAP DELEGATOR := ( delegate
, # anonymous PROC to invoke the delegate's thing #
( REF DELEGATE delegate )STRING:
IF delegate IS REF DELEGATE(NIL)
THEN
# we have no delegate #
"default implementation"
ELIF thing OF delegate IS REF PROC STRING(NIL)
THEN
# the delegate doesn't have an implementation #
"default implementation"
ELSE
# the delegate can thing #
thing OF delegate
FI
)
;
# invokes the delegate's thing via the delagator #
# Because the PROCs of a STRUCT don't have an equivalent of e.g. Java's #
# "this", we have to explicitly pass the delegate as a parameter #
PROC invoke thing = ( REF DELEGATOR delegator )STRING:
# the following is Algol 68 for what would be written in Java as #
# "delegator.thing( delegator.delegate )" #
( thing OF delegator )( delegate OF delegator )
;
main:
(
print( ( "No delegate : "
, invoke thing( new delegator( NIL ) )
, newline
, "Delegate with no thing: "
, invoke thing( new delegator( new delegate( NIL ) ) )
, newline
, "Delegate with a thing : "
, invoke thing( new delegator( new delegate( HEAP PROC STRING := STRING: ( "delegate implementation" ) ) ) )
, newline
)
)
)
|
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #Delphi | Delphi | open System
type Point = double * double
type Triangle = Point * Point * Point
let Det2D (t:Triangle) =
let (p1, p2, p3) = t
let (p1x, p1y) = p1
let (p2x, p2y) = p2
let (p3x, p3y) = p3
p1x * (p2y - p3y) +
p2x * (p3y - p1y) +
p3x * (p1y - p2y)
let CheckTriWinding allowReversed t =
let detTri = Det2D t
if detTri < 0.0 then
if allowReversed then
let (p1, p2, p3) = t
(p1, p3, p2)
else
raise (Exception "Triangle has wrong winding direction")
else
t
let boundaryCollideChk eps t =
(Det2D t) < eps
let boundaryDoesntCollideChk eps t =
(Det2D t) <= eps
let TriTri2D eps allowReversed onBoundary t1 t2 =
// Triangles must be expressed anti-clockwise
let t3 = CheckTriWinding allowReversed t1
let t4 = CheckTriWinding allowReversed t2
// 'onBoundary' determines whether points on boundary are considered as colliding or not
let chkEdge = if onBoundary then boundaryCollideChk else boundaryDoesntCollideChk
let (t1p1, t1p2, t1p3) = t3
let (t2p1, t2p2, t2p3) = t4
// Check all points of t2 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge eps (t1p1, t1p2, t2p1)) && (chkEdge eps (t1p1, t1p2, t2p2)) && (chkEdge eps (t1p1, t1p2, t2p3)) then
false
else if (chkEdge eps (t1p2, t1p3, t2p1)) && (chkEdge eps (t1p2, t1p3, t2p2)) && (chkEdge eps (t1p2, t1p3, t2p3)) then
false
else if (chkEdge eps (t1p3, t1p1, t2p1)) && (chkEdge eps (t1p3, t1p1, t2p2)) && (chkEdge eps (t1p3, t1p1, t2p3)) then
false
// Check all points of t1 lay on the external side of edge E.
// If they do, the triangles do not overlap.
else if (chkEdge eps (t2p1, t2p2, t1p1)) && (chkEdge eps (t2p1, t2p2, t1p2)) && (chkEdge eps (t2p1, t2p2, t1p3)) then
false
else if (chkEdge eps (t2p2, t2p3, t1p1)) && (chkEdge eps (t2p2, t2p3, t1p2)) && (chkEdge eps (t2p2, t2p3, t1p3)) then
false
else if (chkEdge eps (t2p3, t2p1, t1p1)) && (chkEdge eps (t2p3, t2p1, t1p2)) && (chkEdge eps (t2p3, t2p1, t1p3)) then
false
else
// The triangles overlap
true
let Print t1 t2 =
Console.WriteLine("{0} and\n{1}\n{2}\n", t1, t2, if TriTri2D 0.0 false true t1 t2 then "overlap" else "do not overlap")
[<EntryPoint>]
let main _ =
let t1 = ((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
let t2 = ((0.0, 0.0), (5.0, 0.0), (0.0, 6.0))
Print t1 t2
let t3 = ((0.0, 0.0), (0.0, 5.0), (5.0, 0.0))
Console.WriteLine("{0} and\n{1}\n{2}\n", t3, t3, if TriTri2D 0.0 true true t3 t3 then "overlap (reversed)" else "do not overlap")
let t4 = ((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
let t5 = ((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0))
Print t4 t5
let t6 = ((0.0, 0.0), (5.0, 0.0), (2.5, 5.0))
let t7 = ((0.0, 4.0), (2.5, -1.0), (5.0, 4.0))
Print t6 t7
let t8 = ((0.0, 0.0), (1.0, 1.0), (0.0, 2.0))
let t9 = ((2.0, 1.0), (3.0, 0.0), (3.0, 2.0))
Print t8 t9
let t10 = ((2.0, 1.0), (3.0, -2.0), (3.0, 4.0))
Print t8 t10
let t11 = ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))
let t12 = ((1.0, 0.0), (2.0, 0.0), (1.0, 1.1))
printfn "The following triangles which have only a single corner in contact, if boundary points collide"
Print t11 t12
Console.WriteLine("{0} and\n{1}\nwhich have only a single corner in contact, if boundary points do not collide\n{2}", t11, t12, if TriTri2D 0.0 false false t11 t12 then "overlap" else "do not overlap")
0 // return an integer exit code |
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.
| #Aikido | Aikido |
remove ("input.txt")
remove ("/input.txt")
remove ("docs")
remove ("/docs")
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Aime | Aime | remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs"); |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #Factor | Factor | USING: fry kernel math.combinatorics math.matrices sequences ;
: permanent ( matrix -- x )
dup square-matrix? [ "Matrix must be square." throw ] unless
[ dim first <iota> ] keep
'[ [ _ nth nth ] map-index product ] map-permutations sum ; |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #Forth | Forth | S" fsl-util.fs" REQUIRED
S" fsl/dynmem.seq" REQUIRED
[UNDEFINED] defines [IF] SYNONYM defines IS [THEN]
S" fsl/structs.seq" REQUIRED
S" fsl/lufact.seq" REQUIRED
S" fsl/dets.seq" REQUIRED
S" permute.fs" REQUIRED
VARIABLE the-mat
: add-perm ( p0 p1 p2 ... pn n s -- )
DROP \ sign
1E
1 DO
the-mat @ SWAP 1- I 1- }} F@ F*
LOOP
DROP \ Dummy element because we're using 1-based indexing
F+ ;
: permanent ( len mat -- ) ( F: -- perm )
the-mat !
0E
['] add-perm perms ;
3 SET-PRECISION
2 2 float matrix m2{{
1e 2e 3e 4e 2 2 m2{{ }}fput
lumatrix lmat
3 3 float matrix m3{{
2e 9e 4e 7e 5e 3e 6e 1e 8e 3 3 m3{{ }}fput
lmat 2 lu-malloc
m2{{ lmat lufact
lmat det F. 2 m2{{ permanent F. CR
lmat lu-free
lmat 3 lu-malloc
m3{{ lmat lufact
lmat det F. 3 m3{{ permanent F. CR
lmat lu-free |
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.
| #C.23 | C# | using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
int x = 1;
int y = 0;
try {
int z = x / y;
} catch (DivideByZeroException e) {
Console.WriteLine(e);
}
}
}
} |
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.
| #C.2B.2B | C++ |
#include<iostream>
#include<csignal> /* for signal */
#include<cstdlib>
using namespace std;
void fpe_handler(int signal)
{
cerr << "Floating Point Exception: division by zero" << endl;
exit(signal);
}
int main()
{
// Register floating-point exception handler.
signal(SIGFPE, fpe_handler);
int a = 1;
int b = 0;
cout << a/b << endl;
return 0;
}
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BaCon | BaCon | INPUT "Your string: ", s$
IF REGEX(s$, "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$") THEN
PRINT "This is a number"
ELSE
PRINT "Not a number"
ENDIF |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BASIC | BASIC | 10 INPUT "Enter a string";S$:GOSUB 1000
20 IF R THEN PRINT "Is num" ELSE PRINT"Not num"
99 END
1000 T1=VAL(S$):T1$=STR$(T1)
1010 R=T1$=S$ OR T1$=" "+S$
1099 RETURN |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Clojure | Clojure |
(defn uniq-char-string [s]
(let [len (count s)]
(if (= len (count (set s)))
(println (format "All %d chars unique in: '%s'" len s))
(loop [prev-chars #{}
idx 0
chars (vec s)]
(let [c (first chars)]
(if (contains? prev-chars c)
(println (format "'%s' (len: %d) has '%c' duplicated at idx: %d"
s len c idx))
(recur (conj prev-chars c)
(inc idx)
(rest chars))))))))
|
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Frink | Frink | collapse[str] := str =~ %s/(.)\1+/$1/g
lines = ["",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman "]
for line = lines
println[collapse[line]] |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import "fmt"
// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
func collapse(s string) (string, int, int) {
r := []rune(s)
le, del := len(r), 0
for i := le - 2; i >= 0; i-- {
if r[i] == r[i+1] {
copy(r[i:], r[i+1:])
del++
}
}
if del == 0 {
return s, le, le
}
r = r[:le-del]
return string(r), le, len(r)
}
func main() {
strings:= []string {
"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"😍😀🙌💃😍😍😍🙌",
}
for _, s := range strings {
cs, olen, clen := collapse(s)
fmt.Printf("original : length = %2d, string = «««%s»»»\n", olen, s)
fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Erlang | Erlang |
-module(string_examples).
-export([examine_all_same/1, all_same_examples/0]).
all_same_characters([], _Offset) ->
all_same;
all_same_characters([_], _Offset) ->
all_same;
all_same_characters([X, X | Rest], Offset) ->
all_same_characters([X | Rest], Offset + 1);
all_same_characters([X, Y | _Rest], Offset) when X =/= Y ->
{not_all_same, Y, Offset + 1}.
examine_all_same(String) ->
io:format("String \"~ts\" of length ~p:~n", [String, length(String)]),
case all_same_characters(String, 0) of
all_same ->
io:format(" All characters are the same.~n~n");
{not_all_same, OffendingChar, Offset} ->
io:format(" Not all characters are the same.~n"),
io:format(" Char '~tc' (0x~.16b) at offset ~p differs.~n~n",
[OffendingChar, OffendingChar, Offset])
end.
all_same_examples() ->
Strings = ["",
" ",
"2",
"333",
".55",
"tttTTT",
"4444 444k",
"pépé",
"🐶🐶🐺🐶",
"🎄🎄🎄🎄"],
lists:foreach(fun examine_all_same/1, Strings).
|
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.
| #Logtalk | Logtalk | :- category(chopstick).
% chopstick actions (picking up and putting down) are synchronized using a notification
% such that a chopstick can only be handled by a single philosopher at a time:
:- public(pick_up/0).
pick_up :-
threaded_wait(available).
:- public(put_down/0).
put_down :-
threaded_notify(available).
:- end_category.
:- object(cs1,
imports(chopstick)).
:- threaded.
:- initialization(threaded_notify(available)).
:- end_object.
:- object(cs2,
imports(chopstick)).
:- threaded.
:- initialization(threaded_notify(available)).
:- end_object.
:- object(cs3,
imports(chopstick)).
:- threaded.
:- initialization(threaded_notify(available)).
:- end_object.
:- object(cs4,
imports(chopstick)).
:- threaded.
:- initialization(threaded_notify(available)).
:- end_object.
:- object(cs5,
imports(chopstick)).
:- threaded.
:- initialization(threaded_notify(available)).
:- end_object.
:- category(philosopher).
:- public(left_chopstick/1).
:- public(right_chopstick/1).
:- public(run/2).
:- private(message/1).
:- synchronized(message/1).
:- uses(random, [random/3]).
run(0, _) :-
this(Philosopher),
message([Philosopher, ' terminated.']).
run(Count, MaxTime) :-
Count > 0,
think(MaxTime),
eat(MaxTime),
Count2 is Count - 1,
run(Count2, MaxTime).
think(MaxTime):-
this(Philosopher),
random(1, MaxTime, ThinkTime),
message(['Philosopher ', Philosopher, ' thinking for ', ThinkTime, ' seconds.']),
thread_sleep(ThinkTime).
eat(MaxTime):-
this(Philosopher),
random(1, MaxTime, EatTime),
::left_chopstick(LeftStick),
::right_chopstick(RightStick),
LeftStick::pick_up,
RightStick::pick_up,
message(['Philosopher ', Philosopher, ' eating for ', EatTime, ' seconds with chopsticks ', LeftStick, ' and ', RightStick, '.']),
thread_sleep(EatTime),
::LeftStick::put_down,
::RightStick::put_down.
% writing a message needs to be synchronized as it's accomplished
% using a combination of individual write/1 and nl/0 calls:
message([]) :-
nl,
flush_output.
message([Atom| Atoms]) :-
write(Atom),
message(Atoms).
:- end_category.
:- object(aristotle,
imports(philosopher)).
left_chopstick(cs1).
right_chopstick(cs2).
:- end_object.
:- object(kant,
imports(philosopher)).
left_chopstick(cs2).
right_chopstick(cs3).
:- end_object.
:- object(spinoza,
imports(philosopher)).
left_chopstick(cs3).
right_chopstick(cs4).
:- end_object.
:- object(marx,
imports(philosopher)).
left_chopstick(cs4).
right_chopstick(cs5).
:- end_object.
:- object(russell,
imports(philosopher)).
left_chopstick(cs1). % change order so that the chopsticks are picked
right_chopstick(cs5). % in different order from the other philosophers
:- end_object. |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Julia | Julia | using Dates
function discordiandate(year::Integer, month::Integer, day::Integer)
discordianseasons = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
holidays = Dict(
"Chaos 5" => "Mungday",
"Chaos 50" => "Chaoflux",
"Discord 5" => "Mojoday",
"Discord 50" => "Discoflux",
"Confusion 5" => "Syaday",
"Confusion 50" => "Confuflux",
"Bureaucracy 5" => "Zaraday",
"Bureaucracy 50" => "Bureflux",
"The Aftermath 5" => "Maladay",
"The Aftermath 50" => "Afflux")
today = Date(year, month, day)
isleap = isleapyear(year)
if isleap && month == 2 && day == 29
rst = "St. Tib's Day, YOLD " * string(year + 1166)
else
dy = dayofyear(today)
if isleap && dy >= 60
dy -= 1
end
rst = string(discordianseasons[div(dy, 73) + 1], " ", rem(dy, 73)) # day
if haskey(holidays, rst)
rst *= " ($(holidays[rst]))" # if holiday
end
rst *= ", YOLD $(year + 1166)" # year
end
return rst
end
@show discordiandate(2017, 08, 15)
@show discordiandate(1996, 02, 29)
@show discordiandate(1996, 02, 19) |
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)
| #Maple | Maple | restart:
with(GraphTheory):
G:=Digraph([a,b,c,d,e,f],{[[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]}):
DijkstrasAlgorithm(G,a);
# [[[a], 0], [[a, b], 7], [[a, c], 9], [[a, c, d], 20], [[a, c, d, e], 26], [[a, c, f], 11]] |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displaystyle X}
has only one digit.
The additive persistence is the number of summations required to obtain the single digit.
The task is to calculate the additive persistence and the digital root of a number, e.g.:
627615
{\displaystyle 627615}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
39390
{\displaystyle 39390}
has additive persistence
2
{\displaystyle 2}
and digital root of
6
{\displaystyle 6}
;
588225
{\displaystyle 588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
3
{\displaystyle 3}
;
393900588225
{\displaystyle 393900588225}
has additive persistence
2
{\displaystyle 2}
and digital root of
9
{\displaystyle 9}
;
The digital root may be calculated in bases other than 10.
See
Casting out nines for this wiki's use of this procedure.
Digital root/Multiplicative digital root
Sum digits of an integer
Digital root sequence on OEIS
Additive persistence sequence on OEIS
Iterated digits squaring
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"log"
"strconv"
)
func Sum(i uint64, base int) (sum int) {
b64 := uint64(base)
for ; i > 0; i /= b64 {
sum += int(i % b64)
}
return
}
func DigitalRoot(n uint64, base int) (persistence, root int) {
root = int(n)
for x := n; x >= uint64(base); x = uint64(root) {
root = Sum(x, base)
persistence++
}
return
}
// Normally the below would be moved to a *_test.go file and
// use the testing package to be runnable as a regular test.
var testCases = []struct {
n string
base int
persistence int
root int
}{
{"627615", 10, 2, 9},
{"39390", 10, 2, 6},
{"588225", 10, 2, 3},
{"393900588225", 10, 2, 9},
{"1", 10, 0, 1},
{"11", 10, 1, 2},
{"e", 16, 0, 0xe},
{"87", 16, 1, 0xf},
// From Applesoft BASIC example:
{"DigitalRoot", 30, 2, 26}, // 26 is Q base 30
// From C++ example:
{"448944221089", 10, 3, 1},
{"7e0", 16, 2, 0x6},
{"14e344", 16, 2, 0xf},
{"d60141", 16, 2, 0xa},
{"12343210", 16, 2, 0x1},
// From the D example:
{"1101122201121110011000000", 3, 3, 1},
}
func main() {
for _, tc := range testCases {
n, err := strconv.ParseUint(tc.n, tc.base, 64)
if err != nil {
log.Fatal(err)
}
p, r := DigitalRoot(n, tc.base)
fmt.Printf("%12v (base %2d) has additive persistence %d and digital root %s\n",
tc.n, tc.base, p, strconv.FormatInt(int64(r), tc.base))
if p != tc.persistence || r != tc.root {
log.Fatalln("bad result:", tc, p, r)
}
}
} |
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
| #Red | Red | Red ["Multiplicative digital root"]
mdr: function [
"Returns a block containing the mdr and persistence of an integer"
n [integer!]
][
persistence: 0
while [n > 10][
product: 1
m: n
while [m > 0][
product: m % 10 * product
m: to-integer m / 10
]
persistence: persistence + 1
n: product
]
reduce [n persistence]
]
foreach n [123321 7739 893 899998][
result: mdr n
print [pad n 6 "has multiplicative persistence" result/2 "and MDR" result/1]
]
print [newline "First five numbers with MDR of"]
repeat i 10 [
prin rejoin [i - 1 ": "]
hits: n: 0
while [hits < 5][
if i - 1 = first mdr n [
prin pad n 5
hits: hits + 1
]
n: n + 1
]
prin newline
] |
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?
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
{Baker, Cooper, Fletcher, Miller, Smith};
(Unequal @@ %) && (And @@ (0 < # < 6 & /@ %)) &&
Baker < 5 &&
Cooper > 1 &&
1 < Fletcher < 5 &&
Miller > Cooper &&
Abs[Smith - Fletcher] > 1 &&
Abs[Cooper - Fletcher] > 1 //
Reduce[#, %, Integers] &
|
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
| #GLSL | GLSL |
float dot_product = dot(vec3(1, 3, -5), vec3(4, -2, -1));
|
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Groovy | Groovy | class StringSqueezable {
static void main(String[] args) {
String[] testStrings = [
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"
]
String[] testChar = [" ", "-", "7", ".", " -r", "5", "e", "s"]
for (int testNum = 0; testNum < testStrings.length; testNum++) {
String s = testStrings[testNum]
for (char c : testChar[testNum].toCharArray()) {
String result = squeeze(s, c)
System.out.printf("use: '%c'%nold: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", c, s.length(), s, result.length(), result)
}
}
}
private static String squeeze(String input, char include) {
StringBuilder sb = new StringBuilder()
for (int i = 0; i < input.length(); i++) {
if (i == 0 || input.charAt(i - 1) != input.charAt(i) || (input.charAt(i - 1) == input.charAt(i) && input.charAt(i) != include)) {
sb.append(input.charAt(i))
}
}
return sb.toString()
}
} |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #Haskell | Haskell | import Data.List (mapAccumL, genericLength)
import Text.Printf
funnel :: (Num a) => (a -> a -> a) -> [a] -> [a]
funnel rule = snd . mapAccumL (\x dx -> (rule x dx, x + dx)) 0
mean :: (Fractional a) => [a] -> a
mean xs = sum xs / genericLength xs
stddev :: (Floating a) => [a] -> a
stddev xs = sqrt $ sum [(x-m)**2 | x <- xs] / genericLength xs where
m = mean xs
experiment :: String -> [Double] -> [Double] -> (Double -> Double -> Double) -> IO ()
experiment label dxs dys rule = do
let rxs = funnel rule dxs
rys = funnel rule dys
putStrLn label
printf "Mean x, y : %7.4f, %7.4f\n" (mean rxs) (mean rys)
printf "Std dev x, y : %7.4f, %7.4f\n" (stddev rxs) (stddev rys)
putStrLn ""
dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,
-0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,
0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,
-0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,
0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,
-1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,
0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,
0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,
0.443, -0.521, -0.799, 0.087]
dys = [ 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,
0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,
0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,
0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,
-0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,
0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,
0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,
1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,
-0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,
0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,
-0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,
1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,
-0.947, -1.424, -0.542, -1.032]
main :: IO ()
main = do
experiment "Rule 1:" dxs dys (\_ _ -> 0)
experiment "Rule 2:" dxs dys (\_ dz -> -dz)
experiment "Rule 3:" dxs dys (\z dz -> -(z+dz))
experiment "Rule 4:" dxs dys (\z dz -> z+dz) |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Action.21 | Action! | PROC Main()
BYTE p,s,f
PrintE("P S F")
FOR p=2 TO 6 STEP 2
DO
FOR s=1 TO 7
DO
FOR f=1 TO 7
DO
IF p#s AND p#f AND s#f AND p+s+f=12 THEN
PrintF("%B %B %B%E",p,s,f)
FI
OD
OD
OD
RETURN |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Ada | Ada | with Ada.Text_IO;
procedure Department_Numbers is
use Ada.Text_IO;
begin
Put_Line (" P S F");
for Police in 2 .. 6 loop
for Sanitation in 1 .. 7 loop
for Fire in 1 .. 7 loop
if
Police mod 2 = 0 and
Police + Sanitation + Fire = 12 and
Sanitation /= Police and
Sanitation /= Fire and
Police /= Fire
then
Put_Line (Police'Image & Sanitation'Image & Fire'Image);
end if;
end loop;
end loop;
end loop;
end Department_Numbers; |
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
| #Ring | Ring |
load "stdlibcore.ring"
limit = 1000
row = 0
for n = 1 to limit
flag = 0
strn = string(n)
if isprime(n) = 1
for m = 1 to len(strn)-1
if number(substr(strn,m)) < number(substr(strn,m+1))
flag = 1
ok
next
if flag = 1
row++
see "" + n + " "
ok
if row % 10 = 0
see nl
ok
ok
next
|
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
| #Sidef | Sidef | func primes_with_descending_digits(base = 10) {
var list = []
var digits = @(1..^base)
var end_digits = digits.grep { .is_coprime(base) }
list << digits.grep { .is_prime && !.is_coprime(base) }...
for k in (0 .. digits.end) {
digits.combinations(k, {|*a|
var v = a.digits2num(base)
end_digits.each {|d|
var n = (v*base + d)
next if ((n >= base) && (a[0] <= d))
list << n if n.is_prime
}
})
}
list.sort
}
var base = 10
var arr = primes_with_descending_digits(base)
say "There are #{arr.len} descending primes in base #{base}.\n"
arr.each_slice(8, {|*a|
say a.map { '%9s' % _ }.join(' ')
}) |
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
| #Wren | Wren | import "./perm" for Powerset
import "./math" for Int
import "./seq" for Lst
import "./fmt" for Fmt
var ps = Powerset.list((9..1).toList)
var descPrimes = ps.skip(1).map { |s| Num.fromString(s.join()) }
.where { |p| Int.isPrime(p) }
.toList
.sort()
System.print("There are %(descPrimes.count) descending primes, namely:")
for (chunk in Lst.chunks(descPrimes, 10)) Fmt.print("$8s", chunk) |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #Atari_Basic | Atari Basic |
10 REM DELEGATION CODE AND EXAMPLE . ATARI BASIC 2020 A. KRESS [email protected]
14 REM
15 GOTO 100:REM MAINLOOP
16 REM
20 REM DELEGATOR OBJECT
21 REM
30 IF DELEGATE THEN GOSUB DELEGATE:GOTO 56
35 REM
50 REM DELEGATOR HAS TO DO THE JOB
55 PRINT "DEFAULT IMPLEMENTATION - DONE BY DELEGATOR"
56 RETURN
60 REM CALL DELEGATE
65 GOSUB DELEGATOR
66 RETURN
79 REM
80 REM DELEGATE OBJECT
81 REM
90 PRINT "DELEGATE IMPLEMENTATION - DONE BY DELEGATE"
91 RETURN
99 REM
100 REM MAINLOOP - DELEGATION EXAMPLE
101 REM
110 DELEGATE=0:REM NO DELEGATE
120 GOSUB 20:REM INIT DELEGATOR
130 DELEGATE=80:REM DELEGATE IS
140 GOSUB 20:REM INIT DELEGATOR
|
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef const char * (*Responder)( int p1);
typedef struct sDelegate {
Responder operation;
} *Delegate;
/* Delegate class constructor */
Delegate NewDelegate( Responder rspndr )
{
Delegate dl = malloc(sizeof(struct sDelegate));
dl->operation = rspndr;
return dl;
}
/* Thing method of Delegate */
const char *DelegateThing(Delegate dl, int p1)
{
return (dl->operation)? (*dl->operation)(p1) : NULL;
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
typedef struct sDelegator {
int param;
char *phrase;
Delegate delegate;
} *Delegator;
const char * defaultResponse( int p1)
{
return "default implementation";
}
static struct sDelegate defaultDel = { &defaultResponse };
/* Delegator class constructor */
Delegator NewDelegator( int p, char *phrase)
{
Delegator d = malloc(sizeof(struct sDelegator));
d->param = p;
d->phrase = phrase;
d->delegate = &defaultDel; /* default delegate */
return d;
}
/* Operation method of Delegator */
const char *Delegator_Operation( Delegator theDelegator, int p1, Delegate delroy)
{
const char *rtn;
if (delroy) {
rtn = DelegateThing(delroy, p1);
if (!rtn) { /* delegate didn't handle 'thing' */
rtn = DelegateThing(theDelegator->delegate, p1);
}
}
else /* no delegate */
rtn = DelegateThing(theDelegator->delegate, p1);
printf("%s\n", theDelegator->phrase );
return rtn;
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
const char *thing1( int p1)
{
printf("We're in thing1 with value %d\n" , p1);
return "delegate implementation";
}
int main()
{
Delegate del1 = NewDelegate(&thing1);
Delegate del2 = NewDelegate(NULL);
Delegator theDelegator = NewDelegator( 14, "A stellar vista, Baby.");
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, NULL));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del1));
printf("Delegator returns %s\n\n",
Delegator_Operation( theDelegator, 3, del2));
return 0;
} |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #F.23 | F# | open System
type Point = double * double
type Triangle = Point * Point * Point
let Det2D (t:Triangle) =
let (p1, p2, p3) = t
let (p1x, p1y) = p1
let (p2x, p2y) = p2
let (p3x, p3y) = p3
p1x * (p2y - p3y) +
p2x * (p3y - p1y) +
p3x * (p1y - p2y)
let CheckTriWinding allowReversed t =
let detTri = Det2D t
if detTri < 0.0 then
if allowReversed then
let (p1, p2, p3) = t
(p1, p3, p2)
else
raise (Exception "Triangle has wrong winding direction")
else
t
let boundaryCollideChk eps t =
(Det2D t) < eps
let boundaryDoesntCollideChk eps t =
(Det2D t) <= eps
let TriTri2D eps allowReversed onBoundary t1 t2 =
// Triangles must be expressed anti-clockwise
let t3 = CheckTriWinding allowReversed t1
let t4 = CheckTriWinding allowReversed t2
// 'onBoundary' determines whether points on boundary are considered as colliding or not
let chkEdge = if onBoundary then boundaryCollideChk else boundaryDoesntCollideChk
let (t1p1, t1p2, t1p3) = t3
let (t2p1, t2p2, t2p3) = t4
// Check all points of t2 lay on the external side of edge E.
// If they do, the triangles do not overlap.
if (chkEdge eps (t1p1, t1p2, t2p1)) && (chkEdge eps (t1p1, t1p2, t2p2)) && (chkEdge eps (t1p1, t1p2, t2p3)) then
false
else if (chkEdge eps (t1p2, t1p3, t2p1)) && (chkEdge eps (t1p2, t1p3, t2p2)) && (chkEdge eps (t1p2, t1p3, t2p3)) then
false
else if (chkEdge eps (t1p3, t1p1, t2p1)) && (chkEdge eps (t1p3, t1p1, t2p2)) && (chkEdge eps (t1p3, t1p1, t2p3)) then
false
// Check all points of t1 lay on the external side of edge E.
// If they do, the triangles do not overlap.
else if (chkEdge eps (t2p1, t2p2, t1p1)) && (chkEdge eps (t2p1, t2p2, t1p2)) && (chkEdge eps (t2p1, t2p2, t1p3)) then
false
else if (chkEdge eps (t2p2, t2p3, t1p1)) && (chkEdge eps (t2p2, t2p3, t1p2)) && (chkEdge eps (t2p2, t2p3, t1p3)) then
false
else if (chkEdge eps (t2p3, t2p1, t1p1)) && (chkEdge eps (t2p3, t2p1, t1p2)) && (chkEdge eps (t2p3, t2p1, t1p3)) then
false
else
// The triangles overlap
true
let Print t1 t2 =
Console.WriteLine("{0} and\n{1}\n{2}\n", t1, t2, if TriTri2D 0.0 false true t1 t2 then "overlap" else "do not overlap")
[<EntryPoint>]
let main _ =
let t1 = ((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
let t2 = ((0.0, 0.0), (5.0, 0.0), (0.0, 6.0))
Print t1 t2
let t3 = ((0.0, 0.0), (0.0, 5.0), (5.0, 0.0))
Console.WriteLine("{0} and\n{1}\n{2}\n", t3, t3, if TriTri2D 0.0 true true t3 t3 then "overlap (reversed)" else "do not overlap")
let t4 = ((0.0, 0.0), (5.0, 0.0), (0.0, 5.0))
let t5 = ((-10.0, 0.0), (-5.0, 0.0), (-1.0, 6.0))
Print t4 t5
let t6 = ((0.0, 0.0), (5.0, 0.0), (2.5, 5.0))
let t7 = ((0.0, 4.0), (2.5, -1.0), (5.0, 4.0))
Print t6 t7
let t8 = ((0.0, 0.0), (1.0, 1.0), (0.0, 2.0))
let t9 = ((2.0, 1.0), (3.0, 0.0), (3.0, 2.0))
Print t8 t9
let t10 = ((2.0, 1.0), (3.0, -2.0), (3.0, 4.0))
Print t8 t10
let t11 = ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0))
let t12 = ((1.0, 0.0), (2.0, 0.0), (1.0, 1.1))
printfn "The following triangles which have only a single corner in contact, if boundary points collide"
Print t11 t12
Console.WriteLine("{0} and\n{1}\nwhich have only a single corner in contact, if boundary points do not collide\n{2}", t11, t12, if TriTri2D 0.0 false false t11 t12 then "overlap" else "do not overlap")
0 // return an integer exit code |
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.
| #ALGOL_68 | ALGOL 68 | main:(
PROC remove = (STRING file name)INT:
BEGIN
FILE actual file;
INT errno = open(actual file, file name, stand back channel);
IF errno NE 0 THEN stop remove FI;
scratch(actual file); # detach the book and burn it #
errno
EXIT
stop remove:
errno
END;
remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs")
) |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program deleteFic.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/***************************************************************/
/* File Constantes see task Include a file for arm assembly */
/***************************************************************/
.include "../constantes.inc"
.equ RMDIR, 0x28
.equ UNLINK, 0xA
/******************************************/
/* Initialized data */
/******************************************/
.data
szMessDeleteDirOk: .asciz "Delete directory Ok.\n"
szMessErrDeleteDir: .asciz "Unable delete dir. \n"
szMessDeleteFileOk: .asciz "Delete file Ok.\n"
szMessErrDeleteFile: .asciz "Unable delete file. \n"
szNameDir: .asciz "Docs"
szNameFile: .asciz "input.txt"
/******************************************/
/* UnInitialized data */
/******************************************/
.bss
/******************************************/
/* code section */
/******************************************/
.text
.global main
main: @ entry of program
@ delete file
ldr r0,iAdrszNameFile @ file name
mov r7,#UNLINK @ code call system delete file
svc #0 @ call systeme
cmp r0,#0 @ error ?
blt 99f
ldr r0,iAdrszMessDeleteFileOk @ delete file OK
bl affichageMess
@ delete directory
ldr r0,iAdrszNameDir @ directory name
mov r7, #RMDIR @ code call system delete directory
swi #0 @ call systeme
cmp r0,#0 @ error ?
blt 98f
ldr r0,iAdrszMessDeleteDirOk @ display message ok directory
bl affichageMess
@ end Ok
b 100f
98: @ display error message delete directory
ldr r0,iAdrszMessErrDeleteDir
bl affichageMess
b 100f
99: @ display error message delete file
ldr r0,iAdrszMessErrDeleteFile
bl affichageMess
b 100f
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszMessDeleteDirOk: .int szMessDeleteDirOk
iAdrszMessErrDeleteDir: .int szMessErrDeleteDir
iAdrszMessDeleteFileOk: .int szMessDeleteFileOk
iAdrszNameFile: .int szNameFile
iAdrszMessErrDeleteFile: .int szMessErrDeleteFile
iAdrszNameDir: .int szNameDir
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
perm
(
A
)
=
∑
σ
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \operatorname {perm} (A)=\sum _{\sigma }\prod _{i=1}^{n}M_{i,\sigma _{i}}}
In both cases the sum is over the permutations
σ
{\displaystyle \sigma }
of the permutations of 1, 2, ..., n. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)
More efficient algorithms for the determinant are known: LU decomposition, see for example wp:LU decomposition#Computing the determinant. Efficient methods for calculating the permanent are not known.
Related task
Permutations by swapping
| #Fortran | Fortran |
!-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Sat May 18 23:25:42
!
!a=./F && make $a && $a < unixdict.txt
!f95 -Wall -ffree-form F.F -o F
! j example, determinant: 7.00000000
! j example, permanent: 5.00000000
! maxima, determinant: -360.000000
! maxima, permanent: 900.000000
!
!Compilation finished at Sat May 18 23:25:43
! NB. example computed by J
! NB. fixed seed random matrix
! _2+3 3?.@$5
! 2 _1 1
!_1 _2 1
!_1 _1 _1
!
! (-/ .*)_2+3 3?.@$5 NB. determinant
!7
! (+/ .*)_2+3 3?.@$5 NB. permanent
!5
!maxima example
!a: matrix([2, 9, 4], [7, 5, 3], [6, 1, 8])$
!determinant(a);
!-360
!
!permanent(a);
!900
! compute permanent or determinant
program f
implicit none
real, dimension(3,3) :: j, m
data j/ 2,-1, 1,-1,-2, 1,-1,-1,-1/
data m/2, 9, 4, 7, 5, 3, 6, 1, 8/
write(6,*) 'j example, determinant: ',det(j,3,-1)
write(6,*) 'j example, permanent: ',det(j,3,1)
write(6,*) 'maxima, determinant: ',det(m,3,-1)
write(6,*) 'maxima, permanent: ',det(m,3,1)
contains
recursive function det(a,n,permanent) result(accumulation)
! setting permanent to 1 computes the permanent.
! setting permanent to -1 computes the determinant.
real, dimension(n,n), intent(in) :: a
integer, intent(in) :: n, permanent
real, dimension(n-1, n-1) :: b
real :: accumulation
integer :: i, sgn
if (n .eq. 1) then
accumulation = a(1,1)
else
accumulation = 0
sgn = 1
do i=1, n
b(:, :(i-1)) = a(2:, :i-1)
b(:, i:) = a(2:, i+1:)
accumulation = accumulation + sgn * a(1, i) * det(b, n-1, permanent)
sgn = sgn * permanent
enddo
endif
end function det
end program f
|
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.
| #Ceylon | Ceylon | shared void run() {
//integers divided by zero throw an exception
try {
value a = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
//floats divided by zero produce infinity
print(1.0 / 0 == infinity then "division by zero!" else "not division by zero!");
} |
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.
| #Clojure | Clojure | (defn safe-/ [x y]
(try (/ x y)
(catch ArithmeticException _
(println "Division by zero caught!")
(cond (> x 0) Double/POSITIVE_INFINITY
(zero? x) Double/NaN
:else Double/NEGATIVE_INFINITY) ))) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Batch_File | Batch File | set /a a=%arg%+0 >nul
if %a% == 0 (
if not "%arg%"=="0" (
echo Non Numeric.
) else (
echo Numeric.
)
) else (
echo Numeric.
) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #BBC_BASIC | BBC BASIC | REPEAT
READ N$
IF FN_isanumber(N$) THEN
PRINT "'" N$ "' is a number"
ELSE
PRINT "'" N$ "' is NOT a number"
ENDIF
UNTIL N$ = "end"
END
DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"
DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"
DEF FN_isanumber(A$)
ON ERROR LOCAL = FALSE
IF EVAL("(" + A$ + ")") <> VAL(A$) THEN = FALSE
IF VAL(A$) <> 0 THEN = TRUE
IF LEFT$(A$,1) = "0" THEN = TRUE
= FALSE
|
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as unique
process the strings from left─to─right
if unique, display a message saying such
if not unique, then:
display a message saying such
display what character is duplicated
only the 1st non─unique character need be displayed
display where "both" duplicated characters are in the string
the above messages can be part of a single message
display the hexadecimal value of the duplicated character
Use (at least) these five test values (strings):
a string of length 0 (an empty string)
a string of length 1 which is a single period (.)
a string of length 6 which contains: abcABC
a string of length 7 which contains a blank in the middle: XYZ ZYX
a string of length 36 which doesn't contain the letter "oh":
1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Common_Lisp | Common Lisp | ;; * Loading the iterate library
(eval-when (:compile-toplevel :load-toplevel)
(ql:quickload '("iterate")))
;; * The package definition
(defpackage :unique-string
(:use :common-lisp :iterate))
(in-package :unique-string)
;; * The test strings
(defparameter test-strings
'("" "." "abcABC" "XYZ ZYX" "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"))
;; * The function
(defun unique-string (string)
"Returns T if STRING has all unique characters."
(iter
(with hash = (make-hash-table :test #'equal))
(with len = (length string))
(with result = T)
(for char in-string string)
(for pos from 0)
(initially (format t "String ~a of length ~D~%" string len))
(if #1=(gethash char hash)
;; The character was seen before
(progn
(format t
" --> Non-unique character ~c #X~X found at position ~D,
before ~D ~%" char (char-code char) pos #1#)
(setf result nil))
;; The character was not seen before, saving its position
(setf #1# pos))
(finally (when result
(format t " --> All characters are unique~%"))
(return result))))
(mapcar #'unique-string test-strings) |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediately repeated character is any character that is immediately followed by an
identical character (or characters). Another word choice could've been duplicated character, but that
might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) PL/I BIF: collapse.}
Examples
In the following character string:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd t, e, and l are repeated characters, indicated
by underscores (above), even though they (those characters) appear elsewhere in the character string.
So, after collapsing the string, the result would be:
The beter the 4-whel drive, the further you'l be from help when ya get stuck!
Another example:
In the following character string:
headmistressship
The "collapsed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to
locate repeated characters and collapse (delete) them from the character
string. The character string can be processed from either direction.
Show all output here, on this page:
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
string
number
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║
5 ║ --- Harry S Truman ║ ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Groovy | Groovy | class StringCollapsible {
static void main(String[] args) {
for ( String s : [
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"122333444455555666666777777788888888999999999",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship"]) {
String result = collapse(s)
System.out.printf("old: %2d <<<%s>>>%nnew: %2d <<<%s>>>%n%n", s.length(), s, result.length(), result)
}
}
private static String collapse(String input) {
StringBuilder sb = new StringBuilder()
for ( int i = 0 ; i < input.length() ; i++ ) {
if ( i == 0 || input.charAt(i-1) != input.charAt(i) ) {
sb.append(input.charAt(i))
}
}
return sb.toString()
}
} |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.23 | F# |
// Determine if a string has all the same characters. Nigel Galloway: June 9th., 2020
let fN n=if String.length n=0 then None else n.ToCharArray()|>Array.tryFindIndex(fun g->g<>n.[0])
let allSame n=match fN n with
Some g->printfn "First different character in <<<%s>>> (length %d) is hex %x at position %d" n n.Length (int n.[g]) g
|_->printfn "All Characters are the same in <<<%s>>> (length %d)" n n.Length
allSame ""
allSame " "
allSame "2"
allSame "333"
allSame ".55"
allSame "tttTTT"
allSame "4444 444k"
|
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the strings are being examined)
a zero─length (empty) string shall be considered as all the same character(s)
process the strings from left─to─right
if all the same character, display a message saying such
if not all the same character, then:
display a message saying such
display what character is different
only the 1st different character need be displayed
display where the different character is in the string
the above messages can be part of a single message
display the hexadecimal value of the different character
Use (at least) these seven test values (strings):
a string of length 0 (an empty string)
a string of length 3 which contains three blanks
a string of length 1 which contains: 2
a string of length 3 which contains: 333
a string of length 3 which contains: .55
a string of length 6 which contains: tttTTT
a string of length 9 with a blank in the middle: 4444 444k
Show all output here on this page.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: formatting io kernel math.parser sequences ;
: find-diff ( str -- i elt ) dup ?first [ = not ] curry find ;
: len. ( str -- ) dup length "%u — length %d — " printf ;
: same. ( -- ) "contains all the same character." print ;
: diff. ( -- ) "contains a different character at " write ;
: not-same. ( i elt -- )
dup >hex diff. "index %d: '%c' (0x%s)\n" printf ;
: sameness-report. ( str -- )
dup len. find-diff dup [ not-same. ] [ 2drop same. ] if ;
{
""
" "
"2"
"333"
".55"
"tttTTT"
"4444 444k"
} [ sameness-report. ] each |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Dining_philosophers (whichplan) {
Form 80, 32
Const MayChangePick=Random(True, False)
dim energy(1 to 5)=50
Document Doc$
const nl$={
}
Print $(,12), ' set column width to 12
Pen 14
Pen 15 {
Doc$="Dining Philosophers"+nl$
\\ we can change thread plan only if no threads defined
if whichplan=1 then
Doc$="Sequential threads - to execute exclusive one threads code"+nl$
thread.plan sequential
\\ need time_to_think>time_to_eat, but time_to_appear maybe the same for all
time_to_think=150 ' one or more intervals
time_to_eat=100 ' one interval to eat only
time_to_appear=(150,150,150,150,150)
Return time_to_appear, random(0,3):=300
else
Doc$="Concurrent threads - to execute a statement or a block of code"+nl$
thread.plan concurrent
time_to_think=100 ' one or more intervals
time_to_eat=50 ' one interval to eat only
time_to_appear=(100,100,100,100,100)
Return time_to_appear, random(1,4):=200
end if
Print #-2,Doc$
Print @(0,2),"Press left mouse button to exit"
Print Part $(1), time_to_appear
Print under
}
Pen 13 {Print "Aristotle", "Kant", "Spinoza", "Marx", "Russell"}
enum philosopher {
Aristotle, Kant, Spinoza, Marx, Russell
}
global enum forks {NoFork, Fork}
RoundTable =(Fork, Fork, Fork, Fork, Fork)
Getleft=lambda RoundTable (ph as philosopher) -> {
where=(ph+4) mod 5
= RoundTable#val(where)
Return RoundTable, where:=NoFork
}
GetRight=lambda RoundTable (ph as philosopher) -> {
where=ph mod 5
=RoundTable#val(where)
Return RoundTable, where:=NoFork
}
PlaceForks=lambda RoundTable (ph as philosopher) -> {
Return RoundTable, (ph+4) mod 5:=Fork,ph mod 5:=Fork
}
PlaceAnyFork=lambda RoundTable (ph as philosopher, &ForkL, &ForkR) -> {
If ForkL=Fork then Return RoundTable, (ph+4) mod 5:=Fork : ForkL=NoFork
If ForkR=Fork Then Return RoundTable, ph mod 5:=Fork : ForkR=NoFork
}
ShowTable=lambda RoundTable -> {
m=each(RoundTable)
while m
print if$(array(m)=NoFork->"No Fork", "Fork"),
end while
Print
}
noforks=lambda RoundTable -> {
k=0
m=each(RoundTable)
while m
if array(m)=NoFork then k++
end while
=k=5
}
def critical as long, basetick
Document page$
m=each(philosopher)
while m {
\\ we make 5 threads
\\ a thread has module scope (except for own static variables, and stack of values)
thread {
if energy(f)<1 then {
call PlaceAnyFork(f, ForkL, ForkR)
energy(f)=0
Page$=format$("{0::-12} - ",tick-basetick)+eval$(f)+" - Die"+nl$
thread this erase
} else {
Page$=format$("{0::-12} - ",tick-basetick)+eval$(f)
Page$=if$(ForkL=Nofork or ForkR=Nofork->" thinking", " eating"+str$(eatcount))
Page$=if$(R->"- R", " - L")+nl$
}
if not think then
{ \\ a block always run blocking all other threads
energy(f)++
eatcount--
if eatcount>0 then exit
Call PlaceForks(f) : ForkL=Nofork:ForkR=NoFork
eatcount=random(4,8)
if MayChangePick then R=random(-1,0)
think=true :thread this interval time_to_think*random(1,5)
}
else.if energy(f)>70 or critical>5 then
{
call PlaceAnyFork(f, &ForkL, &ForkR)
if energy(f)>70 then energy(f)=60
}
else.if R then
if ForkR=Nofork then ForkR=GetRight(f)
if ForkR=fork and ForkL=Nofork then ForkL=GetLeft(f)
if ForkL=fork then think=false:thread this interval time_to_eat else energy(f)--
else
if ForkL=Nofork then ForkL=GetLeft(f)
if ForkL=fork and ForkR=Nofork then ForkR=GetRight(f)
if ForkR=fork then think=false:thread this interval time_to_eat else energy(f)--
end if
} as a interval time_to_appear#val(m^)
\\ a is a variable which hold the number of thread (as returned from task manager)
\\ so we can get 5 times a new number.
\\ for each thread we make some static variables (only for each thread)
\\ this statement execute a line of code in thread a
thread a execute {
\\ this executed on thread execution object
static f=eval(m), think=true, ForkL=NoFork
static ForkR=NoFork, eatcount=random(2,5)
static R=-1
if MayChangePick then R=Random(-1,0)
}
}
cls ,5 ' set split screen from fifth row
\\ Main.Task is a thread also. Normaly exit if no other threads running in background
\\ also serve a the wait loop for task manager (we can use Every 200 {} but isn't a thread, is a kind of a wait statement)
\\ tick return the counter from task manager which used to triger threads
basetick=tick
\\ 4hz display results
MaxCritical=0
Main.Task 1000/4 {
{ \\ a block always run blocking all other threads
cls
Print Part $(1),$("####;\D\I\E;\D\I\E"),energy()
Print Under
Print "Table:"
Call ShowTable()
if noforks() then critical++ else critical=0
MaxCritical=if(MaxCritical<critical->critical,MaxCritical)
Print "noforks on table counter:";critical, "Max:";MaxCritical
Print #-2,Page$
Doc$=Page$
Clear Page$
}
if critical>40 or keypress(1) then exit
}
threads erase
Clipboard Doc$
}
Dining_philosophers Random(1,2)
|
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Kotlin | Kotlin | import java.util.Calendar
import java.util.GregorianCalendar
enum class Season {
Chaos, Discord, Confusion, Bureaucracy, Aftermath;
companion object { fun from(i: Int) = values()[i / 73] }
}
enum class Weekday {
Sweetmorn, Boomtime, Pungenday, Prickle_Prickle, Setting_Orange;
companion object { fun from(i: Int) = values()[i % 5] }
}
enum class Apostle {
Mungday, Mojoday, Syaday, Zaraday, Maladay;
companion object { fun from(i: Int) = values()[i / 73] }
}
enum class Holiday {
Chaoflux, Discoflux, Confuflux, Bureflux, Afflux;
companion object { fun from(i: Int) = values()[i / 73] }
}
fun GregorianCalendar.discordianDate(): String {
val y = get(Calendar.YEAR)
val yold = y + 1166
var dayOfYear = get(Calendar.DAY_OF_YEAR)
if (isLeapYear(y)) {
if (dayOfYear == 60)
return "St. Tib's Day, in the YOLD " + yold
else if (dayOfYear > 60)
dayOfYear--
}
val seasonDay = --dayOfYear % 73 + 1
return when (seasonDay) {
5 -> "" + Apostle.from(dayOfYear) + ", in the YOLD " + yold
50 -> "" + Holiday.from(dayOfYear) + ", in the YOLD " + yold
else -> "" + Weekday.from(dayOfYear) + ", day " + seasonDay + " of " + Season.from(dayOfYear) + " in the YOLD " + yold
}
}
internal fun test(y: Int, m: Int, d: Int, result: String) {
assert(GregorianCalendar(y, m, d).discordianDate() == result)
}
fun main(args: Array<String>) {
println(GregorianCalendar().discordianDate())
test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176")
test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178")
test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178")
test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178")
test(2010, 0, 5, "Mungday, in the YOLD 3176")
test(2011, 4, 3, "Discoflux, in the YOLD 3177")
test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181")
} |
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)
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | bd = Graph[{"a" \[DirectedEdge] "b", "a" \[DirectedEdge] "c",
"b" \[DirectedEdge] "c", "b" \[DirectedEdge] "d",
"c" \[DirectedEdge] "d", "d" \[DirectedEdge] "e",
"a" \[DirectedEdge] "f", "c" \[DirectedEdge] "f",
"e" \[DirectedEdge] "f"},
EdgeWeight -> {7, 9, 10, 15, 11, 6, 14, 2, 9},
VertexLabels -> "Name", VertexLabelStyle -> Directive[Black, 20],
ImagePadding -> 20]
FindShortestPath[bd, "a", "e", Method -> "Dijkstra"]
-> {"a", "c", "d", "e"} |
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
| #Go | Go | package main
import (
"fmt"
"log"
"strconv"
)
func Sum(i uint64, base int) (sum int) {
b64 := uint64(base)
for ; i > 0; i /= b64 {
sum += int(i % b64)
}
return
}
func DigitalRoot(n uint64, base int) (persistence, root int) {
root = int(n)
for x := n; x >= uint64(base); x = uint64(root) {
root = Sum(x, base)
persistence++
}
return
}
// Normally the below would be moved to a *_test.go file and
// use the testing package to be runnable as a regular test.
var testCases = []struct {
n string
base int
persistence int
root int
}{
{"627615", 10, 2, 9},
{"39390", 10, 2, 6},
{"588225", 10, 2, 3},
{"393900588225", 10, 2, 9},
{"1", 10, 0, 1},
{"11", 10, 1, 2},
{"e", 16, 0, 0xe},
{"87", 16, 1, 0xf},
// From Applesoft BASIC example:
{"DigitalRoot", 30, 2, 26}, // 26 is Q base 30
// From C++ example:
{"448944221089", 10, 3, 1},
{"7e0", 16, 2, 0x6},
{"14e344", 16, 2, 0xf},
{"d60141", 16, 2, 0xa},
{"12343210", 16, 2, 0x1},
// From the D example:
{"1101122201121110011000000", 3, 3, 1},
}
func main() {
for _, tc := range testCases {
n, err := strconv.ParseUint(tc.n, tc.base, 64)
if err != nil {
log.Fatal(err)
}
p, r := DigitalRoot(n, tc.base)
fmt.Printf("%12v (base %2d) has additive persistence %d and digital root %s\n",
tc.n, tc.base, p, strconv.FormatInt(int64(r), tc.base))
if p != tc.persistence || r != tc.root {
log.Fatalln("bad result:", tc, p, r)
}
}
} |
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
| #REXX | REXX | /*REXX program finds the persistence and multiplicative digital root of some numbers.*/
numeric digits 100 /*increase the number of decimal digits*/
parse arg x /*obtain optional arguments from the CL*/
if x='' | x="," then x=123321 7739 893 899998 /*Not specified? Then use the default.*/
say center('number', 8) ' persistence multiplicative digital root'
say copies('─' , 8) ' ─────────── ───────────────────────────'
/* [↑] the title and separator. */
do j=1 for words(x); n=word(x, j) /*process each number in the X list.*/
parse value MDR(n) with mp mdr /*obtain the persistence and the MDR. */
say right(n,8) center(mp,13) center(mdr,30) /*display a number, persistence, MDR.*/
end /*j*/ /* [↑] show MP & MDR for each number. */
say copies('─' , 8) ' ─────────── ───────────────────────────'
say; say; target=5
say 'MDR first ' target " numbers that have a matching MDR"
say '═══ ═══════════════════════════════════════════════════'
do k=0 for 10; hits=0; _= /*show numbers that have an MDR of K. */
do m=k until hits==target /*find target numbers with an MDR of K.*/
if word( MDR(m), 2)\==k then iterate /*is this the MDR that's wanted? */
hits=hits + 1; _=space(_ m',') /*yes, we got a hit, add to the list. */
end /*m*/ /* [↑] built a list of MDRs that = K. */
say " "k': ['strip(_, , ',')"]" /*display the K (MDR) and the list. */
end /*k*/ /* [↑] done with the K MDR list. */
say '═══ ═══════════════════════════════════════════════════'
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
MDR: procedure; parse arg y; y=abs(y) /*get the number and determine the MDR.*/
do p=1 until y<10; parse var y r 2
do k=2 to length(y); r=r * substr(y, k, 1)
end /*k*/
y=r
end /*p*/ /* [↑] wash, rinse, and repeat ··· */
return p r /*return the persistence and the MDR. */ |
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?
| #MiniZinc | MiniZinc |
%Dinesman's multiple-dwelling problem. Nigel Galloway, September 25th., 2020
include "alldifferent.mzn";
enum names={Baker,Cooper,Miller,Smith,Fletcher};
array[names] of var 1..5: res; constraint alldifferent([res[n] | n in names]);
constraint res[Baker] !=5;
constraint res[Cooper] !=1;
constraint res[Fletcher] !=1;
constraint res[Fletcher] !=5;
constraint abs(res[Smith] -res[Fletcher]) > 1;
constraint abs(res[Cooper]-res[Fletcher]) > 1;
constraint res[Cooper] < res[Miller];
output["\(n) resides on floor \(res[n])\n" | n in names]
|
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
| #Go | Go | package main
import (
"errors"
"fmt"
"log"
)
var (
v1 = []int{1, 3, -5}
v2 = []int{4, -2, -1}
)
func dot(x, y []int) (r int, err error) {
if len(x) != len(y) {
return 0, errors.New("incompatible lengths")
}
for i, xi := range x {
r += xi * y[i]
}
return
}
func main() {
d, err := dot([]int{1, 3, -5}, []int{4, -2, -1})
if err != nil {
log.Fatal(err)
}
fmt.Println(d)
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead of any character that is immediately repeated.
If a character string has a specified immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
A specified immediately repeated character is any specified character that is immediately
followed by an identical character (or characters). Another word choice could've been duplicated
character, but that might have ruled out (to some readers) triplicated characters ··· or more.
{This Rosetta Code task was inspired by a newly introduced (as of around
November 2019) PL/I BIF: squeeze.}
Examples
In the following character string with a specified immediately repeated character of e:
The better the 4-wheel drive, the further you'll be from help when ya get stuck!
Only the 2nd e is an specified repeated character, indicated by an underscore
(above), even though they (the characters) appear elsewhere in the character string.
So, after squeezing the string, the result would be:
The better the 4-whel drive, the further you'll be from help when ya get stuck!
Another example:
In the following character string, using a specified immediately repeated character s:
headmistressship
The "squeezed" string would be:
headmistreship
Task
Write a subroutine/function/procedure/routine··· to locate a specified immediately repeated character
and squeeze (delete) them from the character string. The
character string can be processed from either direction.
Show all output here, on this page:
the specified repeated character (to be searched for and possibly squeezed):
the original string and its length
the resultant string and its length
the above strings should be "bracketed" with <<< and >>> (to delineate blanks)
«««Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here»»»
Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except
the 1st string:
immediately
string repeated
number character
( ↓ a blank, a minus, a seven, a period)
╔╗
1 ║╚═══════════════════════════════════════════════════════════════════════╗ ' ' ◄■■■■■■ a null string (length zero)
2 ║"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ║ '-'
3 ║..1111111111111111111111111111111111111111111111111111111111111117777888║ '7'
4 ║I never give 'em hell, I just tell the truth, and they think it's hell. ║ '.'
5 ║ --- Harry S Truman ║ (below) ◄■■■■■■ has many repeated blanks
╚════════════════════════════════════════════════════════════════════════╝ ↑
│
│
For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:
• a blank
• a minus
• a lowercase r
Note: there should be seven results shown, one each for the 1st four strings, and three results for
the 5th string.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | import Text.Printf (printf)
input :: [(String, Char)]
input = [ ("", ' ')
, ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e')
, ("headmistressship", 's')
, ("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-')
, ("..1111111111111111111111111111111111111111111111111111111111111117777888", '7')
, ("I never give 'em hell, I just tell the truth, and they think it's hell. ", '.')
, (" --- Harry S Truman ", 'r')
, ("aardvark", 'a')
, ("😍😀🙌💃😍😍😍🙌", '😍')
]
collapse :: Eq a => [a] -> a -> [a]
collapse s c = go s
where go [] = []
go (x:y:xs)
| x == y && x == c = go (y:xs)
| otherwise = x : go (y:xs)
go xs = xs
main :: IO ()
main =
mapM_ (\(a, b, c) -> printf "squeeze: '%c'\nold: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" c (length a) a (length b) b)
$ (\(s, c) -> (s, collapse s c, c)) <$> input |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.
Rule 1: The funnel remains directly above the target.
Rule 2: Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
Rule 3: As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
Rule 4: The funnel is moved directly over the last place a marble landed.
Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. Output: calculate the mean and standard-deviations of the resulting x and y values for each rule.
Note that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.
Stretch goal 1: Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.
Stretch goal 2: Show scatter plots of all four results.
Further information
Further explanation and interpretation
Video demonstration of the funnel experiment at the Mayo Clinic. | #J | J |
dx=:".0 :0-.LF
_0.533 0.270 0.859 _0.043 _0.205 _0.127 _0.071 0.275
1.251 _0.231 _0.401 0.269 0.491 0.951 1.150 0.001
_0.382 0.161 0.915 2.080 _2.337 0.034 _0.126 0.014
0.709 0.129 _1.093 _0.483 _1.193 0.020 _0.051 0.047
_0.095 0.695 0.340 _0.182 0.287 0.213 _0.423 _0.021
_0.134 1.798 0.021 _1.099 _0.361 1.636 _1.134 1.315
0.201 0.034 0.097 _0.170 0.054 _0.553 _0.024 _0.181
_0.700 _0.361 _0.789 0.279 _0.174 _0.009 _0.323 _0.658
0.348 _0.528 0.881 0.021 _0.853 0.157 0.648 1.774
_1.043 0.051 0.021 0.247 _0.310 0.171 0.000 0.106
0.024 _0.386 0.962 0.765 _0.125 _0.289 0.521 0.017
0.281 _0.749 _0.149 _2.436 _0.909 0.394 _0.113 _0.598
0.443 _0.521 _0.799 0.087
)
dy=:".0 :0-.LF
0.136 0.717 0.459 _0.225 1.392 0.385 0.121 _0.395
0.490 _0.682 _0.065 0.242 _0.288 0.658 0.459 0.000
0.426 0.205 _0.765 _2.188 _0.742 _0.010 0.089 0.208
0.585 0.633 _0.444 _0.351 _1.087 0.199 0.701 0.096
_0.025 _0.868 1.051 0.157 0.216 0.162 0.249 _0.007
0.009 0.508 _0.790 0.723 0.881 _0.508 0.393 _0.226
0.710 0.038 _0.217 0.831 0.480 0.407 0.447 _0.295
1.126 0.380 0.549 _0.445 _0.046 0.428 _0.074 0.217
_0.822 0.491 1.347 _0.141 1.230 _0.044 0.079 0.219
0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104
_0.729 0.650 _1.103 0.154 _1.720 0.051 _0.385 0.477
1.537 _0.901 0.939 _0.411 0.341 _0.411 0.106 0.224
_0.947 _1.424 _0.542 _1.032
)
Rule1=: ]
Rule2=: -/\.&.|.
Rule3=: ]-0,}:
Rule4=: ]+0,}:
smoutput ' Rule 1 (x,y):'
smoutput ' Mean: ',":dx ,&mean&Rule1 dy
smoutput ' Std dev: ',":dx ,&stddev&Rule1 dy
smoutput ' '
smoutput ' Rule 2 (x,y):'
smoutput ' Mean: ',":dx ,&mean&Rule2 dy
smoutput ' Std dev: ',":dx ,&stddev&Rule2 dy
smoutput ' '
smoutput ' Rule 3 (x,y):'
smoutput ' Mean: ',":dx ,&mean&Rule3 dy
smoutput ' Std dev: ',":dx ,&stddev&Rule3 dy
smoutput ' '
smoutput ' Rule 4 (x,y):'
smoutput ' Mean: ',":dx ,&mean&Rule4 dy
smoutput ' Std dev: ',":dx ,&stddev&Rule4 dy |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and must add up to 12.
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
Task
Write a computer program which outputs all valid combinations.
Possible output (for the 1st and 14th solutions):
--police-- --sanitation-- --fire--
2 3 7
6 5 1
| #Aime | Aime | integer p, s, f;
p = 0;
while ((p += 2) <= 7) {
s = 0;
while ((s += 1) <= 7) {
f = 0;
while ((f += 1) <= 7) {
if (p + s + f == 12 && p != s && p != f && s != f) {
o_form(" ~ ~ ~\n", p, s, f);
}
}
}
} |
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
| #XPL0 | XPL0 | include xpllib; \provides IsPrime and Sort
int I, N, Mask, Digit, A(512), Cnt;
[for I:= 0 to 511 do
[N:= 0; Mask:= I; Digit:= 9;
while Mask do
[if Mask&1 then
N:= N*10 + Digit;
Mask:= Mask>>1;
Digit:= Digit-1;
];
A(I):= N;
];
Sort(A, 512);
Cnt:= 0;
Format(9, 0);
for I:= 1 to 511 do \skip empty set
[N:= A(I);
if IsPrime(N) then
[RlOut(0, float(N));
Cnt:= Cnt+1;
if rem(Cnt/10) = 0 then CrLf(0);
];
];
] |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects responsibilities:
Delegator:
Keep an optional delegate instance.
Implement "operation" method, returning the delegate "thing" if the delegate respond to "thing", or the string "default implementation".
Delegate:
Implement "thing" and return the string "delegate implementation"
Show how objects are created and used. First, without a delegate, then with a delegate that does not implement "thing", and last with a delegate that implements "thing".
| #C.23 | C# | using System;
interface IOperable
{
string Operate();
}
class Inoperable
{
}
class Operable : IOperable
{
public string Operate()
{
return "Delegate implementation.";
}
}
class Delegator : IOperable
{
object Delegate;
public string Operate()
{
var operable = Delegate as IOperable;
return operable != null ? operable.Operate() : "Default implementation.";
}
static void Main()
{
var delegator = new Delegator();
foreach (var @delegate in new object[] { null, new Inoperable(), new Operable() })
{
delegator.Delegate = @delegate;
Console.WriteLine(delegator.Operate());
}
}
} |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)
(0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)
(0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)
(0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)
Optionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):
(0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)
| #FreeBASIC | FreeBASIC | #macro min(x,y)
Iif(x>y,y,x)
#endmacro
#macro max(x,y)
Iif(x>y,x,y)
#endmacro
type pnt 'typedef for a point
x as double
y as double
end type
type edg 'typedef for an edge
p1 as pnt
p2 as pnt
end type
function point_in_tri( r as pnt, a as pnt, b as pnt, c as pnt ) as boolean
'uses barycentric coordinates to determine whether point r is in the triangle defined by a, b, c
dim as double k = ((b.y - c.y)*(a.x - c.x) + (c.x - b.x)*(a.y - c.y))
dim as double v = ((b.y - c.y)*(r.x - c.x) + (c.x - b.x)*(r.y - c.y)) / k
dim as double w = ((c.y - a.y)*(r.x - c.x) + (a.x - c.x)*(r.y - c.y)) / k
dim as double z = 1 - v- w
if v<0 or v>1 then return false
if w<0 or w>1 then return false
if z<0 or z>1 then return false
return true
end function
function bbox_overlap( a1 as pnt, a2 as pnt, b1 as pnt, b2 as pnt) as boolean
dim as double a1x = min(a1.x, a2.x), a1y = min(a1.y, a2.y)
dim as double a2x = max(a1.x, a2.x), a2y = max(a1.y, a2.y)
dim as double b1x = min(b1.x, b2.x), b1y = min(b1.y, b2.y)
dim as double b2x = max(b1.x, b2.x), b2y = max(b1.y, b2.y)
if a1x > b2x or b1x > a2x then return false
if a1y > b2y or b2y > a2y then return false
return true
end function
function ccw( a as pnt, b as pnt, c as pnt) as double
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)
end function
function line_intersect( a as edg, b as edg ) as boolean
if ccw(a.p1, a.p2, b.p1)*ccw(a.p1, a.p2, b.p2) > 0 then return false
if ccw(b.p1, b.p2, a.p1)*ccw(b.p1, b.p2, a.p2) > 0 then return false
if not bbox_overlap( a.p1, a.p2, b.p1, b.p2 ) then return false
return true
end function
function triangle_overlap( a() as pnt, b() as pnt ) as boolean
'if two triangles overlap then either a corner of one triangle is inside
'the other OR an edge of one triangle intersects an edge of the other.
dim as uinteger i, j
dim as edg c, d
for i = 0 to 2
if point_in_tri( a(i), b(0), b(1), b(2) ) then return true
if point_in_tri( b(i), a(0), a(1), a(2) ) then return true
c.p1.x = a(i).x
c.p1.y = a(i).y
c.p2.x = a((i+1) mod 3).x
c.p2.y = a((i+1) mod 3).y
for j = 0 to 2
d.p1.x = b(i).x
d.p1.y = b(i).y
d.p2.x = b((i+1) mod 3).x
d.p2.y = b((i+1) mod 3).y
if line_intersect( c, d ) then return true
next j
next i
return 00
end function
data 0,0 , 5,0 , 0,5 , 0,0 , 5,0 , 0,6
data 0,0 , 0,5 , 5,0 , 0,0 , 0,5 , 5,0
data 0,0 , 5,0 , 0,5 , -10,0 , -5,0 , -1,6
data 0,0 , 5,0 , 2.5,5 , 0,4 , 2.5,-1 , 5,4
data 0,0 , 1,1 , 0,2 , 2,1 , 3,0 , 3,2
data 0,0 , 1,1 , 0,2 , 2,1 , 3,-2 , 3,4
data 0,0 , 1,0 , 0,1 , 1,0 , 2,0 , 1,1
dim as uinteger t, i
dim as pnt a(0 to 2), b(0 to 2)
for t = 1 to 7
for i = 0 to 2
read a(i).x, a(i).y
next i
for i = 0 to 2
read b(i).x, b(i).y
next i
print triangle_overlap( a(), b() )
next t
|
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.
| #Arturo | Arturo | file: "input.txt"
docs: "docs"
delete file
delete.directory file
delete join.path ["/" file]
delete.directory join.path ["/" docs] |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #AutoHotkey | AutoHotkey | FileDelete, input.txt
FileDelete, \input.txt
FileRemoveDir, docs, 1
FileRemoveDir, \docs, 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.