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/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #MiniScript | MiniScript | parseSep = function(s, pats)
result = []
startPos = 0
pos = 0
while pos < s.len
for pat in pats
if s[pos : pos+pat.len] != pat then continue
result.push s[startPos : pos]
result.push "{" + pat + "}"
startPos = pos + pat.len
pos = startPos - 1
break
end for
pos = pos + 1
end while
return result
end function
print parseSep("a!===b=!=c", ["==", "!=", "="]) |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Nim | Nim | import strutils
iterator tokenize(text: string; sep: openArray[string]): tuple[token: string, isSep: bool] =
var i, lastMatch = 0
while i < text.len:
for j, s in sep:
if text[i..text.high].startsWith s:
if i > lastMatch: yield (text[lastMatch ..< i], false)
yield (s, true)
lastMatch = i + s.len
i += s.high
break
inc i
if i > lastMatch: yield (text[lastMatch ..< i], false)
for token, isSep in "a!===b=!=c".tokenize(["==", "!=", "="]):
if isSep: stdout.write '{',token,'}'
else: stdout.write token
echo "" |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Befunge | Befunge | <+--XX@_v#!:-1,+55,g\1$_:00g2%-0vv:,+55<&,,,,,,"Size: "
"| Q"$$$>:01p:2%!00g0>>^<<!:-1\<1>00p::2%-:40p2/50p2*1+
!77**48*+31p\:1\g,::2\g:,\3\g,,^g>0g++40g%40g\-\40g\`*-
2g05\**!!%6g04-g052!:`\g05::-1/2<^4*2%g05\+*+1*!!%6g04- |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 1/x <-> x^y С/П |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #NetRexx | NetRexx |
/*NetRexx program to calculate the Nth root of X, with DIGS accuracy. */
class nth_root
method main(args=String[]) static
if args.length < 2 then
do
say "at least 2 arguments expected"
exit
end
x = args[0]
root = args[1]
if args.length > 2 then digs = args[2]
if root=='' then root=2
if digs = null, digs = '' then digs=20
numeric digits digs
say ' x = ' x
say ' root = ' root
say 'digits = ' digs
say 'answer = ' root(x,root,digs)
method root(x,r,digs) static --procedure; parse arg x,R 1 oldR /*assign 2nd arg-->r and rOrig. */
/*this subroutine will use the */
/*digits from the calling prog. */
/*The default digits is 9. */
R = r
oldR = r
if r=0 then do
say
say '*** error! ***'
say "a root of zero can't be specified."
say
return '[n/a]'
end
R=R.abs() /*use absolute value of root. */
if x<0 & (R//2==0) then do
say
say '*** error! ***'
say "an even root can't be calculated for a" -
'negative number,'
say 'the result would be complex.'
say
return '[n/a]'
end
if x=0 | r=1 then return x/1 /*handle couple of special cases.*/
Rm1=R-1 /*just a fast version of ROOT-1 */
oldDigs=digs /*get the current number of digs.*/
dm=oldDigs+5 /*we need a little guard room. */
ax=x.abs() /*the absolute value of X. */
g=(ax+1)/r**r /*take a good stab at 1st guess. */
-- numeric fuzz 3 /*fuzz digits for higher roots. */
d=5 /*start with only five digits. */
/*each calc doubles precision. */
loop forever
d=d+d
if d>dm then d = dm /*double the digits, but not>DM. */
numeric digits d /*tell REXX to use D digits. */
old=0 /*assume some kind of old guess. */
loop forever
_=(Rm1*g**R+ax)/R/g**rm1 /*this is the nitty-gritty stuff.*/
if _=g | _=old then leave /*computed close to this before? */
old=g /*now, keep calculation for OLD. */
g=_ /*set calculation to guesstimate.*/
end
if d==dm then leave /*found the root for DM digits ? */
end
_=g*x.sign() /*correct the sign (maybe). */
if oldR<0 then return _=1/_ /*root < 0 ? Reciprocal it is.*/
numeric digits oldDigs /*re-instate the original digits.*/
return _/1 /*normalize the number to digs. */
|
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #F.23 | F# | open System
let ordinalsuffix n =
let suffixstrings = [|"th"; "st"; "nd"; "rd"|]
let (d, r) = Math.DivRem(n, 10)
n.ToString() + suffixstrings.[ if r < 4 && (d &&& 1) = 0 then r else 0 ]
[<EntryPoint>]
let main argv =
let show = (Seq.iter (ordinalsuffix >> (printf " %s"))) >> (Console.WriteLine)
[0..25] |> show
[250..265] |> show
[1000..1025] |> show
0
|
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #REXX | REXX | ┌────────────────────────────────────────────────────────────────────┐
┌─┘ Input to this program (bases must be positive integers > 1): └─┐
│ │
│ x is required (it may have a sign). │
│ toBase the base to convert X to. │
│ inBase the base X is expressed in. │
│ │
│ If X has a leading sign, it is maintained (kept) after conversion. │
│ │
│ toBase or inBase can be a comma (,) which causes the default │
└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘
└────────────────────────────────────────────────────────────────────┘
|
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Ring | Ring |
# Project : Non-decimal radices/Convert
see "0 (decimal) -> " + hex(0) + " (base 16)" + nl
see "26 (decimal) -> " + hex(26) + " (base 16)" + nl
see "383 (decimal) -> " + hex(383) + " (base 16)" + nl
see "26 (decimal) -> " + tobase(26, 2) + " (base 2)" + nl
see "383 (decimal) -> " + tobase(383, 2) + " (base 2)" + nl
see "1a (base 16) -> " + dec("1a") + " (decimal)" + nl
see "1A (base 16) -> " + dec("1A") + " (decimal)" + nl
see "17f (base 16) -> " + dec("17f") + " (decimal)" + nl
see "101111111 (base 2) -> " + bintodec("101111111") + " (decimal)" + nl
func tobase(nr, base)
binary = 0
i = 1
while(nr != 0)
remainder = nr % base
nr = floor(nr/base)
binary= binary + (remainder*i)
i = i*10
end
return string(binary)
func bintodec(bin)
binsum = 0
for n=1 to len(bin)
binsum = binsum + number(bin[n]) *pow(2, len(bin)-n)
next
return binsum
|
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #Oforth | Oforth | : isNarcissistic(n)
| i m |
n 0 while( n ) [ n 10 /mod ->n swap 1 + ] ->m
0 m loop: i [ swap m pow + ] == ;
: genNarcissistic(n)
| l |
ListBuffer new dup ->l
0 while(l size n <>) [ dup isNarcissistic ifTrue: [ dup l add ] 1 + ] drop ;
|
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #PARI.2FGP | PARI/GP | isNarcissistic(n)=my(v=digits(n)); sum(i=1, #v, v[i]^#v)==n
v=List();for(n=1,1e9,if(isNarcissistic(n),listput(v,n);if(#v>24, return(Vec(v))))) |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #QBasic | QBasic | w = 254
SCREEN 13
VIEW (0, 0)-(w / 2, w / 2), , 0
FOR x = 0 TO w
FOR y = 0 TO w
COLOR ((x XOR y) AND 255)
PSET (x, y)
NEXT y
NEXT x |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Racket | Racket |
#lang racket
(require racket/draw)
(define palette (for/vector ([x 256]) (make-object color% 0 0 x)))
(define bm (make-object bitmap% 256 256))
(define dc (new bitmap-dc% [bitmap bm]))
(for* ([x 256] [y 256])
(define c (vector-ref palette (bitwise-xor x y)))
(send dc set-pixel x y c))
bm
|
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #Elixir | Elixir | defmodule Munchausen do
@pow for i <- 0..9, into: %{}, do: {i, :math.pow(i,i) |> round}
def number?(n) do
n == Integer.digits(n) |> Enum.reduce(0, fn d,acc -> @pow[d] + acc end)
end
end
Enum.each(1..5000, fn i ->
if Munchausen.number?(i), do: IO.puts i
end) |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Common_Lisp | Common Lisp | (defun m (n)
(if (zerop n)
0
(- n (f (m (- n 1))))))
(defun f (n)
(if (zerop n)
1
(- n (m (f (- n 1)))))) |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Perl | Perl | sub multisplit {
my ($sep, $string, %opt) = @_ ;
$sep = join '|', map quotemeta($_), @$sep;
$sep = "($sep)" if $opt{keep_separators};
split /$sep/, $string, -1;
}
print "'$_' " for multisplit ['==','!=','='], "a!===b=!=c";
print "\n";
print "'$_' " for multisplit ['==','!=','='], "a!===b=!=c", keep_separators => 1;
print "\n"; |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Bracmat | Bracmat | ( ( printBoard
= board M L x y S R row line
. :?board
& !ups:? [?M
& whl
' ( !arg:(?x.?y) ?arg
& !M:?L
& :?row:?line
& whl
' ( !L+-1:~<0:?L
& !x+1:~>!M:?x
& "---+" !line:?line
& " |" !row:?row
)
& "---+" !line:?line
& " Q |" !row:?row
& whl
' ( !L+-1:~<0:?L
& "---+" !line:?line
& " |" !row:?row
)
& "\n|" !row "\n+" !line !board:?board
)
& str$("\n+" !line !board)
)
( queens
= hor ver up down ups downs a z A Z x y Q
. !arg:(?hor.?ver.?ups.?downs.?Q)
& !ver
: (
& 1+!solutions:?solutions
{ Comment the line below if you only want a count. }
& out$(str$("\nsolution " !solutions) printBoard$!Q)
& ~ { Fail! (and backtrack to find more solutions)}
| #%?y
( ?z
& !hor
: ?A
#%?x
( ?Z
& !x+!y:?up
& !x+-1*!y:?down
& ~(!ups:? !up ?)
& ~(!downs:? !down ?)
& queens
$ ( !A !Z
. !z
. !up !ups
. !down !downs
. (!x.!y) !Q
)
)
)
)
)
& 0:?solutions
& 1 2 3 4 5 6 7 8:?H:?V {You can edit this line to find solutions for other sizes.}
& ( queens$(!H.!V...)
| out$(found !solutions solutions)
)
); |
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #11l | 11l | T PExp
BigInt prime
Int exp
F (prime, exp)
.prime = prime
.exp = exp
F isqrt(self)
V b = self
L
V a = b
b = (self I/ a + a) I/ 2
I b >= a
R a
F factor(BigInt n)
[PExp] pf
V nn = n
V b = 0
L ((nn % 2) == 0)
nn I/= 2
b++
I b > 0
pf [+]= PExp(BigInt(2), b)
V s = isqrt(nn)
V d = BigInt(3)
L nn > 1
I d > s
d = nn
V e = 0
L
V (div, rem) = divmod(nn, d)
I bit_length(rem) > 0
L.break
nn = div
e++
I e > 0
pf [+]= PExp(d, e)
s = isqrt(nn)
d += 2
R pf
F moBachShallit58(BigInt a, BigInt n; pf)
V n1 = n - 1
V mo = BigInt(1)
L(pe) pf
V y = n1 I/ pow(pe.prime, BigInt(pe.exp))
V o = 0
V x = pow(a, y, n)
L x > 1
x = pow(x, pe.prime, n)
o++
V o1 = pow(pe.prime, BigInt(o))
o1 I/= gcd(mo, o1)
mo *= o1
R mo
F moTest(a, n)
I bit_length(a) < 100
print(‘ord(’a‘)’, end' ‘’)
E
print(‘ord([big])’, end' ‘’)
print(‘ mod ’n‘ = ’moBachShallit58(a, n, factor(n - 1)))
moTest(37, 3343)
moTest(pow(BigInt(10), 100) + 1, 7919)
moTest(pow(BigInt(10), 1000) + 1, 15485863)
moTest(pow(BigInt(10), 10000) - 1, BigInt(22801763489))
moTest(1511678068, 7379191741)
moTest(BigInt(‘3047753288’), BigInt(‘2257683301’)) |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #NewLISP | NewLISP | (define (nth-root n a)
(let ((x1 a)
(x2 (div a n)))
(until (= x1 x2)
(setq x1 x2
x2 (div
(add
(mul x1 (- n 1))
(div a (pow x1 (- n 1))))
n)))
x2)) |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Factor | Factor | USING: io kernel math math.order math.parser math.ranges qw
sequences ;
IN: rosetta-code.nth
: n'th ( n -- str )
dup 10 /mod swap 1 = [ drop 0 ] when
[ number>string ]
[ 4 min qw{ th st nd rd th } nth ] bi* append ;
: n'th-demo ( -- )
0 25 250 265 1000 1025 [ [a,b] ] 2tri@
[ [ n'th write bl ] each nl ] tri@ ;
MAIN: n'th-demo |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Ruby | Ruby | class String
def convert_base(from, to)
Integer(self, from).to_s(to)
# self.to_i(from).to_s(to) #if you don't want exceptions
end
end
# first three taken from TCL
p "12345".convert_base(10, 23) # => "107h"
p "107h".convert_base(23, 7) # =>"50664"
p "50664".convert_base(7, 10) # =>"12345"
p "1038334289300125869792154778345043071467300".convert_base(10, 36) # =>"zombieseatingdeadvegetables"
p "ff".convert_base(15, 10) # => ArgumentError |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #Pascal | Pascal |
program NdN;
//Narcissistic decimal number
const
Base = 10;
MaxDigits = 16;
type
tDigit = 0..Base-1;
tcntDgt= 0..MaxDigits-1;
var
powDgt : array[tDigit] of NativeUint;
PotdgtPos: array[tcntDgt] of NativeUint;
UpperSum : array[tcntDgt] of NativeUint;
tmpSum,
tmpN,
actPot : NativeUint;
procedure InitPowDig;
var
i,j : NativeUint;
Begin
j := 1;
For i := 0 to High(tDigit) do
Begin
powDgt[i] := i;
PotdgtPos[i] := j;
j := j*Base;
end;
actPot := 0;
end;
procedure NextPowDig;
var
i,j : NativeUint;
Begin
// Next power of digit = i ^ actPot,always 0 = 0 , 1 = 1
For i := 2 to High(tDigit) do
powDgt[i] := powDgt[i]*i;
// number of digits times 9 ^(max number of digits)
j := powDgt[High(tDigit)];
For i := 0 to High(UpperSum) do
UpperSum[i] := (i+1)*j;
inc(actPot);
end;
procedure OutPutNdN(n:NativeUint);
Begin
write(n,' ');
end;
procedure NextDgtSum(dgtPos,i,sumPowDgt,n:NativeUint);
begin
//unable to reach sum
IF (sumPowDgt+UpperSum[dgtPos]) < n then
EXIT;
repeat
tmpN := n+PotdgtPos[dgtPos]*i;
tmpSum := sumPowDgt+powDgt[i];
//unable to get smaller
if tmpSum > tmpN then
EXIT;
IF tmpSum = tmpN then
OutPutNdN(tmpSum);
IF dgtPos>0 then
NextDgtSum(dgtPos-1,0,tmpSum,tmpN);
inc(i);
until i >= Base;
end;
var
i : NativeUint;
Begin
InitPowDig;
For i := 1 to 9 do
Begin
write(' length ',actPot+1:2,': ');
//start with 1 in front, else you got i-times 0 in front
NextDgtSum(actPot,1,0,0);
writeln;
NextPowDig;
end;
end. |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Raku | Raku | my $ppm = open("munching0.ppm", :w) orelse .die;
$ppm.print(q :to 'EOT');
P3
256 256
255
EOT
for 0 .. 255 -> $row {
for 0 .. 255 -> $col {
my $color = $row +^ $col;
$ppm.print("0 $color 0 ");
}
$ppm.say();
}
$ppm.close();
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #REXX | REXX | /*REXX program renders a graphical pattern by coloring each pixel with x XOR y */
/*───────────────────────────────────────── from an arbitrary constructed color table. */
rows= 2 /*the number of rows in the color table*/
cols= 5 /* " " " cols " " " " */
do row =0 for rows*3 /*construct a color table, size 25x50.*/
do col=0 for cols*3
$= (row+col) // 255
@.row.col= x2b( d2x($+0, 2) ) ||, /*ensure $ is converted──►2 hex nibbles*/
x2b( d2x($+1, 2) ) ||,
x2b( d2x($+2, 2) )
end /*col*/ /* [↑] construct a three-byte pixel. */
end /*row*/
do x=0 for cols /*create a graphical pattern with XORs.*/
do y=0 for rows
@.x.y= bitxor(@.x, @.y) /*renders 3 bytes (a pixel) at a time. */
end /*y*/
end /*x*/ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #F.23 | F# | let toFloat x = x |> int |> fun n -> n - 48 |> float
let power x = toFloat x ** toFloat x |> int
let isMunchausen n = n = (string n |> Seq.map char |> Seq.map power |> Seq.sum)
printfn "%A" ([1..5000] |> List.filter isMunchausen) |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #D | D | import std.stdio, std.algorithm, std.range;
int male(in int n) pure nothrow {
return n ? n - male(n - 1).female : 0;
}
int female(in int n) pure nothrow {
return n ? n - female(n - 1).male : 1;
}
void main() {
20.iota.map!female.writeln;
20.iota.map!male.writeln;
} |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Phix | Phix | with javascript_semantics
procedure multisplit(string text, sequence delims)
integer k = 1, kdx
while true do
integer kmin = 0
for i=1 to length(delims) do
integer ki = match(delims[i],text,k)
if ki!=0 then
if kmin=0 or ki<kmin then
kmin = ki
kdx = i
end if
end if
end for
string token = text[k..kmin-1],
delim = iff(kmin=0?"":sprintf(", delimiter (%s) at %d",{delims[kdx],kmin}))
printf(1,"Token: [%s] at %d%s\n",{token,k,delim})
if kmin=0 then exit end if
k = kmin+length(delims[kdx])
end while
end procedure
multisplit("a!===b=!=c",{"==","!=","="})
|
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #C | C | #include <stdio.h>
#include <stdlib.h>
int count = 0;
void solve(int n, int col, int *hist)
{
if (col == n) {
printf("\nNo. %d\n-----\n", ++count);
for (int i = 0; i < n; i++, putchar('\n'))
for (int j = 0; j < n; j++)
putchar(j == hist[i] ? 'Q' : ((i + j) & 1) ? ' ' : '.');
return;
}
# define attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j)
for (int i = 0, j = 0; i < n; i++) {
for (j = 0; j < col && !attack(i, j); j++);
if (j < col) continue;
hist[col] = i;
solve(n, col + 1, hist);
}
}
int main(int n, char **argv)
{
if (n <= 1 || (n = atoi(argv[1])) <= 0) n = 8;
int hist[n];
solve(n, 0, hist);
} |
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #Ada | Ada | package Multiplicative_Order is
type Positive_Array is array (Positive range <>) of Positive;
function Find_Order(Element, Modulus: Positive) return Positive;
-- naive algorithm
-- returns the smallest I such that (Element**I) mod Modulus = 1
function Find_Order(Element: Positive;
Coprime_Factors: Positive_Array) return Positive;
-- faster algorithm for the same task
-- computes the order of all Coprime_Factors(I)
-- and returns their least common multiple
-- this gives the same result as Find_Order(Element, Modulus)
-- with Modulus being the product of all the Coprime_Factors(I)
--
-- preconditions: (1) 1 = GCD(Coprime_Factors(I), Coprime_Factors(J))
-- for all pairs I, J with I /= J
-- (2) 1 < Coprime_Factors(I) for all I
end Multiplicative_Order; |
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #ALGOL_68 | ALGOL 68 | MODE LOOPINT = INT;
MODE POWMODSTRUCT = LONG INT;
PR READ "prelude/pow_mod.a68" PR;
MODE SORTSTRUCT = LONG INT;
PR READ "prelude/sort.a68" PR;
MODE GCDSTRUCT = LONG INT;
PR READ "prelude/gcd.a68" PR;
PR READ "prelude/iterator.a68" PR;
PROC is prime = (LONG INT p)BOOL:
( p > 1 |#ANDF# ALL((YIELDBOOL yield)VOID: factored(p, (LONG INT f, LONG INT e)VOID: yield(f = p))) | FALSE );
FLEX[4]LONG INT prime list := (2,3,5,7);
OP +:= = (REF FLEX[]LONG INT lhs, LONG INT rhs)VOID: (
[UPB lhs +1] LONG INT next lhs;
next lhs[:UPB lhs] := lhs;
lhs := next lhs;
lhs[UPB lhs] := rhs
);
PROC primes = (PROC (LONG INT)VOID yield)VOID: (
LONG INT p;
FOR p index TO UPB prime list DO
p:= prime list[p index];
yield(p)
OD;
DO
p +:= 2;
WHILE NOT is prime(p) DO
p +:= 2
OD;
prime list +:= p;
yield(p)
OD
);
PROC factored = (LONG INT in a, PROC (LONG INT,LONG INT)VOID yield)VOID: (
LONG INT a := in a;
# FOR p IN # primes( # DO #
(LONG INT p)VOID:(
LONG INT j := 0;
WHILE a MOD p = 0 DO
a := a % p;
j +:= 1
OD;
IF j > 0 THEN yield (p,j) FI;
IF a < p*p THEN done FI
)
# ) OD # );
done:
IF a > 1 THEN yield (a,1) FI
);
PROC mult0rdr1 = (LONG INT a, p, e)LONG INT: (
LONG INT m := p ** SHORTEN e;
LONG INT t := (p-1)*(p**SHORTEN (e-1)); # = Phi(p**e) where p prime #
LONG INT q;
FLEX[0]LONG INT qs := (1);
# FOR f0,f1 IN # factored(t # DO #,
(LONG INT f0,f1)VOID: (
FLEX[SHORTEN((f1+1)*UPB qs)]LONG INT next qs;
FOR j TO SHORTEN f1 + 1 DO
FOR q index TO UPB qs DO
q := qs[q index];
next qs[(j-1)*UPB qs+q index] := q * f0**(j-1)
OD
OD;
qs := next qs
)
# OD # );
VOID(in place shell sort(qs));
FOR q index TO UPB qs DO
q := qs[q index];
IF pow mod(a,q,m)=1 THEN done FI
OD;
done:
q
);
PROC reduce = (PROC (LONG INT,LONG INT)LONG INT diadic, FORLONGINT iterator, LONG INT initial value)LONG INT: (
LONG INT out := initial value;
# FOR next IN # iterator( # DO #
(LONG INT next)VOID:
out := diadic(out, next)
# OD # );
out
);
PROC mult order = (LONG INT a, LONG INT m)LONG INT: (
PROC mofs = (YIELDLONGINT yield)VOID:(
# FOR p, count IN # factored(m, # DO #
(LONG INT p, LONG INT count)VOID:
yield(mult0rdr1(a,p,count))
)
# OD # );
reduce(lcm, mofs, 1)
);
main:(
FORMAT d = $g(-0)$;
printf((d, mult order(37, 1000), $l$)); # 100 #
LONG INT b := LENG 10**20-1;
printf((d, mult order(2, b), $l$)); # 3748806900 #
printf((d, mult order(17,b), $l$)); # 1499522760 #
b := 100001;
printf((d, mult order(54,b), $l$));
printf((d, pow mod( 54, mult order(54,b),b), $l$));
IF ANY( (YIELDBOOL yield)VOID: FOR r FROM 2 TO SHORTEN mult order(54,b)-1 DO yield(1=pow mod(54,r, b)) OD )
THEN
printf(($g$, "Exists a power r < 9090 where pow mod(54,r,b) = 1", $l$))
ELSE
printf(($g$, "Everything checks.", $l$))
FI
) |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Nim | Nim | import math
proc nthRoot(a: float; n: int): float =
var n = float(n)
result = a
var x = a / n
while abs(result-x) > 1e-15:
x = result
result = (1/n) * (((n-1)*x) + (a / pow(x, n-1)))
echo nthRoot(34.0, 5)
echo nthRoot(42.0, 10)
echo nthRoot(5.0, 2) |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Objeck | Objeck | class NthRoot {
function : Main(args : String[]) ~ Nil {
NthRoot(5, 34, .001)->PrintLine();
}
function : NthRoot(n : Int, A: Float, p : Float) ~ Float {
x := Float->New[2];
x[0] := A;
x[1] := A / n;
while((x[1] - x[0])->Abs() > p) {
x[0] := x[1];
x[1] := ((n - 1.0) * x[1] + A / x[1]->Power(n - 1.0)) / n;
};
return x[1];
}
} |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Forth | Forth | : 'nth ( -- c-addr ) s" th st nd rd th th th th th th " drop ;
: .nth ( n -- )
dup 10 20 within if 0 .r ." th " exit then
dup 0 .r 10 mod 3 * 'nth + 3 type ;
: test ( n n -- ) cr do i 5 mod 0= if cr then i .nth loop ;
: tests ( -- )
26 0 test 266 250 test 1026 1000 test ;
tests |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Run_BASIC | Run BASIC | global basCvt$
basCvt$ ="0123456789abcdefghijklmnopqrstuvwxyz"
html "<table border=1><tr bgcolor=wheat align=center><td>Decimal</td><td>To Base</td><td>Num</td><td>to Dec</td></tr>"
for i =1 to 10
RandNum = int(100 * rnd(1))
base = 2 +int(35 * rnd(1))
html "<tr align=right><td>";using("###", RandNum);"</td><td>";using("###", base);"</td><td>";toBase$(base,RandNum);"</td><td>";toDecimal( base, toBase$( base, RandNum));"</td></tr>"
next i
html "</table>"
end
function toBase$(b,n) ' b=base n=nmber
toBase$ =""
for i =10 to 1 step -1
toBase$ =mid$(basCvt$,n mod b +1,1) +toBase$
n =int( n /b)
if n <1 then exit for
next i
end function
function toDecimal( b, s$) ' scring number to decimal
toDecimal =0
for i =1 to len( s$)
toDecimal = toDecimal * b + instr(basCvt$,mid$(s$,i,1),1) -1
next i
end function |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #Perl | Perl | sub is_narcissistic {
my $n = shift;
my($k,$sum) = (length($n),0);
$sum += $_**$k for split(//,$n);
$n == $sum;
}
my $i = 0;
for (1..25) {
$i++ while !is_narcissistic($i);
say $i++;
} |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Ring | Ring |
# Project : Munching squares
load "guilib.ring"
paint = null
new qapp
{
win1 = new qwidget() {
setwindowtitle("Archimedean spiral")
setgeometry(100,100,500,600)
label1 = new qlabel(win1) {
setgeometry(10,10,400,400)
settext("")
}
new qpushbutton(win1) {
setgeometry(150,500,100,30)
settext("draw")
setclickevent("draw()")
}
show()
}
exec()
}
func draw
p1 = new qpicture()
color = new qcolor() {
setrgb(0,0,255,255)
}
pen = new qpen() {
setcolor(color)
setwidth(1)
}
paint = new qpainter() {
begin(p1)
setpen(pen)
w = 100
for x = 0 to w
for y = 0 to w
b = (x ^ y)
color = new qcolor()
color.setrgb(255 -b,b /2,b,255)
pen.setcolor(color)
setpen(pen)
drawpoint(x,w -y -1)
next
next
endpaint()
}
label1 { setpicture(p1) show() }
return
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Ruby | Ruby | load 'raster_graphics.rb'
class Pixmap
def self.xor_pattern(width, height, rgb1, rgb2)
# create colour table
size = 256
colours = Array.new(size) do |i|
RGBColour.new(
(rgb1.red + (rgb2.red - rgb1.red) * i / size),
(rgb1.green + (rgb2.green - rgb1.green) * i / size),
(rgb1.blue + (rgb2.blue - rgb1.blue) * i / size),
)
end
# create the image
pixmap = new(width, height)
pixmap.each_pixel do |x, y|
pixmap[x,y] = colours[(x^y)%size]
end
pixmap
end
end
img = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW)
img.save_as_png('xorpattern.png') |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #Factor | Factor | USING: kernel math.functions math.ranges math.text.utils
prettyprint sequences ;
: munchausen? ( n -- ? )
dup 1 digit-groups dup [ ^ ] 2map sum = ;
5000 [1,b] [ munchausen? ] filter . |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Dart | Dart | int M(int n) => n==0?1:n-F(M(n-1));
int F(int n) => n==0?0:n-M(F(n-1));
main() {
String f="",m="";
for(int i=0;i<20;i++) {
m+="${M(i)} ";
f+="${F(i)} ";
}
print("M: $m");
print("F: $f");
} |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #PicoLisp | PicoLisp | (de multisplit (Str Sep)
(setq Sep (mapcar chop Sep))
(make
(for (S (chop Str) S)
(let L
(make
(loop
(T (find head Sep (circ S))
(link
(list
(- (length Str) (length S))
(pack (cut (length @) 'S)) ) ) )
(link (pop 'S))
(NIL S (link NIL)) ) )
(link (pack (cdr (rot L))))
(and (car L) (link @)) ) ) ) )
(println (multisplit "a!===b=!=c" '("==" "!=" "=")))
(println (multisplit "a!===b=!=c" '("=" "!=" "=="))) |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Pike | Pike | string input = "a!===b=!=c";
array sep = ({"==", "!=", "=" });
array result = replace(input, sep, `+("\0", sep[*], "\0"))/"\0";
result;
Result: ({ "a", "!=", "", "==", "b", "=", "", "!=", "c" })
int pos = 0;
foreach(result; int index; string data)
{
if ((<"==", "!=", "=">)[data])
result[index] = ({ data, pos });
pos+=sizeof(data);
}
result;
Result: ({"a", ({"!=", 1}), "", ({"==", 3}), "b", ({"=", 6}), "", ({"!=", 7}), "c"}) |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #C.23 | C# | using System.Collections.Generic;
using static System.Linq.Enumerable;
using static System.Console;
using static System.Math;
namespace N_Queens
{
static class Program
{
static void Main(string[] args)
{
var n = 8;
var cols = Range(0, n);
var combs = cols.Combinations(2).Select(pairs=> pairs.ToArray());
var solved = from v in cols.Permutations().Select(p => p.ToArray())
where combs.All(c => Abs(v[c[0]] - v[c[1]]) != Abs(c[0] - c[1]))
select v;
WriteLine($"{n}-queens has {solved.Count()} solutions");
WriteLine("Position is row, value is column:-");
var first = string.Join(" ", solved.First());
WriteLine($"First Solution: {first}");
Read();
}
//Helpers
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)
{
if (values.Count() == 1)
return values.ToSingleton();
return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())), (v, p) => p.Prepend(v));
}
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) =>
seq.Aggregate(Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b))));
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) =>
seq.Combinations().Where(s => s.Count() == numItems);
public static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }
}
} |
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #C | C | ulong mpow(ulong a, ulong p, ulong m)
{
ulong r = 1;
while (p) {
if ((1 & p)) r = r * a % m;
a = a * a % m;
p >>= 1;
}
return r;
}
ulong ipow(ulong a, ulong p) {
ulong r = 1;
while (p) {
if ((1 & p)) r = r * a;
a *= a;
p >>= 1;
}
return r;
}
ulong gcd(ulong m, ulong n)
{
ulong t;
while (m) { t = m; m = n % m; n = t; }
return n;
}
ulong lcm(ulong m, ulong n)
{
ulong g = gcd(m, n);
return m / g * n;
}
ulong multi_order_p(ulong a, ulong p, ulong e)
{
ulong fac[10000];
ulong m = ipow(p, e);
ulong t = m / p * (p - 1);
int i, len = get_factors(t, fac);
for (i = 0; i < len; i++)
if (mpow(a, fac[i], m) == 1)
return fac[i];
return 0;
}
ulong multi_order(ulong a, ulong m)
{
prime_factor pf[100];
int i, len = get_prime_factors(m, pf);
ulong res = 1;
for (i = 0; i < len; i++)
res = lcm(res, multi_order_p(a, pf[i].p, pf[i].e));
return res;
}
int main()
{
sieve();
printf("%lu\n", multi_order(37, 1000));
printf("%lu\n", multi_order(54, 100001));
return 0;
} |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #OCaml | OCaml | let nthroot ~n ~a ?(tol=0.001) () =
let nf = float n in let nf1 = nf -. 1.0 in
let rec iter x =
let x' = (nf1 *. x +. a /. (x ** nf1)) /. nf in
if tol > abs_float (x -. x') then x' else iter x' in
iter 1.0
;;
let () =
Printf.printf "%g\n" (nthroot 10 (7131.5 ** 10.0) ());
Printf.printf "%g\n" (nthroot 5 34.0 ());
;; |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Fortran | Fortran | !-*- mode: compilation; default-directory: "/tmp/" -*-
!Compilation started at Fri Jun 6 15:40:18
!
!a=./f && make -k $a && echo 0 25 | $a && echo 250 265 | $a && echo 1000 1025 | $a
!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none -g f.f08 -o f
! 0'th 1'st 2'nd
! 3'rd 4'th 5'th
! 6'th 7'th 8'th
! 9'th 10'th 11'th
! 12'th 13'th 14'th
! 15'th 16'th 17'th
! 18'th 19'th 20'th
! 21'st 22'nd 23'rd
! 24'th 25'th
! 250'th 251'st
! 252'nd 253'rd 254'th
! 255'th 256'th 257'th
! 258'th 259'th 260'th
! 261'st 262'nd 263'rd
! 264'th 265'th
! 1000th 1001st
! 1002nd 1003rd 1004th
! 1005th 1006th 1007th
! 1008th 1009th 1010th
! 1011th 1012th 1013th
! 1014th 1015th 1016th
! 1017th 1018th 1019th
! 1020th 1021st 1022nd
! 1023rd 1024th 1025th
!
!Compilation finished at Fri Jun 6 15:40:18
program nth
implicit none
logical :: need
integer :: here, there, n, i, iostat
read(5,*,iostat=iostat) here, there
if (iostat .ne. 0) then
write(6,*)'such bad input never before seen.'
write(6,*)'I AYE EYE QUIT!'
call exit(1)
end if
need = .false.
n = abs(there - here) + 1
i = 0
do while (0 /= mod(3+mod(here-i, 3), 3))
write(6,'(a22)',advance='no') ''
i = i+1
end do
do i = here, there, sign(1, there-here)
write(6,'(a22)',advance='no') ordinate(i)
if (2 /= mod(i,3)) then
need = .true.
else
write(6,'(a)')''
need = .false.
end if
end do
if (need) write(6,'(a)')''
contains
character(len=22) function ordinate(n)
character(len=19) :: a
character(len=20), parameter :: &
&a09 = "thstndrdthththththth",&
&ateen = "thththththththththth"
integer :: ones, tens, ones_index
integer, intent(in) :: n
write(a,'(i19)') n
ones = mod(n,10)
tens = mod(n,100)
ones_index = ones*2+1
if (n < 1000) then
if ((10 .le. tens) .and. (tens .lt. 20)) then
ordinate = a // "'" // ateen(ones_index:ones_index+1)
! ^^^^^^ remove these characters to remove the important '
else
ordinate = a // "'" // a09(ones_index:ones_index+1)
! ^^^^^^ remove these characters to remove the important '
end if
else
if ((10 .le. tens) .and. (tens .lt. 20)) then
ordinate = a // ateen(ones_index:ones_index+1)
else
ordinate = a // a09(ones_index:ones_index+1)
end if
end if
end function ordinate
end program nth |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Rust | Rust | fn format_with_radix(mut n: u32, radix: u32) -> String {
assert!(2 <= radix && radix <= 36);
let mut result = String::new();
loop {
result.push(std::char::from_digit(n % radix, radix).unwrap());
n /= radix;
if n == 0 {
break;
}
}
result.chars().rev().collect()
}
#[cfg(test)]
#[test]
fn test() {
for value in 0..100u32 {
for radix in 2..=36 {
let s = format_with_radix(value, radix);
let v = u32::from_str_radix(s.as_str(), radix).unwrap();
assert_eq!(value, v);
}
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("{}", format_with_radix(0xdeadbeef, 2));
println!("{}", format_with_radix(0xdeadbeef, 36));
println!("{}", format_with_radix(0xdeadbeef, 16));
println!("{}", u32::from_str_radix("DeadBeef", 16)?);
Ok(())
} |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #Phix | Phix | with javascript_semantics
function narcissistic(integer n)
string d = sprintf("%d",n)
integer l = length(d)
atom sumn = 0
for i=1 to l do
sumn += power(d[i]-'0',l)
end for
return sumn=n
end function
sequence s = {}
integer n = 0
while length(s)<25 do
if narcissistic(n) then s &= n end if
n += 1
end while
pp(s)
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Run_BASIC | Run BASIC | w = 100
graphic #g, w,w
for x = 0 to w
for y = 0 to w
b = (x xor y) and 255
#g color(255 -b,b /2,b)
#g "set "; x; " "; w -y -1
next y
next x
render #g
#g "flush" |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Rust | Rust | extern crate image;
use image::{ImageBuffer, Pixel, Rgb};
fn main() {
let mut img = ImageBuffer::new(256, 256);
for x in 0..256 {
for y in 0..256 {
let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0);
img.put_pixel(x, y, pixel);
}
}
let _ = img.save("output.png");
} |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #FALSE | FALSE | 0[1+$5000>~][
$$0\[$][
$10/$@\10*-
$0>[
$$[1-$][\2O*\]#
%\%
]?
@+\
]#
%=[$.10,]?
]#% |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Delphi | Delphi |
unit Hofstadter;
interface
type
THofstadterFemaleMaleSequences = class
public
class function F(n: Integer): Integer;
class function M(n: Integer): Integer;
end;
implementation
class function THofstadterFemaleMaleSequences.F(n: Integer): Integer;
begin
Result:= 1;
if (n > 0) then
Result:= n - M(F(n-1));
end;
class function THofstadterFemaleMaleSequences.M(n: Integer): Integer;
begin
Result:= 0;
if (n > 0) then
Result:= n - F(M(n - 1));
end;
end.
|
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #PowerShell | PowerShell |
$string = "a!===b=!=c"
$separators = [regex]"(==|!=|=)"
$matchInfo = $separators.Matches($string) |
Select-Object -Property Index, Value |
Group-Object -Property Value |
Select-Object -Property @{Name="Separator"; Expression={$_.Name}},
Count,
@{Name="Position" ; Expression={$_.Group.Index}}
$matchInfo
|
http://rosettacode.org/wiki/Multiple_distinct_objects | Multiple distinct objects | Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #11l | 11l | (1..n).map(i -> Foo()) |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #C.2B.2B | C++ | // Much shorter than the version below;
// uses C++11 threads to parallelize the computation; also uses backtracking
// Outputs all solutions for any table size
#include <vector>
#include <iostream>
#include <iomanip>
#include <thread>
#include <future>
// Print table. 'pos' is a vector of positions – the index in pos is the row,
// and the number at that index is the column where the queen is placed.
static void print(const std::vector<int> &pos)
{
// print table header
for (int i = 0; i < pos.size(); i++) {
std::cout << std::setw(3) << char('a' + i);
}
std::cout << '\n';
for (int row = 0; row < pos.size(); row++) {
int col = pos[row];
std::cout << row + 1 << std::setw(3 * col + 3) << " # ";
std::cout << '\n';
}
std::cout << "\n\n";
}
static bool threatens(int row_a, int col_a, int row_b, int col_b)
{
return row_a == row_b // same row
or col_a == col_b // same column
or std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal
}
// the i-th queen is in the i-th row
// we only check rows up to end_idx
// so that the same function can be used for backtracking and checking the final solution
static bool good(const std::vector<int> &pos, int end_idx)
{
for (int row_a = 0; row_a < end_idx; row_a++) {
for (int row_b = row_a + 1; row_b < end_idx; row_b++) {
int col_a = pos[row_a];
int col_b = pos[row_b];
if (threatens(row_a, col_a, row_b, col_b)) {
return false;
}
}
}
return true;
}
static std::mutex print_count_mutex; // mutex protecting 'n_sols'
static int n_sols = 0; // number of solutions
// recursive DFS backtracking solver
static void n_queens(std::vector<int> &pos, int index)
{
// if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return
if (index >= pos.size()) {
if (good(pos, index)) {
std::lock_guard<std::mutex> lock(print_count_mutex);
print(pos);
n_sols++;
}
return;
}
// backtracking step
if (not good(pos, index)) {
return;
}
// optimization: the first level of the search tree is parallelized
if (index == 0) {
std::vector<std::future<void>> fts;
for (int col = 0; col < pos.size(); col++) {
pos[index] = col;
auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); });
fts.push_back(std::move(ft));
}
for (const auto &ft : fts) {
ft.wait();
}
} else { // deeper levels are not
for (int col = 0; col < pos.size(); col++) {
pos[index] = col;
n_queens(pos, index + 1);
}
}
}
int main()
{
std::vector<int> start(12); // 12: table size
n_queens(start, 0);
std::cout << n_sols << " solutions found.\n";
return 0;
}
|
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
namespace MultiplicativeOrder {
// Taken from https://stackoverflow.com/a/33918233
public static class PrimeExtensions {
// Random generator (thread safe)
private static ThreadLocal<Random> s_Gen = new ThreadLocal<Random>(
() => {
return new Random();
}
);
// Random generator (thread safe)
private static Random Gen {
get {
return s_Gen.Value;
}
}
public static bool IsProbablyPrime(this BigInteger value, int witnesses = 10) {
if (value <= 1)
return false;
if (witnesses <= 0)
witnesses = 10;
BigInteger d = value - 1;
int s = 0;
while (d % 2 == 0) {
d /= 2;
s += 1;
}
byte[] bytes = new byte[value.ToByteArray().LongLength];
BigInteger a;
for (int i = 0; i < witnesses; i++) {
do {
Gen.NextBytes(bytes);
a = new BigInteger(bytes);
}
while (a < 2 || a >= value - 2);
BigInteger x = BigInteger.ModPow(a, d, value);
if (x == 1 || x == value - 1)
continue;
for (int r = 1; r < s; r++) {
x = BigInteger.ModPow(x, 2, value);
if (x == 1)
return false;
if (x == value - 1)
break;
}
if (x != value - 1)
return false;
}
return true;
}
}
static class Helper {
public static BigInteger Sqrt(this BigInteger self) {
BigInteger b = self;
while (true) {
BigInteger a = b;
b = self / a + a >> 1;
if (b >= a) return a;
}
}
public static long BitLength(this BigInteger self) {
BigInteger bi = self;
long bitlength = 0;
while (bi != 0) {
bitlength++;
bi >>= 1;
}
return bitlength;
}
public static bool BitTest(this BigInteger self, int pos) {
byte[] arr = self.ToByteArray();
int idx = pos / 8;
int mod = pos % 8;
if (idx >= arr.Length) {
return false;
}
return (arr[idx] & (1 << mod)) > 0;
}
}
class PExp {
public PExp(BigInteger prime, int exp) {
Prime = prime;
Exp = exp;
}
public BigInteger Prime { get; }
public int Exp { get; }
}
class Program {
static void MoTest(BigInteger a, BigInteger n) {
if (!n.IsProbablyPrime(20)) {
Console.WriteLine("Not computed. Modulus must be prime for this algorithm.");
return;
}
if (a.BitLength() < 100) {
Console.Write("ord({0})", a);
} else {
Console.Write("ord([big])");
}
if (n.BitLength() < 100) {
Console.Write(" mod {0} ", n);
} else {
Console.Write(" mod [big] ");
}
BigInteger mob = MoBachShallit58(a, n, Factor(n - 1));
Console.WriteLine("= {0}", mob);
}
static BigInteger MoBachShallit58(BigInteger a, BigInteger n, List<PExp> pf) {
BigInteger n1 = n - 1;
BigInteger mo = 1;
foreach (PExp pe in pf) {
BigInteger y = n1 / BigInteger.Pow(pe.Prime, pe.Exp);
int o = 0;
BigInteger x = BigInteger.ModPow(a, y, BigInteger.Abs(n));
while (x > 1) {
x = BigInteger.ModPow(x, pe.Prime, BigInteger.Abs(n));
o++;
}
BigInteger o1 = BigInteger.Pow(pe.Prime, o);
o1 = o1 / BigInteger.GreatestCommonDivisor(mo, o1);
mo = mo * o1;
}
return mo;
}
static List<PExp> Factor(BigInteger n) {
List<PExp> pf = new List<PExp>();
BigInteger nn = n;
int e = 0;
while (!nn.BitTest(e)) e++;
if (e > 0) {
nn = nn >> e;
pf.Add(new PExp(2, e));
}
BigInteger s = nn.Sqrt();
BigInteger d = 3;
while (nn > 1) {
if (d > s) d = nn;
e = 0;
while (true) {
BigInteger div = BigInteger.DivRem(nn, d, out BigInteger rem);
if (rem.BitLength() > 0) break;
nn = div;
e++;
}
if (e > 0) {
pf.Add(new PExp(d, e));
s = nn.Sqrt();
}
d = d + 2;
}
return pf;
}
static void Main(string[] args) {
MoTest(37, 3343);
MoTest(BigInteger.Pow(10, 100) + 1, 7919);
MoTest(BigInteger.Pow(10, 1000) + 1, 15485863);
MoTest(BigInteger.Pow(10, 10000) - 1, 22801763489);
MoTest(1511678068, 7379191741);
MoTest(3047753288, 2257683301);
}
}
} |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Octave | Octave |
r = A.^(1./n)
|
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Apostrophes NOT used as incorrect English
Function ordinal(n As UInteger) As String
Dim ns As String = Str(n)
Select Case Right(ns, 1)
Case "0", "4" To "9"
Return ns + "th"
Case "1"
If Right(ns, 2) = "11" Then Return ns + "th"
Return ns + "st"
Case "2"
If Right(ns, 2) = "12" Then Return ns + "th"
Return ns + "nd"
Case "3"
If Right(ns, 2) = "13" Then Return ns + "th"
Return ns + "rd"
End Select
End Function
Dim i As Integer
For i = 0 To 25
Print ordinal(i); " ";
Next
Print : Print
For i = 250 To 265
Print ordinal(i); " ";
Next
Print : Print
For i = 1000 To 1025
Print ordinal(i); " ";
Next
Print : Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Scala | Scala | def backToBig(num: String, oldBase: Int): BigInt = BigInt(num, oldBase)
def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase) |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const proc: main is func
begin
writeln(60272032366_ radix 36); # Convert bigInteger to string
writeln(591458 radix 36); # Convert integer to string
writeln(bigInteger("rosetta", 36)); # Convert string to bigInteger
writeln(integer("code", 36)); # Convert string to integer
end func; |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #PicoLisp | PicoLisp | (let (C 25 N 0 L 1)
(loop
(when
(=
N
(sum ** (mapcar format (chop N)) (need L L)) )
(println N)
(dec 'C) )
(inc 'N)
(setq L (length N))
(T (=0 C) 'done) ) )
(bye) |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #PL.2FI | PL/I | narn: Proc Options(main);
Dcl (j,k,l,nn,n,sum) Dec Fixed(15)init(0);
Dcl s Char(15) Var;
Dcl p(15) Pic'9' Based(addr(s));
Dcl (ms,msa,ela) Dec Fixed(15);
Dcl tim Char(12);
n=30;
ms=milliseconds();
Do j=0 By 1 Until(nn=n);
s=dec2str(j);
l=length(s);
sum=left(s,1)**l;
Do k=2 To l;
sum=sum+substr(s,k,1)**l;
If sum>j Then Leave;
End;
If sum=j Then Do
nn=nn+1;
msa=milliseconds();
ela=msa-ms;
/*Put Skip Data(ms,msa,ela);*/
ms=msa; /*yyyymmddhhmissmis*/
tim=translate('ij:kl:mn.opq',datetime(),'abcdefghijklmnopq');
Put Edit(nn,' narcissistic:',j,ela,tim)
(Skip,f(9),a,f(12),f(15),x(2),a(12));
End;
End;
dec2str: Proc(x) Returns(char(16) var);
Dcl x Dec Fixed(15);
Dcl ds Pic'(14)z9';
ds=x;
Return(trim(ds));
End;
milliseconds: Proc Returns(Dec Fixed(15));
Dcl c17 Char(17);
dcl 1 * Def C17,
2 * char(8),
2 hh Pic'99',
2 mm Pic'99',
2 ss Pic'99',
2 ms Pic'999';
Dcl result Dec Fixed(15);
c17=datetime();
result=(((hh*60+mm)*60)+ss)*1000+ms;
/*
Put Edit(translate('ij:kl:mn.opq',datetime(),'abcdefghijklmnopq'),
result)
(Skip,a(12),F(15));
*/
Return(result);
End
End; |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Scala | Scala | import scala.swing.Swing.pair2Dimension
import scala.swing.{Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication}
object XorPattern extends SimpleSwingApplication {
def top = new MainFrame {
preferredSize = (300, 300)
title = "Rosetta Code >>> Task: Munching squares | Language: Scala"
contents = new Panel {
protected override def paintComponent(g: Graphics2D) = {
super.paintComponent(g)
for {
y <- 0 until size.getHeight.toInt
x <- 0 until size.getWidth.toInt
} {
g.setColor(new Color(0, (x ^ y) % 256, 0))
g.drawLine(x, y, x, y)
}
}
}
centerOnScreen()
}
} |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #FOCAL | FOCAL | 01.10 F N=1,5000;D 2
02.10 S M=N;S S=0
02.20 S D=M-FITR(M/10)*10
02.25 S S=S+D^D
02.30 S M=FITR(M/10)
02.40 I (M),2.5,2.2
02.50 I (N-S)2.7,2.6,2.7
02.60 T %4,N,!
02.70 R |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | F n:
if n:
- n M F -- n
else:
1
M n:
if n:
- n F M -- n
else:
0
for i range 0 10:
!.( M i F i ) |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Prolog | Prolog | multisplit(_LSep, '') -->
{!},
[].
multisplit(LSep, T) -->
{next_sep(LSep, T, [], Token, Sep, T1)},
( {Token \= '' },[Token], {!}; []),
( {Sep \= '' },[Sep], {!}; []),
multisplit(LSep, T1).
next_sep([], T, Lst, Token, Sep, T1) :-
% if we can't find any separator, the game is over
( Lst = [] ->
Token = T, Sep = '', T1 = '';
% we sort the list to get nearest longest separator
predsort(my_sort, Lst, [(_,_, Sep)|_]),
atomic_list_concat([Token|_], Sep, T),
atom_concat(Token, Sep, Tmp),
atom_concat(Tmp, T1, T)).
next_sep([HSep|TSep], T, Lst, Token, Sep, T1) :-
sub_atom(T, Before, Len, _, HSep),
next_sep(TSep, T, [(Before, Len,HSep) | Lst], Token, Sep, T1).
next_sep([_HSep|TSep], T, Lst, Token, Sep, T1) :-
next_sep(TSep, T, Lst, Token, Sep, T1).
my_sort(<, (N1, _, _), (N2, _, _)) :-
N1 < N2.
my_sort(>, (N1, _, _), (N2, _, _)) :-
N1 > N2.
my_sort(>, (N, N1, _), (N, N2, _)) :-
N1 < N2.
my_sort(<, (N, N1, _), (N, N2, _)) :-
N1 > N2.
|
http://rosettacode.org/wiki/Multiple_distinct_objects | Multiple distinct objects | Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Action.21 | Action! | DEFINE PTR="CARD"
DEFINE OBJSIZE="4"
TYPE Record=[BYTE b CHAR c INT i]
PROC PrintObjects(PTR ARRAY items BYTE count)
Record POINTER r
BYTE n
FOR n=0 TO count-1
DO
r=items(n)
PrintF("(%B ""%C"" %I) ",r.b,r.c,r.i)
IF n MOD 3=2 THEN PutE() FI
OD
PutE()
RETURN
PROC Main()
DEFINE MIN="1"
DEFINE MAX="20"
DEFINE BUFSIZE="80"
BYTE ARRAY buffer(BUFSIZE)
PTR ARRAY items(MAX)
BYTE count=[0],n,LMARGIN=$52,oldLMARGIN
Record POINTER r
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
WHILE count<min OR count>max
DO
PrintF("How many objects (%I-%I)?",MIN,MAX)
count=InputB()
OD
FOR n=0 TO count-1
DO
items(n)=buffer+n*OBJSIZE
OD
PutE()
PrintE("Uninitialized objects:")
PrintObjects(items,count)
FOR n=0 TO count-1
DO
r=items(n)
r.b=n r.c=n+'A r.i=-n
OD
PutE()
PrintE("Initialized objects:")
PrintObjects(items,count)
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN |
http://rosettacode.org/wiki/Multiple_distinct_objects | Multiple distinct objects | Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Ada | Ada | A : array (1..N) of T; |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Clojure | Clojure | (def size 8)
(defn extends? [v n]
(let [k (count v)]
(not-any? true?
(for [i (range k) :let [vi (v i)]]
(or
(= vi n) ;check for shared row
(= (- k i) (Math/abs (- n vi)))))))) ;check for shared diagonal
(defn extend [vs]
(for [v vs
n (range 1 (inc size)) :when (extends? v n)]
(conj v n)))
(def solutions
(nth (iterate extend [[]]) size))
(doseq [s solutions]
(println s))
(println (count solutions) "solutions") |
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #C.2B.2B | C++ | #include <algorithm>
#include <bitset>
#include <iostream>
#include <vector>
typedef unsigned long ulong;
std::vector<ulong> primes;
typedef struct {
ulong p, e;
} prime_factor; /* prime, exponent */
void sieve() {
/* 65536 = 2^16, so we can factor all 32 bit ints */
constexpr int SIZE = 1 << 16;
std::bitset<SIZE> bits;
bits.flip(); // set all bits
bits.reset(0);
bits.reset(1);
for (int i = 0; i < 256; i++) {
if (bits.test(i)) {
for (int j = i * i; j < SIZE; j += i) {
bits.reset(j);
}
}
}
/* collect primes into a list. slightly faster this way if dealing with large numbers */
for (int i = 0; i < SIZE; i++) {
if (bits.test(i)) {
primes.push_back(i);
}
}
}
auto get_prime_factors(ulong n) {
std::vector<prime_factor> lst;
ulong e, p;
for (ulong i = 0; i < primes.size(); i++) {
p = primes[i];
if (p * p > n) break;
for (e = 0; !(n % p); n /= p, e++);
if (e) {
lst.push_back({ p, e });
}
}
if (n != 1) {
lst.push_back({ n, 1 });
}
return lst;
}
auto get_factors(ulong n) {
auto f = get_prime_factors(n);
std::vector<ulong> lst{ 1 };
size_t len2 = 1;
/* L = (1); L = (L, L * p**(1 .. e)) forall((p, e)) */
for (size_t i = 0; i < f.size(); i++, len2 = lst.size()) {
for (ulong j = 0, p = f[i].p; j < f[i].e; j++, p *= f[i].p) {
for (size_t k = 0; k < len2; k++) {
lst.push_back(lst[k] * p);
}
}
}
std::sort(lst.begin(), lst.end());
return lst;
}
ulong mpow(ulong a, ulong p, ulong m) {
ulong r = 1;
while (p) {
if (p & 1) {
r = r * a % m;
}
a = a * a % m;
p >>= 1;
}
return r;
}
ulong ipow(ulong a, ulong p) {
ulong r = 1;
while (p) {
if (p & 1) r *= a;
a *= a;
p >>= 1;
}
return r;
}
ulong gcd(ulong m, ulong n) {
ulong t;
while (m) {
t = m;
m = n % m;
n = t;
}
return n;
}
ulong lcm(ulong m, ulong n) {
ulong g = gcd(m, n);
return m / g * n;
}
ulong multi_order_p(ulong a, ulong p, ulong e) {
ulong m = ipow(p, e);
ulong t = m / p * (p - 1);
auto fac = get_factors(t);
for (size_t i = 0; i < fac.size(); i++) {
if (mpow(a, fac[i], m) == 1) {
return fac[i];
}
}
return 0;
}
ulong multi_order(ulong a, ulong m) {
auto pf = get_prime_factors(m);
ulong res = 1;
for (size_t i = 0; i < pf.size(); i++) {
res = lcm(res, multi_order_p(a, pf[i].p, pf[i].e));
}
return res;
}
int main() {
sieve();
printf("%lu\n", multi_order(37, 1000)); // expect 100
printf("%lu\n", multi_order(54, 100001)); // expect 9090
return 0;
} |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Oforth | Oforth | Float method: nthroot(n)
1.0 doWhile: [ self over n 1 - pow / over - n / tuck + swap 0.0 <> ] ; |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Oz | Oz | declare
fun {NthRoot NInt A}
N = {Int.toFloat NInt}
fun {Next X}
( (N-1.0)*X + A / {Pow X N-1.0} ) / N
end
in
{Until Value.'==' Next A/N}
end
fun {Until P F X}
case {F X}
of NX andthen {P NX X} then X
[] NX then {Until P F NX}
end
end
in
{Show {NthRoot 2 2.0}} |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Gambas | Gambas | Public Sub Main()
Dim siNums As Short[] = [0, 25, 250, 265, 1000, 1025]
Dim siCount, siNumbers As Short
Dim sOrdinal As String
For siNumbers = 0 To 4 Step 2
For siCount = siNums[siNumbers] To siNums[siNumbers + 1]
sOrdinal = "th"
If Right(Str(siCount), 1) = "1" And Right(Str(siCount), 2) <> "11" Then sOrdinal = "st"
If Right(Str(siCount), 1) = "2" And Right(Str(siCount), 2) <> "12" Then sOrdinal = "nd"
If Right(Str(siCount), 1) = "3" And Right(Str(siCount), 2) <> "13" Then sOrdinal = "rd"
Print siCount & sOrdinal;;
Next
Print gb.NewLine
Next
End |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Sidef | Sidef | say 60272032366.base(36) # convert number to string
say Number("rosetta", 36) # convert string to number |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #PowerShell | PowerShell |
function Test-Narcissistic ([int]$Number)
{
if ($Number -lt 0) {return $false}
$total = 0
$digits = $Number.ToString().ToCharArray()
foreach ($digit in $digits)
{
$total += [Math]::Pow([Char]::GetNumericValue($digit), $digits.Count)
}
$total -eq $Number
}
[int[]]$narcissisticNumbers = @()
[int]$i = 0
while ($narcissisticNumbers.Count -lt 25)
{
if (Test-Narcissistic -Number $i)
{
$narcissisticNumbers += $i
}
$i++
}
$narcissisticNumbers | Format-Wide {"{0,7}" -f $_} -Column 5 -Force
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Sidef | Sidef | require('Imager')
var img = %O<Imager>.new(xsize => 256, ysize => 256)
for y=(^256), x=(^256) {
var rgb = [(255 - x - y).abs, (255-x)^y, x^(255-y)]
img.setpixel(x => x, y => y, color => rgb)
}
img.write(file => 'xor.png') |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Tcl | Tcl | package require Tk
proc xorImage {img table} {
set data {}
set h [image height $img]
set w [image width $img]
for {set y 0} {$y < $h} {incr y} {
set row {}
for {set x 0} {$x < $w} {incr x} {
lappend row [lindex $table [expr {($x^$y) % [llength $table]}]]
}
lappend data $row
}
$img put $data
}
proc inRange {i f t} {expr {$f + ($t-$f)*$i/255}}
proc mkTable {rf rt gf gt bf bt} {
for {set i 0} {$i < 256} {incr i} {
lappend tbl [format "#%02x%02x%02x" \
[inRange $i $rf $rt] [inRange $i $gf $gt] [inRange $i $bf $bt]]
}
return $tbl
}
set img [image create photo -width 512 -height 512]
xorImage $img [mkTable 0 255 64 192 255 0]
pack [label .l -image $img] |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #Forth | Forth |
: dig.num \ returns input number and the number of its digits ( n -- n n1 )
dup
0 swap
begin
swap 1 + swap
dup 10 >= while
10 /
repeat
drop ;
: to.self \ returns input number raised to the power of itself ( n -- n^n )
dup 1 = if drop 1 else \ positive numbers only, zero and negative returns zero
dup 0 <= if drop 0 else
dup
1 do
dup
loop
dup
1 do
*
loop
then then ;
: ten.to \ ( n -- 10^n ) returns 1 for zero and negative
dup 0 <= if drop 1 else
dup 1 = if drop 10 else
10 swap
1 do
10 *
loop then then ;
: zero.divmod \ /mod that returns zero if number is zero
dup
0 = if drop 0
else /mod
then ;
: split.div \ returns input number and its digits ( n -- n n1 n2 n3....)
dup 10 < if dup 0 else \ duplicates single digit numbers adds 0 for add.pow
dig.num \ provides number of digits
swap dup rot dup 1 - ten.to swap \ stack juggling, ten raised to number of digits - 1...
1 do \ ... is the needed divisor, counter on top and ...
dup rot swap zero.divmod swap rot 10 / \ ...division loop
loop drop then ;
: add.pow \ raises each number on the stack except last one to ...
to.self \ ...the power of itself and adds them
depth \ needs at least 3 numbers on the stack
2 do
swap to.self +
loop ;
: check.num
split.div add.pow ;
: munch.num \ ( n -- ) displays Munchausen numbers between 1 and n
1 +
page
1 do
i check.num = if i . cr
then loop ;
|
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Draco | Draco | /* We need to predeclare M if we want F to be able to see it.
* This is done using 'extern', same as if it had been in a
* different compilation unit. */
extern M(byte n) byte;
/* Mutually recursive functions */
proc F(byte n) byte:
if n=0 then 1 else n - M(F(n-1)) fi
corp
proc M(byte n) byte:
if n=0 then 0 else n - F(M(n-1)) fi
corp
/* Show the first 16 values of each */
proc nonrec main() void:
byte i;
write("F:");
for i from 0 upto 15 do write(F(i):2) od;
writeln();
write("M:");
for i from 0 upto 15 do write(M(i):2) od;
writeln()
corp |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Python | Python | >>> import re
>>> def ms2(txt="a!===b=!=c", sep=["==", "!=", "="]):
if not txt or not sep:
return []
ans = m = []
for m in re.finditer('(.*?)(?:' + '|'.join('('+re.escape(s)+')' for s in sep) + ')', txt):
ans += [m.group(1), (m.lastindex-2, m.start(m.lastindex))]
if m and txt[m.end(m.lastindex):]:
ans += [txt[m.end(m.lastindex):]]
return ans
>>> ms2()
['a', (1, 1), '', (0, 3), 'b', (2, 6), '', (1, 7), 'c']
>>> ms2(txt="a!===b=!=c", sep=["=", "!=", "=="])
['a', (1, 1), '', (0, 3), '', (0, 4), 'b', (0, 6), '', (1, 7), 'c'] |
http://rosettacode.org/wiki/Multiple_distinct_objects | Multiple distinct objects | Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #Aime | Aime | void
show_sublist(list l)
{
integer i, v;
for (i, v in l) {
o_space(sign(i));
o_integer(v);
}
}
void
show_list(list l)
{
integer i;
list v;
for (i, v in l) {
o_text(" [");
show_sublist(v);
o_text("]");
}
o_byte('\n');
}
list
multiple_distinct(integer n, object o)
{
list l;
call_n(n, l_append, l, o);
return l;
}
integer
main(void)
{
list l, z;
# create a list of integers - `3' will serve as initializer
l = multiple_distinct(8, 3);
l_clear(l);
# create a list of distinct lists - `z' will serve as initializer
l_append(z, 4);
l = multiple_distinct(8, z);
# modify one of the sublists
l_q_list(l, 3)[0] = 7;
# display the list of lists
show_list(l);
return 0;
} |
http://rosettacode.org/wiki/Multiple_distinct_objects | Multiple distinct objects | Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #ALGOL_68 | ALGOL 68 | MODE FOO = STRUCT(CHAR u,l);
INT n := 26;
[n]FOO f;
# Additionally each item can be initialised #
FOR i TO UPB f DO f[i] := (REPR(ABS("A")-1+i), REPR(ABS("a")-1+i)) OD;
print((f, new line)) |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #CLU | CLU | n_queens = cluster is solve
rep = null
own hist: array[int] := array[int]$[]
own solutions: array[string] := array[string]$[]
attack = proc (i,j,col: int) returns (bool)
return(hist[j]=i | int$abs(hist[j]-i)=col-j)
end attack
cur_solution = proc ()
n: int := array[int]$size(hist)
ss: stream := stream$create_output()
for i: int in int$from_to(0,n-1) do
for j: int in int$from_to(0,n-1) do
if j=hist[i] then stream$putc(ss, 'Q')
elseif (i+j)//2 = 1 then stream$putc(ss, ' ')
else stream$putc(ss, '.')
end
end
stream$putc(ss, '\n')
end
array[string]$addh(solutions, stream$get_contents(ss))
end cur_solution
solve_rec = proc (col: int)
n: int := array[int]$size(hist)
if col=n then cur_solution() return end
for i: int in int$from_to(0,n-1) do
j: int := 0
while j<col cand ~attack(i,j,col) do j := j+1 end
if j<col then continue end
hist[col] := i
solve_rec(col+1)
end
end solve_rec
solve = proc (n: int) returns (sequence[string])
hist := array[int]$fill(0,n,0)
solutions := array[string]$[]
solve_rec(0)
return(sequence[string]$a2s(solutions))
end solve
end n_queens
start_up = proc()
N = 8
po: stream := stream$primary_output()
solutions: sequence[string] := n_queens$solve(N)
count: int := 0
for s: string in sequence[string]$elements(solutions) do
count := count + 1
stream$putl(po, "No. " || int$unparse(count) || "\n-------\n" || s)
end
end start_up |
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #Clojure | Clojure | (defn gcd [a b]
(if (zero? b)
a
(recur b (mod a b))))
(defn lcm [a b]
(/ (* a b) (gcd a b)))
(def NaN (Math/log -1))
(defn ord' [a [p e]]
(let [m (imath/expt p e)
t (* (quot m p) (dec p))]
(loop [dv (factor/divisors t)]
(let [d (first dv)]
(if (= (mmath/expm a d m) 1)
d
(recur (next dv)))))))
(defn ord [a n]
(if (not= (gcd a n) 1)
NaN
(->>
(factor/factorize n)
(map (partial ord' a))
(reduce lcm))))
|
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #PARI.2FGP | PARI/GP | root(n,A)=A^(1/n); |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Pascal | Pascal | use strict;
sub nthroot ($$)
{
my ( $n, $A ) = @_;
my $x0 = $A / $n;
my $m = $n - 1.0;
while(1) {
my $x1 = ($m * $x0 + $A / ($x0 ** $m)) / $n;
return $x1 if abs($x1 - $x0) < abs($x0 * 1e-9);
$x0 = $x1;
}
} |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #Go | Go | package main
import "fmt"
func ord(n int) string {
s := "th"
switch c := n % 10; c {
case 1, 2, 3:
if n%100/10 == 1 {
break
}
switch c {
case 1:
s = "st"
case 2:
s = "nd"
case 3:
s = "rd"
}
}
return fmt.Sprintf("%d%s", n, s)
}
func main() {
for n := 0; n <= 25; n++ {
fmt.Printf("%s ", ord(n))
}
fmt.Println()
for n := 250; n <= 265; n++ {
fmt.Printf("%s ", ord(n))
}
fmt.Println()
for n := 1000; n <= 1025; n++ {
fmt.Printf("%s ", ord(n))
}
fmt.Println()
} |
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Slate | Slate | 26 printString &radix: 16
Integer readFrom: '1A' &radix: 16. |
http://rosettacode.org/wiki/Narcissistic_decimal_number | Narcissistic decimal number | A Narcissistic decimal number is a non-negative integer,
n
{\displaystyle n}
, that is equal to the sum of the
m
{\displaystyle m}
-th powers of each of the digits in the decimal representation of
n
{\displaystyle n}
, where
m
{\displaystyle m}
is the number of digits in the decimal representation of
n
{\displaystyle n}
.
Narcissistic (decimal) numbers are sometimes called Armstrong numbers, named after Michael F. Armstrong.
They are also known as Plus Perfect numbers.
An example
if
n
{\displaystyle n}
is 153
then
m
{\displaystyle m}
, (the number of decimal digits) is 3
we have 13 + 53 + 33 = 1 + 125 + 27 = 153
and so 153 is a narcissistic decimal number
Task
Generate and show here the first 25 narcissistic decimal numbers.
Note:
0
1
=
0
{\displaystyle 0^{1}=0}
, the first in the series.
See also
the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
MathWorld entry: Narcissistic Number.
Wikipedia entry: Narcissistic number.
| #Python | Python | from __future__ import print_function
from itertools import count, islice
def narcissists():
for digits in count(0):
digitpowers = [i**digits for i in range(10)]
for n in range(int(10**(digits-1)), 10**digits):
div, digitpsum = n, 0
while div:
div, mod = divmod(div, 10)
digitpsum += digitpowers[mod]
if n == digitpsum:
yield n
for i, n in enumerate(islice(narcissists(), 25), 1):
print(n, end=' ')
if i % 5 == 0: print()
print() |
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #TI-83_BASIC | TI-83 BASIC | PROGRAM:XORPATT
" •.-,+-°-1+o*:πOX"→Str1
ClrHome
{0,0,0,0}→L1
{0,0,0,0)→L2
For(I,1,8,1)
For(J,1,16,1)
J→A
I→B
If A>8
Then
A-8→A
1→L1(1)
Else
0→L1(1)
End
If A>4
Then
A-4→A
1→L1(2)
Else
0→L1(2)
End
If A>2
Then
A-2→A
1→L1(3)
Else
0→L1(3)
End
If A>1
Then
1→L1(4)
Else
0→L1(4)
End
0→L2(1)
If B>4
Then
B-4→B
1→L2(2)
Else
0→L2(2)
End
If B>2
Then
B-2→B
1→L2(3)
Else
0→L2(3)
End
If B>1
Then
1→L2(4)
Else
0→L2(4)
End
L1≠L2→L3
8L3(1)+4L3(2)+2L3(3)+L3(4)→C
Output(I,J,sub(Str1,C+1,1))
End
End
Pause
|
http://rosettacode.org/wiki/Munching_squares | Munching squares | Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
| #Visual_Basic_.NET | Visual Basic .NET | ' Munching squares - 27/07/2018
Public Class MunchingSquares
Const xsize = 256
Dim BMP As New Drawing.Bitmap(xsize, xsize)
Dim GFX As Graphics = Graphics.FromImage(BMP)
Private Sub MunchingSquares_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
'draw
Dim MyGraph As Graphics = Me.CreateGraphics
Dim nColor As Color
Dim i, j, cp As Integer
xPictureBox.Image = BMP
For i = 0 To xsize - 1
For j = 0 To xsize - 1
cp = i Xor j
nColor = Color.FromArgb(cp, 0, cp)
BMP.SetPixel(i, j, nColor)
Next j
Next i
End Sub 'Paint
End Class |
http://rosettacode.org/wiki/Munchausen_numbers | Munchausen numbers | A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n.
(Munchausen is also spelled: Münchhausen.)
For instance: 3435 = 33 + 44 + 33 + 55
Task
Find all Munchausen numbers between 1 and 5000.
Also see
The OEIS entry: A046253
The Wikipedia entry: Perfect digit-to-digit invariant, redirected from Munchausen Number
| #Fortran | Fortran | C MUNCHAUSEN NUMBERS - FORTRAN IV
DO 2 I=1,5000
IS=0
II=I
DO 1 J=1,4
ID=10**(4-J)
N=II/ID
IR=MOD(II,ID)
IF(N.NE.0) IS=IS+N**N
1 II=IR
2 IF(IS.EQ.I) WRITE(*,*) I
END |
http://rosettacode.org/wiki/Mutual_recursion | Mutual recursion | Two functions are said to be mutually recursive if the first calls the second,
and in turn the second calls the first.
Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
F
(
0
)
=
1
;
M
(
0
)
=
0
F
(
n
)
=
n
−
M
(
F
(
n
−
1
)
)
,
n
>
0
M
(
n
)
=
n
−
F
(
M
(
n
−
1
)
)
,
n
>
0.
{\displaystyle {\begin{aligned}F(0)&=1\ ;\ M(0)=0\\F(n)&=n-M(F(n-1)),\quad n>0\\M(n)&=n-F(M(n-1)),\quad n>0.\end{aligned}}}
(If a language does not allow for a solution using mutually recursive functions
then state this rather than give a solution by other means).
| #Dyalect | Dyalect | func f(n) {
n == 0 ? 1 : n - m(f(n-1))
}
and m(n) {
n == 0 ? 0 : n - f(m(n-1))
}
print( (0..20).Map(i => f(i)).ToArray() )
print( (0..20).Map(i => m(i)).ToArray() ) |
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Racket | Racket |
#lang racket
(regexp-match* #rx"==|!=|=" "a!===b=!=c" #:gap-select? #t #:match-select values)
;; => '("a" ("!=") "" ("==") "b" ("=") "" ("!=") "c")
|
http://rosettacode.org/wiki/Multisplit | Multisplit | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”.
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
Extra Credit: provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| #Raku | Raku | sub multisplit($str, @seps) { $str.split(/ ||@seps /, :v) }
my @chunks = multisplit( 'a!===b=!=c==d', < == != = > );
# Print the strings.
say @chunks».Str.raku;
# Print the positions of the separators.
for grep Match, @chunks -> $s {
say " $s from $s.from() to $s.to()";
} |
http://rosettacode.org/wiki/Multiple_distinct_objects | Multiple distinct objects | Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #ALGOL_W | ALGOL W | begin
record T ( integer n, m );
reference(T) singleT;
integer numberOfElements;
singleT := T( 0, 0 );
numberOfElements := 3;
begin
reference(T) array tArray ( 1 :: numberOfElements );
% initialise the "right" way %
for i := 1 until numberOfElements do begin
tArray( i ) := T( i, i * 2 );
m(tArray( i )) := m(tArray( i )) + 1;
end for_i ;
write();
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " );
% initialise the "wrong" way %
for i := 1 until numberOfElements do begin
tArray( i ) := singleT;
m(tArray( i )) := m(tArray( i )) + 1;
end for_i ;
write();
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " )
end
end. |
http://rosettacode.org/wiki/Multiple_distinct_objects | Multiple distinct objects | Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By initialized we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the same mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: Closures/Value capture
| #AppleScript | AppleScript | -- MULTIPLE DISTINCT OBJECTS -------------------------------------------------
-- nObjects Constructor -> Int -> [Object]
on nObjects(f, n)
map(f, enumFromTo(1, n))
end nObjects
-- TEST ----------------------------------------------------------------------
on run
-- someConstructor :: a -> Int -> b
script someConstructor
on |λ|(_, i)
{index:i}
end |λ|
end script
nObjects(someConstructor, 6)
--> {{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}}
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/N-queens_problem | N-queens problem |
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN.
For the number of solutions for small values of N, see OEIS: A000170.
Related tasks
A* search algorithm
Solve a Hidato puzzle
Solve a Holy Knight's tour
Knight's tour
Peaceful chess queen armies
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #CoffeeScript | CoffeeScript |
# Unlike traditional N-Queens solutions that use recursion, this
# program attempts to more closely model the "human" algorithm.
#
# In this algorithm, the function keeps placing queens on the board
# until there is no longer a safe square. If the 8th queen has been
# placed, the solution is noted. If fewer than 8th queens have been
# placed, then you are at a dead end. In either case, backtracking occurs.
# The LAST queen placed on the board gets pulled, then it gets moved
# to the next safe square. (We backtrack even after a "good" attempt in
# order to get to a new solution.) This backtracking may repeat itself
# several times until the original misplaced queen finally is proven to
# be a dead end.
#
# Many N-Queens solutions use lazy logic (along with geometry shortcuts)
# to determine whether a queen is under attack. In this algorithm, we
# are more proactive, essentially updating a sieve every time we lay a
# queen down. To make backtracking easier, the sieve uses ref-counts vs.
# a simple safe/unsafe boolean.
#
# We precompute the "attack graph" up front, and then we essentially ignore
# the geometry of the problem. This approach, while perhaps suboptimal for
# queens, probably is more flexible for general "coexistence" problems.
nqueens = (n) ->
neighbors = precompute_neighbors(n)
board = []
num_solutions = 0
num_backtracks = 0
queens = []
pos = 0
for p in [0...n*n]
board.push 0
attack = (pos, delta=1) ->
for neighbor in neighbors[pos]
board[neighbor] += delta
backtrack = ->
pos = queens.pop()
attack pos, -1 # unattack queen you just pulled
pos += 1
num_backtracks += 1
# The following loop finds all 92 solutions to
# the 8-queens problem (for n=8).
while true
if pos >= n*n
if queens.length == 0
break
backtrack()
continue
# If a square is empty
if board[pos] == 0
attack pos
queens.push pos
if queens.length == n
num_solutions += 1
show_queens queens, n
backtrack()
pos += 1
console.log "#{num_solutions} solutions"
console.log "#{num_backtracks} backtracks"
precompute_neighbors = (n) ->
# For each board position, build a list of all
# the board positions that would be under attack if
# you placed a queen on it. This assumes a 1d array
# of squares.
neighbors = []
find_neighbors = (pos) ->
arr = []
row = Math.floor pos / n
col = pos % n
for i in [0...n]
if i != col
arr.push row*n + i
r1 = row + col - i
r2 = row + i - col
if 0 <= r1 and r1 < n
arr.push r1*n + i
if 0 <= r2 and r2 < n
arr.push r2*n + i
if i != row
arr.push i*n + col
arr
for pos in [0...n*n]
neighbors.push find_neighbors(pos)
neighbors
show_queens = (queens, n) ->
# precondition: queens is a sorted array of integers,
# and each row is represented
console.log "\n------"
for q in queens
col = q % n
s = ''
for c in [0...n]
if c == col
s += "Q "
else
s += "* "
console.log s + "\n"
nqueens(8)
|
http://rosettacode.org/wiki/Multiplicative_order | Multiplicative order | The multiplicative order of a relative to m is the least positive integer n such that a^n is 1 (modulo m).
Example
The multiplicative order of 37 relative to 1000 is 100 because 37^100 is 1 (modulo 1000), and no number smaller than 100 would do.
One possible algorithm that is efficient also for large numbers is the following: By the Chinese Remainder Theorem, it's enough to calculate the multiplicative order for each prime exponent p^k of m, and
combine the results with the least common multiple operation.
Now the order of a with regard to p^k must divide Φ(p^k). Call this number t, and determine it's factors q^e. Since each multiple of the order will also yield 1 when used as exponent for a, it's enough to find the least d such that (q^d)*(t/(q^e)) yields 1 when used as exponent.
Task
Implement a routine to calculate the multiplicative order along these lines. You may assume that routines to determine the factorization into prime powers are available in some library.
An algorithm for the multiplicative order can be found in Bach & Shallit, Algorithmic Number Theory, Volume I: Efficient Algorithms, The MIT Press, 1996:
Exercise 5.8, page 115:
Suppose you are given a prime p and a complete factorization
of p-1. Show how to compute the order of an
element a in (Z/(p))* using O((lg p)4/(lg lg p)) bit
operations.
Solution, page 337:
Let the prime factorization of p-1 be q1e1q2e2...qkek . We use the following observation:
if x^((p-1)/qifi) = 1 (mod p) ,
and fi=ei or x^((p-1)/qifi+1) != 1 (mod p) , then qiei-fi||ordp x. (This follows by combining Exercises 5.1 and 2.10.)
Hence it suffices to find, for each i , the exponent fi such that the condition above holds.
This can be done as follows: first compute q1e1, q2e2, ... ,
qkek . This can be done using O((lg p)2) bit operations. Next, compute y1=(p-1)/q1e1, ... , yk=(p-1)/qkek .
This can be done using O((lg p)2) bit operations. Now, using the binary method,
compute x1=ay1(mod p), ... , xk=ayk(mod p) .
This can be done using O(k(lg p)3) bit operations, and k=O((lg p)/(lg lg p)) by Theorem 8.8.10.
Finally, for each i , repeatedly raise xi to the qi-th power (mod p) (as many as ei-1 times), checking to see when 1 is obtained.
This can be done using O((lg p)3) steps.
The total cost is dominated by O(k(lg p)3) , which is O((lg p)4/(lg lg p)).
| #D | D | import std.bigint;
import std.random;
import std.stdio;
struct PExp {
BigInt prime;
int exp;
}
BigInt gcd(BigInt x, BigInt y) {
if (y == 0) {
return x;
}
return gcd(y, x % y);
}
/// https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
BigInt modPow(BigInt b, BigInt e, BigInt n) {
if (n == 1) return BigInt(0);
BigInt result = 1;
b = b % n;
while (e > 0) {
if (e % 2 == 1) {
result = (result * b) % n;
}
e >>= 1;
b = (b*b) % n;
}
return result;
}
BigInt pow(long b, long e) {
return pow(BigInt(b), BigInt(e));
}
BigInt pow(BigInt b, BigInt e) {
if (e == 0) {
return BigInt(1);
}
BigInt result = 1;
while (e > 1) {
if (e % 2 == 0) {
b *= b;
e /= 2;
} else {
result *= b;
b *= b;
e = (e - 1) / 2;
}
}
return b * result;
}
BigInt sqrt(BigInt self) {
BigInt b = self;
while (true) {
BigInt a = b;
b = self / a + a >> 1;
if (b >= a) return a;
}
}
long bitLength(BigInt self) {
BigInt bi = self;
long length;
while (bi != 0) {
length++;
bi >>= 1;
}
return length;
}
PExp[] factor(BigInt n) {
PExp[] pf;
BigInt nn = n;
int b = 0;
int e = 1;
while ((nn & e) == 0) {
e <<= 1;
b++;
}
if (b > 0) {
nn = nn >> b;
pf ~= PExp(BigInt(2), b);
}
BigInt s = nn.sqrt();
BigInt d = 3;
while (nn > 1) {
if (d > s) d = nn;
e = 0;
while (true) {
BigInt div, rem;
nn.divMod(d, div, rem);
if (rem.bitLength > 0) break;
nn = div;
e++;
}
if (e > 0) {
pf ~= PExp(d, e);
s = nn.sqrt();
}
d += 2;
}
return pf;
}
BigInt moBachShallit58(BigInt a, BigInt n, PExp[] pf) {
BigInt n1 = n - 1;
BigInt mo = 1;
foreach(pe; pf) {
BigInt y = n1 / pe.prime.pow(BigInt(pe.exp));
int o = 0;
BigInt x = a.modPow(y, n);
while (x > 1) {
x = x.modPow(pe.prime, n);
o++;
}
BigInt o1 = pe.prime.pow(BigInt(o));
o1 = o1 / gcd(mo, o1);
mo = mo * o1;
}
return mo;
}
void moTest(ulong a, ulong n) {
moTest(BigInt(a), n);
}
void moTest(BigInt a, ulong n) {
// Commented out because the implementations tried all failed for the -2 and -3 tests.
// if (!n.isProbablePrime()) {
// writeln("Not computed. Modulus must be prime for this algorithm.");
// return;
// }
if (a.bitLength < 100) {
write("ord(", a, ")");
} else {
write("ord([big])");
}
write(" mod ", n, " ");
BigInt nn = n;
BigInt mob = moBachShallit58(a, nn, factor(nn - 1));
writeln("= ", mob);
}
void main() {
moTest(37, 3343);
moTest(pow(10, 100) + 1, 7919);
moTest(pow(10, 1000) + 1, 15485863);
moTest(pow(10, 10000) - 1, 22801763489);
moTest(1511678068, 7379191741);
moTest(3047753288, 2257683301);
} |
http://rosettacode.org/wiki/Nth_root | Nth root | Task
Implement the algorithm to compute the principal nth root
A
n
{\displaystyle {\sqrt[{n}]{A}}}
of a positive real number A, as explained at the Wikipedia page.
| #Perl | Perl | use strict;
sub nthroot ($$)
{
my ( $n, $A ) = @_;
my $x0 = $A / $n;
my $m = $n - 1.0;
while(1) {
my $x1 = ($m * $x0 + $A / ($x0 ** $m)) / $n;
return $x1 if abs($x1 - $x0) < abs($x0 * 1e-9);
$x0 = $x1;
}
} |
http://rosettacode.org/wiki/N%27th | N'th | Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix.
Example
Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th
Task
Use your routine to show here the output for at least the following (inclusive) ranges of integer inputs:
0..25, 250..265, 1000..1025
Note: apostrophes are now optional to allow correct apostrophe-less English.
| #GW-BASIC | GW-BASIC |
10 ' N'th
20 LET LOLIM% = 0
30 LET HILIM% = 25
40 GOSUB 1000
50 LET LOLIM% = 250
60 LET HILIM% = 265
70 GOSUB 1000
80 LET LOLIM% = 1000
90 LET HILIM% = 1025
100 GOSUB 1000
110 END
995 ' Print images
1000 FOR I% = LOLIM% TO HILIM%
1010 LET NR% = I%
1020 GOSUB 1500
1030 LET SI$ = STR$(I%)
1040 PRINT RIGHT$(SI$, LEN(SI$) - 1); SUF$; " ";
1050 NEXT I%
1060 PRINT
1070 RETURN
1495 ' Get suffix
1500 IF (NR% MOD 10 = 1) AND (NR% MOD 100 <> 11) THEN LET SUF$ = "st": GOTO 2000
1600 IF (NR% MOD 10 = 2) AND (NR% MOD 100 <> 12) THEN LET SUF$ = "nd": GOTO 2000
1700 IF (NR% MOD 10 = 3) AND (NR% MOD 100 <> 13) THEN LET SUF$ = "rd": GOTO 2000
1800 LET SUF$ = "th"
2000 RETURN
|
http://rosettacode.org/wiki/Non-decimal_radices/Convert | Non-decimal radices/Convert | Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisible to the user, who normally enters or sees stored integers as decimal.
Task
Write a function (or identify the built-in function) which is passed a non-negative integer to convert, and another integer representing the base.
It should return a string containing the digits of the resulting number, without leading zeros except for the number 0 itself.
For the digits beyond 9, one should use the lowercase English alphabet, where the digit a = 9+1, b = a+1, etc.
For example: the decimal number 26 expressed in base 16 would be 1a.
Write a second function which is passed a string and an integer base, and it returns an integer representing that string interpreted in that base.
The programs may be limited by the word size or other such constraint of a given language. There is no need to do error checking for negatives, bases less than 2, or inappropriate digits.
| #Smalltalk | Smalltalk | 26 printStringRadix:16 -> '1A'
Integer readFrom:'1A' radix:16 -> 26
2 to:36 do:[:radix |
'radix %2d: %s\n' printf:{radix . 100 printStringRadix:radix } on:Transcript.
].
|
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.