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/P-Adic_square_roots | P-Adic square roots |
Task.
Convert rational a/b to its approximate p-adic square root. To check the result,
square the root and construct rational m/n to compare with radicand a/b.
For rational reconstruction Lagrange's lattice basis reduction algorithm is used.
Recipe: find root x1 modulo p and build a sequence of solutions
f(xk) ≡ 0 (mod pk),
using the lifting equation
xk+1 = xk + dk * pk
with dk = –(f(xk) / pk) /
f ′(x1) (mod p).
The multipliers dk are the successive p-adic digits to find.
If evaluation of f(x) = bx2 – a overflows,
the expansion is cut off and might be too short to retrieve the radicand.
Setting a higher precision won't help, using a programming language with built-in
large integer support will.
Related task.
p-Adic numbers, basic
Reference.
[1]
Solving x2 ≡ a (mod n)
| #Phix | Phix | constant EMX = 48 // exponent maximum (if indexing starts at -EMX)
constant DMX = 1e5 // approximation loop maximum
constant AMX = 700000 // argument maximum
constant PMAX = 32749 // prime maximum
// global variables
integer p1 = 0
integer p = 7 // default prime
integer k = 11 // precision
type Ratio(sequence r)
return length(r)=2 and integer(r[1]) and integer(r[2])
end type
class Padic
integer v = 0
sequence d = repeat(0,EMX*2)
function square_root(Ratio g, integer sw)
-- p-adic square root of g = a/b
integer {a,b} = g
atom f, q, pk, x
integer f1, r, s, t, i, res = 0
if b = 0 then return 1 end if
if b < 0 then
b = -b
a = -a
end if
if p < 2 or k < 1 then return 1 end if
-- max. short prime
p = min(p, PMAX)
if sw then
-- numerator, denominator, prime, precision
printf(1,"%d/%d + O(%d^%d)\n",{a,b,p,k})
end if
-- initialize
v = 0
p1 = p - 1
sequence ntd = repeat(0,2*EMX) -- (new this.d)
if a = 0 then return 0 end if
-- valuation
while remainder(b,p)=0 do
b /= p
v -= 1
end while
while remainder(a,p)=0 do
a /= p
v += 1
end while
if remainder(v,2) then
-- odd valuation
printf(1,"(1)non-residue mod %d\n",p)
return -1
end if
-- max. array length
k = min(k + v, EMX - 1) - v
v = floor(v/2)
if abs(a) > AMX or b > AMX then return -1 end if
if p = 2 then
--1 / b = b (mod 8)
--a / b = 1 (mod 8)
t = a * b
if mod(t,8)-1 then
printf(1,"(2)non-residue mod 8\n")
return -1
end if
else
-- find root for small p
for r = 1 to p1 do
f = b * r * r - a
if mod(f,p) = 0 then exit end if
end for
if r = p then
printf(1,"(3)non-residue mod %d\n", p)
return -1
end if
-- f'(r) = 2br
t = b * r * 2
s = 0
t = mod(t,p)
-- modular inverse for small p
for f1 = 1 to p1 do
s += t
if s > p1 then s -= p end if
if s = 1 then exit end if
end for
if f1 = p then
printf(1,"impossible inverse mod\n")
return -1
end if
end if
if p = 2 then
-- initialize
x = 1
ntd[v+EMX+1] = 1
ntd[v+EMX+2] = 0
pk = 4
for i = v+2 to k-1+v do
pk *= 2
f = b * x * x - a
q = floor(f/pk)
-- overflow
if f != q * pk then exit end if
-- next digit
ntd[i+EMX+1] = and_bits(q,1)
-- lift x
x += ntd[i+EMX+1] * floor(pk/2)
end for
else
-- -1 / f'(x) mod p
f1 = p - f1
x = r
ntd[v+EMX+1] = x
pk = 1
for i = v+1 to k-1 do
pk *= p
f = b * x * x - a
q = floor(f/pk)
-- overflow
if f - q * pk then exit end if
r = mod(q*f1,p)
if r < 0 then r += p end if
ntd[i+EMX+1] = r
x += r * pk
end for
end if
this.d = ntd
k = i-v
if sw then
printf(1,"lift: %d mod %d^%d\n",{x,p,k})
end if
return 0
end function
function square()
integer c = 0
Padic r = new()
r.v = this.v * 2
sequence td = this.d,
rd = r.d
for i=0 to k do
for j=0 to i do
c += td[v+j+EMX+1] * td[v+i-j+EMX+1]
end for
// Euclidean step
integer q = floor(c/p)
rd[r.v+i+EMX+1] = c - q*p
c = q
end for
r.d = rd
return r
end function
function complement()
integer c = 1
Padic r = new({v})
sequence rd = r.d
for i=v to k+v do
integer dx = i+EMX+1
c += p1 - this.d[dx]
if c>p1 then
rd[dx] = c - p
c = 1
else
rd[dx] = c
c = 0
end if
end for
r.d = rd
return r
end function
function crat(integer sw)
-- rational reconstruction
integer i, j, t = min(v, 0)
Ratio r
atom f
integer x, y
atom p1,pk, q, s
-- weighted digit sum
s = 0
pk = 1
for i = t to k-1+v do
p1 = pk
pk *= p
if floor(pk/p1) - p then
-- overflow
pk = p1
exit
end if
s += d[i+EMX+1] * p1 --(mod pk)
end for
-- lattice basis reduction
sequence m = {pk, s},
n = {0, 1}
i = 1
j = 2
s = s * s + 1 -- norm(v)^2
-- Lagrange's algorithm
while true do
f = (m[i] * m[j] + n[i] * n[j]) / s
-- Euclidean step
q = floor(f +.5)
m[i] -= q * m[j]
n[i] -= q * n[j]
q = s
s = m[i] * m[i] + n[i] * n[i]
-- compare norms
if s < q then
-- interchange vectors
{i,j} = {j,i}
else
exit
end if
end while
x = m[j]
y = n[j]
if y < 0 then
y = -y
x = -x
end if
-- check determinant
t = abs(m[i] * y - x * n[i]) == pk
if not t then
printf(1,"crat: fail\n")
x = 0
y = 1
else
-- negative powers
for i = v to -1 do
y *= p
end for
if sw then
-- printf(1,iff(y=1?"%d":"%d/%d"),{x*sgn,y})
printf(1,iff(y=1?"%d\n":"%d/%d\n"),{x,y})
end if
end if
r = {x,y}
return r
end function
procedure prntf(bool sw)
-- print expansion
integer t = min(v, 0)
for i=k-1+t to t by -1 do
printf(1,"%d",d[i+EMX+1])
printf(1,iff(i=0 and v<0?". ":" "))
end for
printf(1,"\n")
// rational approximation
if sw then crat(sw) end if
end procedure
end class
constant tests = {
{{-7,1},2,7},
--/*
{{9,1},2,8},
{{17,1},2,9},
{{497,10496},2,18},
{{10496,497},2,19},
{{3141,5926},3,17},
{{2718,281},3,15},
{{-1,1},5,8},
{{86,25},5,8},
{{2150,1},5,10},
{{2,1},7,8},
{{-2645,28518},7,9},
{{3029,4821},7,9},
{{379,449},7,8},
{{717,8},11,7},
{{1414,213},41,5},
--*/
{{-255,256},257,3}
}
Padic a = new(), c
Ratio q, r
for i=1 to length(tests) do
{q,p,k} = tests[i]
integer sw = a.square_root(q, 1)
if sw=1 then exit end if
if sw=0 then
printf(1,"square_root +/-\n")
printf(1,"... ")
a.prntf(0)
a = a.complement()
printf(1,"... ")
a.prntf(0)
c = a.square()
printf(1,"square_root^2\n")
printf(1," ")
c.prntf(0)
r = c.crat(1)
if q[1] * r[2] - r[1] * q[2] then
printf(1,"fail: square_root^2\n")
end if
end if
printf(1,"\n")
end for |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Lua | Lua |
function nextrow(t)
local ret = {}
t[0], t[#t+1] = 0, 0
for i = 1, #t do ret[i] = t[i-1] + t[i] end
return ret
end
function triangle(n)
t = {1}
for i = 1, n do
print(unpack(t))
t = nextrow(t)
end
end
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.23 | F# | let isPalindrome (s: string) =
let arr = s.ToCharArray()
arr = Array.rev arr |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #REXX | REXX | /*REXX program verifies if an entered/supplied string (sentence) is a pangram. */
@abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*a list of all (Latin) capital letters*/
do forever; say /*keep promoting 'til null (or blanks).*/
say '──────── Please enter a pangramic sentence (or a blank to quit):'; say
pull y /*this also uppercases the Y variable.*/
if y='' then leave /*if nothing entered, then we're done.*/
absent= space( translate( @abc, , y), 0) /*obtain a list of any absent letters. */
if absent=='' then say "──────── Sentence is a pangram."
else say "──────── Sentence isn't a pangram, missing: " absent
say
end /*forever*/
say '──────── PANGRAM program ended. ────────' /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Ring | Ring |
pangram = 0
s = "The quick brown fox jumps over the lazy dog."
see "" + pangram(s) + " " + s + nl
s = "My dog has fleas."
see "" + pangram(s) + " " + s + nl
func pangram str
str = lower(str)
for i = ascii("a") to ascii("z")
bool = substr(str, char(i)) > 0
pangram = pangram + bool
next
pan = (pangram = 26)
return pan
|
http://rosettacode.org/wiki/P-Adic_square_roots | P-Adic square roots |
Task.
Convert rational a/b to its approximate p-adic square root. To check the result,
square the root and construct rational m/n to compare with radicand a/b.
For rational reconstruction Lagrange's lattice basis reduction algorithm is used.
Recipe: find root x1 modulo p and build a sequence of solutions
f(xk) ≡ 0 (mod pk),
using the lifting equation
xk+1 = xk + dk * pk
with dk = –(f(xk) / pk) /
f ′(x1) (mod p).
The multipliers dk are the successive p-adic digits to find.
If evaluation of f(x) = bx2 – a overflows,
the expansion is cut off and might be too short to retrieve the radicand.
Setting a higher precision won't help, using a programming language with built-in
large integer support will.
Related task.
p-Adic numbers, basic
Reference.
[1]
Solving x2 ≡ a (mod n)
| #Wren | Wren | import "/dynamic" for Struct
import "/big" for BigInt
// constants
var EMX = 64 // exponent maximum (if indexing starts at -EMX)
var AMX = 6000 // argument maximum
var PMAX = 32749 // prime maximum
// global variables
var P1 = 0
var P = 7 // default prime
var K = 11 // precision
var Ratio = Struct.create("Ratio", ["a", "b"])
class Padic {
// uninitialized
construct new() {
_v = 0
_d = List.filled(2 * EMX, 0) // add EMX to index to be consistent wih FB
}
// properties
v { _v }
v=(o) { _v = o }
d { _d }
// (re)initialize 'this' to the square root of a Ratio, set 'sw' to print
sqrt(g, sw) {
var a = g.a
var b = g.b
if (b == 0) return 1
if (b < 0) {
b = -b
a = -a
}
if (P < 2 || K < 1) return 1
P = P.min(PMAX) // maximum short prime
if (sw != 0) {
System.write("%(a)/%(b) + ") // numerator, denominator
System.print("0(%(P)^%(K))") // prime, precision
}
// (re)initialize
_v = 0
P1 = P - 1
_d = List.filled(2 * EMX, 0)
if (a == 0) return 0
//valuation
while (b%P== 0) {
b = (b/P).truncate
_v = _v - 1
}
while (a%P == 0) {
a = (a/P).truncate
_v = _v + 1
}
if ((_v & 1) == 1) {
// odd valuation
System.print("non-residue mod %(P)")
return -1
}
K = (K + _v).min(EMX - 1) - _v // maximum array length
_v = (_v/2).truncate
if (a.abs > AMX || b > AMX) return -1
var bb = BigInt.new(b) // to avoid overflowing 'f(x) = b * x * x – a'
var r
var s
var t
var f
var f1
if (P == 2) {
t = a * b
if ((t & 7) - 1 != 0) {
System.print("non-residue mod 8")
return -1
}
} else {
// find root for small P
r = 1
while (r <= P1) {
f = bb * r * r - a
if ((f % P) == 0) break
r = r + 1
}
if (r == P) {
System.print("non-residue mod %(P)")
return -1
}
t = 2 * b * r
s = 0
t = t % P
// modular inverse for small P
f1 = 1
while (f1 <= P1) {
s = s + t
if (s > P1) s = s - P
if (s == 1) break
f1 = f1 + 1
}
if (f1 == P) {
System.print("impossible inverse mod")
return -1
}
}
var x
var pk
var q
var i
if (P == 2) {
// initialize
x = 1
_d[_v+EMX] = 1
_d[_v+1+EMX] = 0
pk = 4
i = _v + 2
while (i <= K - 1 + _v) {
pk = pk * 2
f = bb * x * x - a
q = f / pk
// overflow
if (f != q * pk) break
// next digit
_d[i+EMX] = ((q & 1) != 0) ? 1 : 0
// lift x
x = x + _d[i+EMX]*(pk >> 1)
i = i + 1
}
} else {
f1 = P - f1
x = r
_d[_v+EMX] = x
pk = 1
i = _v + 1
while (i <= K - 1 + _v) {
pk = pk * P
f = bb * x * x - a
q = f / pk
// overflow
if (f != q * pk) break
_d[i+EMX] = q.toSmall * f1 % P
if (_d[i+EMX] < 0) _d[i+EMX] = _d[i+EMX] + P
x = x + _d[i+EMX]*pk
i = i + 1
}
}
K = i - _v
if (sw != 0) System.print("lift: %(x) mod %(P)^%(K)")
return 0
}
// rational reconstruction
crat(sw) {
var t = _v.min(0)
// weighted digit sum
var s = 0
var pk = 1
for (i in t..K-1+_v) {
P1 = pk
pk = pk * P
if (((pk/P1).truncate - P) != 0) {
// overflow
pk = p1
break
}
s = s + _d[i+EMX]*P1
}
// lattice basis reduction
var m = [pk, s]
var n = [0, 1]
var i = 0
var j = 1
s = s * s + 1
// Lagrange's algorithm
while (true) {
var f = (m[i] * m[j] + n[i] * n[j]) / s
// Euclidean step
var q = (f + 0.5).floor
m[i] = m[i] - q*m[j]
n[i] = n[i] - q*n[j]
q = s
s = m[i] * m[i] + n[i] * n[i]
// compare norms
if (s < q) {
// interchange vectors
var z = i
i = j
j = z
} else {
break
}
}
var x = m[j]
var y = n[j]
if (y < 0) {
y = -y
x = -x
}
// check determinant
t = (m[i]*y - x*n[i]).abs == pk
if (!t) {
System.print("crat: fail")
x = 0
y = 1
} else {
// negative powers
var i = _v
while (i <= -1) {
y = y * P
i = i + 1
}
if (sw != 0) {
System.write(x)
if (y > 1) System.write("/%(y)")
System.print()
}
}
return Ratio.new(x, y)
}
// print expansion
printf(sw) {
var t = _v.min(0)
for (i in K - 1 + t..t) {
System.write(_d[i + EMX])
if (i == 0 && _v < 0) System.write(".")
System.write(" ")
}
System.print()
// rational approximation
if (sw != 0) crat(sw)
}
// complement
cmpt {
var c = 1
var r = Padic.new()
r.v = _v
for (i in r.v..K + r.v) {
c = c + P1 - _d[i+EMX]
if (c > P1) {
r.d[i+EMX] = c - P
c = 1
} else {
r.d[i+EMX] = c
c = 0
}
}
return r
}
// square
sqr {
var c = 0
var r = Padic.new()
r.v = _v * 2
for (i in 0..K) {
for (j in 0..i) c = c + _d[_v+j+EMX] * _d[_v+i-j+EMX]
// Euclidean step
var q = (c/P).truncate
r.d[r.v+i+EMX] = c - q*P
c = q
}
return r
}
}
var data = [
[-7, 1, 2, 7],
[9, 1, 2, 8],
[17, 1, 2, 9],
[497, 10496, 2, 18],
[10496, 497, 2, 19],
[3141, 5926, 3, 15],
[2718, 281, 3, 13],
[-1, 1, 5, 8],
[86, 25, 5, 8],
[2150, 1, 5, 8],
[2,1, 7, 8],
[-2645, 28518, 7, 9],
[3029, 4821, 7, 9],
[379, 449, 7, 8],
[717, 8, 11, 7],
[1414, 213, 41, 5],
[-255, 256, 257, 3]
]
var sw = 0
var a = Padic.new()
var c = Padic.new()
for (d in data) {
var q = Ratio.new(d[0], d[1])
P = d[2]
K = d[3]
sw = a.sqrt(q, 1)
if (sw == 1) break
if (sw == 0) {
System.print("sqrt +/-")
System.write("...")
a.printf(0)
a = a.cmpt
System.write("...")
a.printf(0)
c = a.sqr
System.print("sqrt^2")
System.write(" ")
c.printf(0)
var r = c.crat(1)
if (q.a * r.b - r.a * q.b != 0) {
System.print("fail: sqrt^2")
}
System.print()
}
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Maple | Maple | f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);
f(3); |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: kernel sequences ;
: palindrome? ( str -- ? ) dup reverse = ; |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Ruby | Ruby | def pangram?(sentence)
s = sentence.downcase
('a'..'z').all? {|char| s.include? (char) }
end
p pangram?('this is a sentence') # ==> false
p pangram?('The quick brown fox jumps over the lazy dog.') # ==> true |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Run_BASIC | Run BASIC | s$ = "The quick brown fox jumps over the lazy dog."
Print pangram(s$);" ";s$
s$ = "My dog has fleas."
Print pangram(s$);" ";s$
function pangram(str$)
str$ = lower$(str$)
for i = asc("a") to asc("z")
pangram = pangram + (instr(str$, chr$(i)) <> 0)
next i
pangram = (pangram = 26)
end function |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | n=7;
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center] |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Falcon | Falcon |
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
function is_palindrome(a)
a = strUpper(a).replace(" ", "")
b = a[-1:0]
return b == a
end
a = "mom"
> is_palindrome(a)
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Rust | Rust | #![feature(test)]
extern crate test;
use std::collections::HashSet;
pub fn is_pangram_via_bitmask(s: &str) -> bool {
// Create a mask of set bits and convert to false as we find characters.
let mut mask = (1 << 26) - 1;
for chr in s.chars() {
let val = chr as u32 & !0x20; /* 0x20 converts lowercase to upper */
if val <= 'Z' as u32 && val >= 'A' as u32 {
mask = mask & !(1 << (val - 'A' as u32));
}
}
mask == 0
}
pub fn is_pangram_via_hashset(s: &str) -> bool {
// Insert lowercase letters into a HashSet, then check if we have at least 26.
let letters = s.chars()
.flat_map(|chr| chr.to_lowercase())
.filter(|&chr| chr >= 'a' && chr <= 'z')
.fold(HashSet::new(), |mut letters, chr| {
letters.insert(chr);
letters
});
letters.len() == 26
}
pub fn is_pangram_via_sort(s: &str) -> bool {
// Copy chars into a vector, convert to lowercase, sort, and remove duplicates.
let mut chars: Vec<char> = s.chars()
.flat_map(|chr| chr.to_lowercase())
.filter(|&chr| chr >= 'a' && chr <= 'z')
.collect();
chars.sort();
chars.dedup();
chars.len() == 26
}
fn main() {
let examples = ["The quick brown fox jumps over the lazy dog",
"The quick white cat jumps over the lazy dog"];
for &text in examples.iter() {
let is_pangram_sort = is_pangram_via_sort(text);
println!("Is \"{}\" a pangram via sort? - {}", text, is_pangram_sort);
let is_pangram_bitmask = is_pangram_via_bitmask(text);
println!("Is \"{}\" a pangram via bitmask? - {}",
text,
is_pangram_bitmask);
let is_pangram_hashset = is_pangram_via_hashset(text);
println!("Is \"{}\" a pangram via bitmask? - {}",
text,
is_pangram_hashset);
}
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Scala | Scala | def is_pangram(sentence: String) = sentence.toLowerCase.filter(c => c >= 'a' && c <= 'z').toSet.size == 26
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #MATLAB_.2F_Octave | MATLAB / Octave | pascal(n); |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fantom | Fantom |
class Palindrome
{
// Function to test if given string is a palindrome
public static Bool isPalindrome (Str str)
{
str == str.reverse
}
// Give it a test run
public static Void main ()
{
echo (isPalindrome(""))
echo (isPalindrome("a"))
echo (isPalindrome("aa"))
echo (isPalindrome("aba"))
echo (isPalindrome("abb"))
echo (isPalindrome("salàlas"))
echo (isPalindrome("In girum imus nocte et consumimur igni".lower.replace(" ","")))
}
}
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: isPangram (in string: stri) is func
result
var boolean: isPangram is FALSE;
local
var char: ch is ' ';
var set of char: usedChars is (set of char).value;
begin
for ch range lower(stri) do
if ch in {'a' .. 'z'} then
incl(usedChars, ch);
end if;
end for;
isPangram := usedChars = {'a' .. 'z'};
end func;
const proc: main is func
begin
writeln(isPangram("This is a test"));
writeln(isPangram("The quick brown fox jumps over the lazy dog"));
writeln(isPangram("NOPQRSTUVWXYZ abcdefghijklm"));
writeln(isPangram("abcdefghijklopqrstuvwxyz")); # Missing m, n
end func; |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Sidef | Sidef | define Eng = 'a'..'z';
define Hex = 'a'..'f';
define Cyr = %w(а б в г д е ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я ё);
func pangram(str, alpha=Eng) {
var lstr = str.lc;
alpha.all {|c| lstr.contains(c) };
}
say pangram("The quick brown fox jumps over the lazy dog.");
say pangram("My dog has fleas.");
say pangram("My dog has fleas.", Hex);
say pangram("My dog backs fleas.", Hex);
say pangram("Съешь же ещё этих мягких французских булок, да выпей чаю", Cyr); |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Maxima | Maxima | sjoin(v, j) := apply(sconcat, rest(join(makelist(j, length(v)), v)))$
display_pascal_triangle(n) := for i from 0 thru 6 do disp(sjoin(makelist(binomial(i, j), j, 0, i), " "));
display_pascal_triangle(6);
/* "1"
"1 1"
"1 2 1"
"1 3 3 1"
"1 4 6 4 1"
"1 5 10 10 5 1"
"1 6 15 20 15 6 1" */ |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING
DIM sTemp AS STRING = ""
DIM c AS STRING
FOR DIM i = 1 TO LEN(s)
c = MID(s, i, 1)
IF INSTR("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c, 0, 1) THEN
sTemp = stemp & c
END IF
NEXT
RETURN sTemp
END FUNCTION
FUNCTION IsPalindrome(BYVAL s AS STRING) AS INTEGER
FOR DIM i = 1 TO STRLEN(s) \ 2 ' only check half of the string, as scanning from both ends
IF s{i} <> s{STRLEN - (i - 1)} THEN RETURN FALSE 'comparison is not case sensitive
NEXT
RETURN TRUE
END FUNCTION
PRINT IsPalindrome(stripNonAlpha("A Toyota"))
PRINT IsPalindrome(stripNonAlpha("Madam, I'm Adam"))
PRINT IsPalindrome(stripNonAlpha("the rain in Spain falls mainly on the rooftops"))
PAUSE
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Smalltalk | Smalltalk | !String methodsFor: 'testing'!
isPangram
^((self collect: [:c | c asUppercase]) select: [:c | c >= $A and: [c <= $Z]]) asSet size = 26
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #SNOBOL4 | SNOBOL4 | define('pangram(str)alfa,c') :(pangram_end)
pangram str = replace(str,&ucase,&lcase)
alfa = &lcase
pgr_1 alfa len(1) . c = :f(return)
str c :s(pgr_1)f(freturn)
pangram_end
define('panchk(str)tf') :(panchk_end)
panchk output = str
tf = 'False'; tf = pangram(str) 'True'
output = 'Pangram: ' tf :(return)
panchk_end
* # Test and display
panchk("The quick brown fox jumped over the lazy dogs.")
panchk("My girl wove six dozen plaid jackets before she quit.")
panchk("This 41-character string: it's a pangram!")
end |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #11l | 11l | F rn(n, k) -> [Int]
assert(k >= 2)
V result = I n == 2 {[1, 1, 1]} E rn(n - 1, n + 1)
L result.len != k
result.append(sum(result[(len)-n-1 .< (len)-1]))
R result
L(n) 2..8
print(n‘: ’rn(n, 15).map(it -> ‘#3’.format(it)).join(‘ ’)) |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Metafont | Metafont | vardef bincoeff(expr n, k) =
save ?;
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
/ (1 for i=2 upto min(k, n-k): * i endfor); ?
enddef;
def pascaltr expr c =
string s_;
for i := 0 upto (c-1):
s_ := "" for k=0 upto (c-i): & " " endfor;
s_ := s_ for k=0 upto i: & decimal(bincoeff(i,k))
& " " if bincoeff(i,k)<9: & " " fi endfor;
message s_;
endfor
enddef;
pascaltr(4);
end |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Forth | Forth | : first over c@ ;
: last >r 2dup + 1- c@ r> swap ;
: palindrome? ( c-addr u -- f )
begin
dup 1 <= if 2drop true exit then
first last <> if 2drop false exit then
1 /string 1-
again ;
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Swift | Swift | import Foundation
let str = "the quick brown fox jumps over the lazy dog"
func isPangram(str:String) -> Bool {
let stringArray = Array(str.lowercaseString)
for char in "abcdefghijklmnopqrstuvwxyz" {
if (find(stringArray, char) == nil) {
return false
}
}
return true
}
isPangram(str) // True
isPangram("Test string") // False |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #ALGOL_68 | ALGOL 68 | BEGIN # show some valuies of the Padovan n-step number sequences #
# returns an array with the elements set to the elements of #
# the Padovan sequences from 2 to max s & elements 1 to max e #
# max s must be >= 2 #
PROC padovan sequences = ( INT max s, max e )[,]INT:
BEGIN
PRIO MIN = 1;
OP MIN = ( INT a, b )INT: IF a < b THEN a ELSE b FI;
# sequence 2 #
[ 2 : max s, 1 : max e ]INT r;
FOR x TO max e MIN 3 DO r[ 2, x ] := 1 OD;
FOR x FROM 4 TO max e DO r[ 2, x ] := r[ 2, x - 2 ] + r[ 2, x - 3 ] OD;
# sequences 3 and above #
FOR n FROM 3 TO max s DO
FOR x TO max e MIN n + 1 DO r[ n, x ] := r[ n - 1, x ] OD;
FOR x FROM n + 2 TO max e DO
r[ n, x ] := 0;
FOR p FROM x - n - 1 TO x - 2 DO r[ n, x ] +:= r[ n, p ] OD
OD
OD;
r
END # padovan sequences # ;
# calculate and show the sequences #
[,]INT r = padovan sequences( 8, 15 );
print( ( "Padovan n-step sequences:", newline ) );
FOR n FROM 1 LWB r TO 1 UPB r DO
print( ( whole( n, 0 ), " |" ) );
FOR x FROM 2 LWB r TO 2 UPB r DO print( ( " ", whole( r[ n, x ], -3 ) ) ) OD;
print( ( newline ) )
OD
END |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Microsoft_Small_Basic | Microsoft Small Basic |
TextWindow.Write("Number of rows? ")
r = TextWindow.ReadNumber()
For i = 0 To r - 1
c = 1
For k = 0 To i
TextWindow.CursorLeft = (k + 1) * 4 - Text.GetLength(c)
TextWindow.Write(c)
c = c * (i - k) / (k + 1)
EndFor
TextWindow.WriteLine("")
EndFor
|
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #FreeBASIC | FreeBASIC |
' ***********************************************
'subject: convert two rationals to p-adic numbers,
' add them up and show the result.
'tested : FreeBasic 1.07.0
'you can change this:
const emx = 64
'exponent maximum
const dmx = 100000
'approximation loop maximum
'better not change
'------------------------------------------------
const amx = 1048576
'argument maximum
const Pmax = 32749
'max. prime < 2^15
type ratio
as longint a, b
end type
type padic
declare function r2pa (byref q as ratio, byval sw as integer) as integer
'convert q = a/b to p-adic number, set sw to print
declare sub printf (byval sw as integer)
'print expansion, set sw to print rational
declare sub crat ()
'rational reconstruction
declare sub add (byref a as padic, byref b as padic)
'let self:= a + b
declare sub cmpt (byref a as padic)
'let self:= complement_a
declare function dsum () as long
'weighted digit sum
as long d(-emx to emx - 1)
as integer v
end type
'global variables
dim shared as long p1, p = 7
'default prime
dim shared as integer k = 11
'precision
#define min(a, b) iif((a) > (b), b, a)
'------------------------------------------------
'convert rational a/b to p-adic number
function padic.r2pa (byref q as ratio, byval sw as integer) as integer
dim as longint a = q.a, b = q.b
dim as long r, s, b1
dim i as integer
r2pa = 0
if b = 0 then return 1
if b < 0 then b = -b: a = -a
if abs(a) > amx or b > amx then return -1
if p < 2 or k < 1 then return 1
'max. short prime
p = min(p, Pmax)
'max. array length
k = min(k, emx - 1)
if sw then
'echo numerator, denominator,
print a;"/";str(b);" + ";
'prime and precision
print "O(";str(p);"^";str(k);")"
end if
'initialize
v = 0
p1 = p - 1
for i = -emx to emx - 1
d(i) = 0: next
if a = 0 then return 0
i = 0
'find -exponent of p in b
do until b mod p
b \= p: i -= 1
loop
s = 0
r = b mod p
'modular inverse for small p
for b1 = 1 to p1
s += r
if s > p1 then s -= p
if s = 1 then exit for
next b1
if b1 = p then
print "r2pa: impossible inverse mod"
return -1
end if
v = emx
do
'find exponent of p in a
do until a mod p
a \= p: i += 1
loop
'valuation
if v = emx then v = i
'upper bound
if i >= emx then exit do
'check precision
if (i - v) > k then exit do
'next digit
d(i) = a * b1 mod p
if d(i) < 0 then d(i) += p
'remainder - digit * divisor
a -= d(i) * b
loop while a
end function
'------------------------------------------------
'Horner's rule
function padic.dsum () as long
dim as integer i, t = min(v, 0)
dim as long r, s = 0
for i = k - 1 + t to t step -1
r = s: s *= p
if r andalso s \ r - p then
'overflow
s = -1: exit for
end if
s += d(i)
next i
return s
end function
#macro pint(cp)
for j = k - 1 + v to v step -1
if cp then exit for
next j
fl = ((j - v) shl 1) < k
#endmacro
'rational reconstruction
sub padic.crat ()
dim as integer i, j, fl
dim as padic s = this
dim as long x, y
'denominator count
for i = 1 to dmx
'check for integer
pint(s.d(j))
if fl then fl = 0: exit for
'check negative integer
pint(p1 - s.d(j))
if fl then exit for
'repeatedly add self to s
s.add(s, this)
next i
if fl then s.cmpt(s)
'numerator: weighted digit sum
x = s.dsum: y = i
if x < 0 or y > dmx then
print "crat: fail"
else
'negative powers
for i = v to -1
y *= p: next
'negative rational
if fl then x = -x
print x;
if y > 1 then print "/";str(y);
print
end if
end sub
'print expansion
sub padic.printf (byval sw as integer)
dim as integer i, t = min(v, 0)
for i = k - 1 + t to t step -1
print d(i);
if i = 0 andalso v < 0 then print ".";
next i
print
'rational approximation
if sw then crat
end sub
'------------------------------------------------
'carry
#macro cstep(dt)
if c > p1 then
dt = c - p: c = 1
else
dt = c: c = 0
end if
#endmacro
'let self:= a + b
sub padic.add (byref a as padic, byref b as padic)
dim i as integer, r as padic
dim as long c = 0
with r
.v = min(a.v, b.v)
for i = .v to k +.v
c += a.d(i) + b.d(i)
cstep(.d(i))
next i
end with
this = r
end sub
'let self:= complement_a
sub padic.cmpt (byref a as padic)
dim i as integer, r as padic
dim as long c = 1
with r
.v = a.v
for i = .v to k +.v
c += p1 - a.d(i)
cstep(.d(i))
next i
end with
this = r
end sub
'main
'------------------------------------------------
dim as integer sw
dim as padic a, b, c
dim q as ratio
width 64, 30
cls
'rational reconstruction
'depends on the precision -
'until the dsum-loop overflows.
data 2,1, 2,4
data 1,1
data 4,1, 2,4
data 3,1
data 4,1, 2,5
data 3,1
' 4/9 + O(5^4)
data 4,9, 5,4
data 8,9
data 26,25, 5,4
data -109,125
data 49,2, 7,6
data -4851,2
data -9,5, 3,8
data 27,7
data 5,19, 2,12
data -101,384
'two 'decadic' pairs
data 2,7, 10,7
data -1,7
data 34,21, 10,9
data -39034,791
'familiar digits
data 11,4, 2,43
data 679001,207
data -8,9, 23,9
data 302113,92
data -22,7, 3,23
data 46071,379
data -22,7, 32749,3
data 46071,379
data 35,61, 5,20
data 9400,109
data -101,109, 61,7
data 583376,6649
data -25,26, 7,13
data 5571,137
data 1,4, 7,11
data 9263,2837
data 122,407, 7,11
data -517,1477
'more subtle
data 5,8, 7,11
data 353,30809
data 0,0, 0,0
print
do
read q.a,q.b, p,k
sw = a.r2pa(q, 1)
if sw = 1 then exit do
a.printf(0)
read q.a,q.b
sw or= b.r2pa(q, 1)
if sw = 1 then exit do
if sw then continue do
b.printf(0)
c.add(a, b)
print "+ ="
c.printf(1)
print : ?
loop
system
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fortran | Fortran | program palindro
implicit none
character(len=*), parameter :: p = "ingirumimusnocteetconsumimurigni"
print *, is_palindro_r(p)
print *, is_palindro_r("anothertest")
print *, is_palindro2(p)
print *, is_palindro2("test")
print *, is_palindro(p)
print *, is_palindro("last test")
contains |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Tcl | Tcl | proc pangram? {sentence} {
set letters [regexp -all -inline {[a-z]} [string tolower $sentence]]
expr {
[llength [lsort -unique $letters]] == 26
}
}
puts [pangram? "This is a sentence"]; # ==> false
puts [pangram? "The quick brown fox jumps over the lazy dog."]; # ==> true |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #TI-83_BASIC | TI-83 BASIC | :Prompt Str1
:For(L,1,26
:If not(inString(Str1,sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",L,1))
:L=28
:End
:If L<28
:Disp "IS A PANGRAM" |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #ALGOL_W | ALGOL W | begin % show some valuies of the Padovan n-step number sequences %
% sets R(i,j) to the jth element of the ith padovan sequence %
% maxS is the number of sequences to generate and maxE is the %
% maximum number of elements for each sequence %
% maxS must be >= 2 %
procedure PadovanSequences ( integer array R ( *, * )
; integer value maxS, maxE
) ;
begin
integer procedure min( integer value a, b ) ; if a < b then a else b;
% sequence 2 %
for x := 1 until min( maxE, 3 ) do R( 2, x ) := 1;
for x := 4 until maxE do R( 2, x ) := R( 2, x - 2 ) + R( 2, x - 3 );
% sequences 3 and above %
for N := 3 until maxS do begin
for x := 1 until min( maxE, N + 1 ) do R( N, x ) := R( N - 1, x );
for x := N + 2 until maxE do begin
R( N, x ) := 0;
for p := x - N - 1 until x - 2 do R( N, x ) := R( N, x ) + R( N, p )
end for_x
end for_N
end PadovanSequences ;
integer MAX_SEQUENCES, MAX_ELEMENTS;
MAX_SEQUENCES := 8;
MAX_ELEMENTS := 15;
begin % calculate and show the sequences %
% array to hold the Padovan Sequences %
integer array R ( 2 :: MAX_SEQUENCES, 1 :: MAX_ELEMENTS );
% construct the sequences %
PadovanSequences( R, MAX_SEQUENCES, MAX_ELEMENTS );
% show the sequences %
write( "Padovan n-step sequences:" );
for n := 2 until MAX_SEQUENCES do begin
write( i_w := 1, s_w := 0, n, " |" );
for x := 1 until MAX_ELEMENTS do writeon( i_w := 3, s_w := 0, " ", R( n, x ) )
end for_n
end
end. |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
------------------ PADOVAN N-STEP NUMBERS ----------------
-- padovans :: [Int]
on padovans(n)
script recurrence
on |λ|(xs)
{item 1 of xs, ¬
rest of xs & {sum(take(n, xs)) as integer}}
end |λ|
end script
if 3 > n then
set seed to |repeat|(1)
else
set seed to padovans(n - 1)
end if
if 0 > n then
{}
else
unfoldr(recurrence, take(1 + n, seed))
end if
end padovans
--------------------------- TEST -------------------------
on run
script nSample
on |λ|(n)
take(15, padovans(n))
end |λ|
end script
script justified
on |λ|(ns)
concatMap(justifyRight(4, space), ns)
end |λ|
end script
fTable("Padovan N-step Series:", str, justified, ¬
nSample, enumFromTo(2, 8))
end run
------------------------ FORMATTING ----------------------
-- fTable :: String -> (a -> String) -> (b -> String) ->
-- (a -> b) -> [a] -> String
on fTable(s, xShow, fxShow, f, xs)
set ys to map(xShow, xs)
set w to maximum(map(my |length|, ys))
script arrowed
on |λ|(a, b)
|λ|(a) of justifyRight(w, space) & " ->" & b
end |λ|
end script
s & linefeed & unlines(zipWith(arrowed, ¬
ys, map(compose(fxShow, f), xs)))
end fTable
------------------------- GENERIC ------------------------
-- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
on compose(f, g)
script
property mf : mReturn(f)
property mg : mReturn(g)
on |λ|(x)
mf's |λ|(mg's |λ|(x))
end |λ|
end script
end compose
-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
set lng to length of xs
set acc to {}
tell mReturn(f)
repeat with i from 1 to lng
set acc to acc & (|λ|(item i of xs, i, xs))
end repeat
end tell
if {text, string} contains class of xs then
acc as text
else
acc
end if
end concatMap
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to {}
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{}
end if
end enumFromTo
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set s to xs as text
set my text item delimiters to dlm
s
end intercalate
-- justifyRight :: Int -> Char -> String -> String
on justifyRight(n, cFiller)
script
on |λ|(v)
set strText to v as text
if n > length of strText then
text -n thru -1 of ¬
((replicate(n, cFiller) as text) & strText)
else
strText
end if
end |λ|
end script
end justifyRight
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of 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
-- maximum :: Ord a => [a] -> a
on maximum(xs)
set ca to current application
unwrap((ca's NSArray's arrayWithArray:xs)'s ¬
valueForKeyPath:"@max.self")
end maximum
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted
-- into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- repeat :: a -> Generator [a]
on |repeat|(x)
script
on |λ|()
return x
end |λ|
end script
end |repeat|
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> String -> String
on replicate(n, s)
-- Egyptian multiplication - progressively doubling a list,
-- appending stages of doubling to an accumulator where needed
-- for binary assembly of a target length
script p
on |λ|({n})
n ≤ 1
end |λ|
end script
script f
on |λ|({n, dbl, out})
if (n mod 2) > 0 then
set d to out & dbl
else
set d to out
end if
{n div 2, dbl & dbl, d}
end |λ|
end script
set xs to |until|(p, f, {n, s, ""})
item 2 of xs & item 3 of xs
end replicate
-- str :: a -> String
on str(x)
x as string
end str
-- sum :: [Num] -> Num
on sum(xs)
set ca to current application
((ca's NSArray's arrayWithArray:xs)'s ¬
valueForKeyPath:"@sum.self") as real
end sum
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
set lng to length of xs
if 0 < n and 0 < lng then
items 1 thru min(n, lng) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
on unfoldr(f, v)
-- A lazy (generator) list unfolded from a seed value
-- by repeated application of f to a value until no
-- residue remains. Dual to fold/reduce.
-- f returns either nothing (missing value),
-- or just (value, residue).
script
property valueResidue : {v, v}
property g : mReturn(f)
on |λ|()
set valueResidue to g's |λ|(item 2 of (valueResidue))
if missing value ≠ valueResidue then
item 1 of (valueResidue)
else
missing value
end if
end |λ|
end script
end unfoldr
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set v to x
set mp to mReturn(p)
set mf to mReturn(f)
repeat until mp's |λ|(v)
set v to mf's |λ|(v)
end repeat
v
end |until|
-- unwrap :: NSValue -> a
on unwrap(nsValue)
if nsValue is missing value then
missing value
else
set ca to current application
item 1 of ((ca's NSArray's arrayWithObject:nsValue) as list)
end if
end unwrap
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
if 1 > lng then
return {}
else
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end if
end zipWith |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Modula-2 | Modula-2 | MODULE Pascal;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE PrintLine(n : INTEGER);
VAR
buf : ARRAY[0..63] OF CHAR;
m,j : INTEGER;
BEGIN
IF n<1 THEN RETURN END;
m := 1;
WriteString("1 ");
FOR j:=1 TO n-1 DO
m := m * (n - j) DIV j;
FormatString("%i ", buf, m);
WriteString(buf)
END;
WriteLn
END PrintLine;
PROCEDURE Print(n : INTEGER);
VAR i : INTEGER;
BEGIN
FOR i:=1 TO n DO
PrintLine(i)
END
END Print;
BEGIN
Print(10);
ReadChar
END Pascal. |
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #Go | Go | package main
import "fmt"
// constants
const EMX = 64 // exponent maximum (if indexing starts at -EMX)
const DMX = 100000 // approximation loop maximum
const AMX = 1048576 // argument maximum
const PMAX = 32749 // prime maximum
// global variables
var p1 = 0
var p = 7 // default prime
var k = 11 // precision
func abs(a int) int {
if a >= 0 {
return a
}
return -a
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
type Ratio struct {
a, b int
}
type Padic struct {
v int
d [2 * EMX]int // add EMX to index to be consistent wih FB
}
// (re)initialize receiver from Ratio, set 'sw' to print
func (pa *Padic) r2pa(q Ratio, sw int) int {
a := q.a
b := q.b
if b == 0 {
return 1
}
if b < 0 {
b = -b
a = -a
}
if abs(a) > AMX || b > AMX {
return -1
}
if p < 2 || k < 1 {
return 1
}
p = min(p, PMAX) // maximum short prime
k = min(k, EMX-1) // maxumum array length
if sw != 0 {
fmt.Printf("%d/%d + ", a, b) // numerator, denominator
fmt.Printf("0(%d^%d)\n", p, k) // prime, precision
}
// (re)initialize
pa.v = 0
p1 = p - 1
pa.d = [2 * EMX]int{}
if a == 0 {
return 0
}
i := 0
// find -exponent of p in b
for b%p == 0 {
b = b / p
i--
}
s := 0
r := b % p
// modular inverse for small p
b1 := 1
for b1 <= p1 {
s += r
if s > p1 {
s -= p
}
if s == 1 {
break
}
b1++
}
if b1 == p {
fmt.Println("r2pa: impossible inverse mod")
return -1
}
pa.v = EMX
for {
// find exponent of P in a
for a%p == 0 {
a = a / p
i++
}
// valuation
if pa.v == EMX {
pa.v = i
}
// upper bound
if i >= EMX {
break
}
// check precision
if (i - pa.v) > k {
break
}
// next digit
pa.d[i+EMX] = a * b1 % p
if pa.d[i+EMX] < 0 {
pa.d[i+EMX] += p
}
// remainder - digit * divisor
a -= pa.d[i+EMX] * b
if a == 0 {
break
}
}
return 0
}
// Horner's rule
func (pa *Padic) dsum() int {
t := min(pa.v, 0)
s := 0
for i := k - 1 + t; i >= t; i-- {
r := s
s *= p
if r != 0 && (s/r-p != 0) {
// overflow
s = -1
break
}
s += pa.d[i+EMX]
}
return s
}
// add b to receiver
func (pa *Padic) add(b Padic) *Padic {
c := 0
r := Padic{}
r.v = min(pa.v, b.v)
for i := r.v; i <= k+r.v; i++ {
c += pa.d[i+EMX] + b.d[i+EMX]
if c > p1 {
r.d[i+EMX] = c - p
c = 1
} else {
r.d[i+EMX] = c
c = 0
}
}
return &r
}
// complement of receiver
func (pa *Padic) cmpt() *Padic {
c := 1
r := Padic{}
r.v = pa.v
for i := pa.v; i <= k+pa.v; i++ {
c += p1 - pa.d[i+EMX]
if c > p1 {
r.d[i+EMX] = c - p
c = 1
} else {
r.d[i+EMX] = c
c = 0
}
}
return &r
}
// rational reconstruction
func (pa *Padic) crat() {
fl := false
s := pa
j := 0
i := 1
// denominator count
for i <= DMX {
// check for integer
j = k - 1 + pa.v
for j >= pa.v {
if s.d[j+EMX] != 0 {
break
}
j--
}
fl = ((j - pa.v) * 2) < k
if fl {
fl = false
break
}
// check negative integer
j = k - 1 + pa.v
for j >= pa.v {
if p1-s.d[j+EMX] != 0 {
break
}
j--
}
fl = ((j - pa.v) * 2) < k
if fl {
break
}
// repeatedly add self to s
s = s.add(*pa)
i++
}
if fl {
s = s.cmpt()
}
// numerator: weighted digit sum
x := s.dsum()
y := i
if x < 0 || y > DMX {
fmt.Println(x, y)
fmt.Println("crat: fail")
} else {
// negative powers
i = pa.v
for i <= -1 {
y *= p
i++
}
// negative rational
if fl {
x = -x
}
fmt.Print(x)
if y > 1 {
fmt.Printf("/%d", y)
}
fmt.Println()
}
}
// print expansion
func (pa *Padic) printf(sw int) {
t := min(pa.v, 0)
for i := k - 1 + t; i >= t; i-- {
fmt.Print(pa.d[i+EMX])
if i == 0 && pa.v < 0 {
fmt.Print(".")
}
fmt.Print(" ")
}
fmt.Println()
// rational approximation
if sw != 0 {
pa.crat()
}
}
func main() {
data := [][]int{
/* rational reconstruction depends on the precision
until the dsum-loop overflows */
{2, 1, 2, 4, 1, 1},
{4, 1, 2, 4, 3, 1},
{4, 1, 2, 5, 3, 1},
{4, 9, 5, 4, 8, 9},
{26, 25, 5, 4, -109, 125},
{49, 2, 7, 6, -4851, 2},
{-9, 5, 3, 8, 27, 7},
{5, 19, 2, 12, -101, 384},
/* two decadic pairs */
{2, 7, 10, 7, -1, 7},
{34, 21, 10, 9, -39034, 791},
/* familiar digits */
{11, 4, 2, 43, 679001, 207},
{-8, 9, 23, 9, 302113, 92},
{-22, 7, 3, 23, 46071, 379},
{-22, 7, 32749, 3, 46071, 379},
{35, 61, 5, 20, 9400, 109},
{-101, 109, 61, 7, 583376, 6649},
{-25, 26, 7, 13, 5571, 137},
{1, 4, 7, 11, 9263, 2837},
{122, 407, 7, 11, -517, 1477},
/* more subtle */
{5, 8, 7, 11, 353, 30809},
}
sw := 0
a := Padic{}
b := Padic{}
for _, d := range data {
q := Ratio{d[0], d[1]}
p = d[2]
k = d[3]
sw = a.r2pa(q, 1)
if sw == 1 {
break
}
a.printf(0)
q.a = d[4]
q.b = d[5]
sw = sw | b.r2pa(q, 1)
if sw == 1 {
break
}
if sw == 0 {
b.printf(0)
c := a.add(b)
fmt.Println("+ =")
c.printf(1)
}
fmt.Println()
}
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | ' version 20-06-2015
' compile with: fbc -s console "filename".bas
#Ifndef TRUE ' define true and false for older freebasic versions
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function reverse(norm As String) As Integer
Dim As String rev
Dim As Integer i, l = Len(norm) -1
rev = norm
For i = 0 To l
rev[l-i] = norm[i]
Next
If norm = rev Then
Return TRUE
Else
Return FALSE
End If
End Function
Function cleanup(in As String, action As String = "") As String
' action = "" do nothing, [l|L] = convert to lowercase,
' [s|S] = strip spaces, [p|P] = strip punctuation.
If action = "" Then Return in
Dim As Integer i, p_, s_
Dim As String ch
action = LCase(action)
For i = 1 To Len(action)
ch = Mid(action, i, 1)
If ch = "l" Then in = LCase(in)
If ch = "p" Then
p_ = 1
ElseIf ch = "s" Then
s_ = 1
End If
Next
If p_ = 0 And s_ = 0 Then Return in
Dim As String unwanted, clean
If s_ = 1 Then unwanted = " "
If p_ = 1 Then unwanted = unwanted + "`~!@#$%^&*()-=_+[]{}\|;:',.<>/?"
For i = 1 To Len(in)
ch = Mid(in, i, 1)
If InStr(unwanted, ch) = 0 Then clean = clean + ch
Next
Return clean
End Function
' ------=< MAIN >=------
Dim As String test = "In girum imus nocte et consumimur igni"
'IIf ( cond, true, false ), true and false must be of the same type (num, string, UDT)
Print
Print " reverse(test) = "; IIf(reverse(test) = FALSE, "FALSE", "TRUE")
Print " reverse(cleanup(test,""l"")) = "; IIf(reverse(cleanup(test,"l")) = FALSE, "FALSE", "TRUE")
Print " reverse(cleanup(test,""ls"")) = "; IIf(reverse(cleanup(test,"ls")) = FALSE, "FALSE", "TRUE")
Print "reverse(cleanup(test,""PLS"")) = "; IIf(reverse(cleanup(test,"PLS")) = FALSE, "FALSE", "TRUE")
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print : Print "Hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT,{}
alfabet="abcdefghijklmnopqrstuvwxyz"
sentences = *
DATA The quick brown fox jumps over the lazy dog
DATA the quick brown fox falls over the lazy dog
LOOP s=sentences
getchars =STRINGS (s," {&a} ")
sortchars =ALPHA_SORT (getchars)
reducechars =REDUCE (sortchars)
chars_in_s =EXCHANGE (reducechars," ' ")
IF (chars_in_s==alfabet) PRINT " pangram: ",s
IF (chars_in_s!=alfabet) PRINT "no pangram: ",s
ENDLOOP
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #TXR | TXR | @/.*[Aa].*&.*[Bb].*&.*[Cc].*&.*[Dd].*& \
.*[Ee].*&.*[Ff].*&.*[Gg].*&.*[Hh].*& \
.*[Ii].*&.*[Jj].*&.*[Kk].*&.*[Ll].*& \
.*[Mm].*&.*[Nn].*&.*[Oo].*&.*[Pp].*& \
.*[Qq].*&.*[Rr].*&.*[Ss].*&.*[Tt].*& \
.*[Uu].*&.*[Vv].*&.*[Ww].*&.*[Xx].*& \
.*[Yy].*&.*[Zz].*/ |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #C | C | #include <stdio.h>
void padovanN(int n, size_t t, int *p) {
int i, j;
if (n < 2 || t < 3) {
for (i = 0; i < t; ++i) p[i] = 1;
return;
}
padovanN(n-1, t, p);
for (i = n + 1; i < t; ++i) {
p[i] = 0;
for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j];
}
}
int main() {
int n, i;
const size_t t = 15;
int p[t];
printf("First %ld terms of the Padovan n-step number sequences:\n", t);
for (n = 2; n <= 8; ++n) {
for (i = 0; i < t; ++i) p[i] = 0;
padovanN(n, t, p);
printf("%d: ", n);
for (i = 0; i < t; ++i) printf("%3d ", p[i]);
printf("\n");
}
return 0;
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 1000 -- allow very large numbers
parse arg rows .
if rows = '' then rows = 11 -- default to 11 rows
printPascalTriangle(rows)
return
-- -----------------------------------------------------------------------------
method printPascalTriangle(rows = 11) public static
lines = ''
mx = (factorial(rows - 1) / factorial(rows % 2) / factorial(rows - 1 - rows % 2)).length() -- width of widest number
loop row = 1 to rows
n1 = 1.center(mx)
line = n1
loop col = 2 to row
n2 = col - 1
n1 = n1 * (row - n2) / n2
line = line n1.center(mx)
end col
lines[row] = line.strip()
end row
-- display triangle
ml = lines[rows].length() -- length of longest line
loop row = 1 to rows
say lines[row].centre(ml)
end row
return
-- -----------------------------------------------------------------------------
method factorial(n) public static
fac = 1
loop n_ = 2 to n
fac = fac * n_
end n_
return fac /*calc. factorial*/
|
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #Haskell | Haskell | {-# LANGUAGE KindSignatures, DataKinds #-}
module Padic where
import Data.Ratio
import Data.List (genericLength)
import GHC.TypeLits
data Padic (n :: Nat) = Null
| Padic { unit :: [Int], order :: Int }
-- valuation of the base
modulo :: (KnownNat p, Integral i) => Padic p -> i
modulo = fromIntegral . natVal
-- Constructor for zero value
pZero :: KnownNat p => Padic p
pZero = Padic (repeat 0) 0
-- Smart constructor, adjusts trailing zeros with the order.
mkPadic :: (KnownNat p, Integral i) => [i] -> Int -> Padic p
mkPadic u k = go 0 (fromIntegral <$> u)
where
go 17 _ = pZero
go i (0:u) = go (i+1) u
go i u = Padic u (k-i)
-- Constructor for p-adic unit
mkUnit :: (KnownNat p, Integral i) => [i] -> Padic p
mkUnit u = mkPadic u 0
-- Zero test (up to 1/p^17)
isZero :: KnownNat p => Padic p -> Bool
isZero (Padic u _) = all (== 0) (take 17 u)
isZero _ = False
-- p-adic norm
pNorm :: KnownNat p => Padic p -> Ratio Int
pNorm Null = undefined
pNorm p = fromIntegral (modulo p) ^^ (- order p)
-- test for an integerness up to p^-17
isInteger :: KnownNat p => Padic p -> Bool
isInteger Null = False
isInteger (Padic s k) = case splitAt k s of
([],i) -> length (takeWhile (==0) $ reverse (take 20 i)) > 3
_ -> False
-- p-adics are shown with 1/p^17 precision
instance KnownNat p => Show (Padic p) where
show Null = "Null"
show x@(Padic u k) =
show (modulo x) ++ "-adic: " ++
(case si of {[] -> "0"; _ -> si})
++ "." ++
(case f of {[] -> "0"; _ -> sf})
where
(f,i) = case compare k 0 of
LT -> ([], replicate (-k) 0 ++ u)
EQ -> ([], u)
GT -> splitAt k (u ++ repeat 0)
sf = foldMap showD $ reverse $ take 17 f
si = foldMap showD $ dropWhile (== 0) $ reverse $ take 17 i
el s = if length s > 16 then "…" else ""
showD n = [(['0'..'9']++['a'..'z']) !! n]
instance KnownNat p => Eq (Padic p) where
a == b = isZero (a - b)
instance KnownNat p => Ord (Padic p) where
compare = error "Ordering is undefined fo p-adics."
instance KnownNat p => Num (Padic p) where
fromInteger 0 = pZero
fromInteger n = pAdic (fromInteger n)
x@(Padic a ka) + Padic b kb = mkPadic s k
where
k = ka `max` kb
s = addMod (modulo x)
(replicate (k-ka) 0 ++ a)
(replicate (k-kb) 0 ++ b)
_ + _ = Null
x@(Padic a ka) * Padic b kb =
mkPadic (mulMod (modulo x) a b) (ka + kb)
_ * _ = Null
negate x@(Padic u k) =
case map (\y -> modulo x - 1 - y) u of
n:ns -> Padic ((n+1):ns) k
[] -> pZero
negate _ = Null
abs p = pAdic (pNorm p)
signum = undefined
------------------------------------------------------------
-- conversion from rationals to p-adics
instance KnownNat p => Fractional (Padic p) where
fromRational = pAdic
recip Null = Null
recip x@(Padic (u:us) k)
| isZero x = Null
| gcd p u /= 1 = Null
| otherwise = mkPadic res (-k)
where
p = modulo x
res = longDivMod p (1:repeat 0) (u:us)
pAdic :: (Show i, Integral i, KnownNat p)
=> Ratio i -> Padic p
pAdic 0 = pZero
pAdic x = res
where
p = modulo res
(k, q) = getUnit p x
(n, d) = (numerator q, denominator q)
res = maybe Null process $ recipMod p d
process r = mkPadic (series n) k
where
series n
| n == 0 = repeat 0
| n `mod` p == 0 = 0 : series (n `div` p)
| otherwise =
let m = (n * r) `mod` p
in m : series ((n - m * d) `div` p)
------------------------------------------------------------
-- conversion from p-adics to rationals
-- works for relatively small denominators
instance KnownNat p => Real (Padic p) where
toRational Null = error "no rational representation!"
toRational x@(Padic s k) = res
where
p = modulo x
res = case break isInteger $ take 10000 $ iterate (x +) x of
(_,[]) -> - toRational (- x)
(d, i:_) -> (fromBase p (unit i) * (p^(- order i))) % (genericLength d + 1)
fromBase p = foldr (\x r -> r*p + x) 0 .
take 20 . map fromIntegral
--------------------------------------------------------------------------------
-- helper functions
-- extracts p-adic unit from a rational number
getUnit :: Integral i => i -> Ratio i -> (Int, Ratio i)
getUnit p x = (genericLength k1 - genericLength k2, c)
where
(k1,b:_) = span (\n -> denominator n `mod` p == 0) $
iterate (* fromIntegral p) x
(k2,c:_) = span (\n -> numerator n `mod` p == 0) $
iterate (/ fromIntegral p) b
-- Reciprocal of a number modulo p (extended Euclidean algorithm).
-- For non-prime p returns Nothing non-invertible element of the ring.
recipMod :: Integral i => i -> i -> Maybe i
recipMod p 1 = Just 1
recipMod p a | gcd p a == 1 = Just $ go 0 1 p a
| otherwise = Nothing
where
go t _ _ 0 = t `mod` p
go t nt r nr =
let q = r `div` nr
in go nt (t - q*nt) nr (r - q*nr)
-- Addition of two sequences modulo p
addMod p = go 0
where
go 0 [] ys = ys
go 0 xs [] = xs
go s [] ys = go 0 [s] ys
go s xs [] = go 0 xs [s]
go s (x:xs) (y:ys) =
let (q, r) = (x + y + s) `divMod` p
in r : go q xs ys
-- Subtraction of two sequences modulo p
subMod p a (b:bs) = addMod p a $ (p-b) : ((p - 1 -) <$> bs)
-- Multiplication of two sequences modulo p
mulMod p as [b] = mulMod p [b] as
mulMod p as bs = case as of
[0] -> repeat 0
[1] -> bs
[a] -> go 0 bs
where
go s [] = [s]
go s (b:bs) =
let (q, r) = (a * b + s) `divMod` p
in r : go q bs
as -> go bs
where
go [] = []
go (b:bs) =
let c:cs = mulMod p [b] as
in c : addMod p (go bs) cs
-- Division of two sequences modulo p
longDivMod p a (b:bs) = case recipMod p b of
Nothing -> error $
show b ++ " is not invertible modulo " ++ show p
Just r -> go a
where
go [] = []
go (0:xs) = 0 : go xs
go (x:xs) =
let m = (x*r) `mod` p
_:zs = subMod p (x:xs) (mulMod p [m] (b:bs))
in m : go zs |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Frink | Frink | isPalindrome[x] := x == reverse[x]
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #UNIX_Shell | UNIX Shell | function pangram? {
local alphabet=abcdefghijklmnopqrstuvwxyz
local string="$*"
string="${string,,}"
while [[ -n "$string" && -n "$alphabet" ]]; do
local ch="${string%%${string#?}}"
string="${string#?}"
alphabet="${alphabet/$ch}"
done
[[ -z "$alphabet" ]]
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Ursala | Ursala |
#import std
is_pangram = ^jZ^(!@l,*+ @rlp -:~&) ~=`A-~ letters
|
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #F.23 | F# |
// Padovan n-step number sequences. Nigel Galloway: July 28th., 2021
let rec pad=function 2->Seq.unfold(fun(n:int[])->Some(n.[0],Array.append n.[1..2] [|Array.sum n.[0..1]|]))[|1;1;1|]
|g->Seq.unfold(fun(n:int[])->Some(n.[0],Array.append n.[1..g] [|Array.sum n.[0..g-1]|]))(Array.ofSeq(pad(g-1)|>Seq.take(g+1)))
[2..8]|>List.iter(fun n->pad n|>Seq.take 15|>Seq.iter(printf "%d "); printfn "")
|
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Factor | Factor | USING: compiler.tree.propagation.call-effect io kernel math
math.ranges prettyprint sequences ;
: padn ( m n -- seq )
V{ "|" 1 1 1 } over prefix clone over 2 -
[ dup last2 + suffix! ] times rot pick 1 + -
[ dup length 1 - pick [ - ] keepd pick <slice> sum suffix! ]
times nip ;
"Padovan n-step sequences" print
2 8 [a..b] [ 15 swap padn ] map simple-table. |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Nial | Nial | factorial is recur [ 0 =, 1 first, pass, product, -1 +]
combination is fork [ > [first, second], 0 first,
/ [factorial second, * [factorial - [second, first], factorial first] ]
]
pascal is transpose each combination cart [pass, pass] tell |
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #Julia | Julia | using Nemo, LinearAlgebra
set_printing_mode(FlintPadicField, :terse)
""" convert to Rational (rational reconstruction) """
function toRational(pa::padic)
rat = lift(QQ, pa)
r, den = BigInt(numerator(rat)), Int(denominator(rat))
p, k = Int(prime(parent(pa))), Int(precision(pa))
N = BigInt(p^k)
a1, a2 = [N, 0], [r, 1]
while dot(a1, a1) > dot(a2, a2)
q = dot(a1, a2) // dot(a2, a2)
a1, a2 = a2, a1 - BigInt(round(q)) * a2
end
if dot(a1, a1) < N
return (Rational{Int}(a1[1]) // Rational{Int}(a1[2])) // Int(den)
else
return Int(r) // den
end
end
function dstring(pa::padic)
u, v, n, p, k = pa.u, pa.v, pa.N, pa.parent.p, pa.parent.prec_max
d = digits(v > 0 ? u * p^v : u, base=pa.parent.p, pad=k)
return prod([i == k + v && v != 0 ? "$x . " : "$x " for (i, x) in enumerate(reverse(d))])
end
const DATA = [
[2, 1, 2, 4, 1, 1],
[4, 1, 2, 4, 3, 1],
[4, 1, 2, 5, 3, 1],
[4, 9, 5, 4, 8, 9],
[26, 25, 5, 4, -109, 125],
[49, 2, 7, 6, -4851, 2],
[-9, 5, 3, 8, 27, 7],
[5, 19, 2, 12, -101, 384],
# Base 10 10-adic p-adics are not allowed by Nemo library -- p must be a prime
# familiar digits
[11, 4, 2, 43, 679001, 207],
[-8, 9, 23, 9, 302113, 92],
[-22, 7, 3, 23, 46071, 379],
[-22, 7, 32749, 3, 46071, 379],
[35, 61, 5, 20, 9400, 109],
[-101, 109, 61, 7, 583376, 6649],
[-25, 26, 7, 13, 5571, 137],
[1, 4, 7, 11, 9263, 2837],
[122, 407, 7, 11, -517, 1477],
# more subtle
[5, 8, 7, 11, 353, 30809],
]
for (num1, den1, P, K, num2, den2) in DATA
Qp = PadicField(P, K)
a = Qp(QQ(num1 // den1))
b = Qp(QQ(num2 // den2))
c = a + b
r = toRational(c)
println(a, "\n", dstring(a), "\n", b, "\n", dstring(b), "\n+ =\n", c, "\n", dstring(c), " $r\n")
end
|
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #Nim | Nim | import math, strformat
const
Emx = 64 # Exponent maximum.
Dmx = 100000 # Approximation loop maximum.
Amx = 1048576 # Argument maximum.
PMax = 32749 # Prime maximum.
type
Ratio = tuple[a, b: int]
Padic = object
p: int # Prime.
k: int # Precision.
v: int
d: array[-Emx..(Emx-1), int]
PadicError = object of ValueError
proc r2pa(pa: var Padic; q: Ratio; sw: bool) =
## Convert "q" to p-adic number, set "sw" to print.
var (a, b) = q
if b == 0:
raise newException(PadicError, &"Wrong rational: {a}/{b}" )
if b < 0:
b = -b
a = -a
if abs(a) > Amx or b > Amx:
raise newException(PadicError, &"Rational exceeding limits: {a}/{b}")
if pa.p < 2:
raise newException(PadicError, &"Wrong value for p: {pa.p}")
if pa.k < 1:
raise newException(PadicError, &"Wrong value for k: {pa.k}")
pa.p = min(pa.p, PMax) # Maximum short prime.
pa.k = min(pa.k, Emx - 1) # Maximum array length.
if sw: echo &"{a}/{b} + 0({pa.p}^{pa.k})"
# Initialize.
pa.v = 0
pa.d.reset()
if a == 0: return
var i = 0
# Find -exponent of "p" in "b".
while b mod pa.p == 0:
b = b div pa.p
dec i
var s = 0
var r = b mod pa.p
# Modular inverse for small "p".
var b1 = 1
while b1 < pa.p:
inc s, r
if s >= pa.p: dec s, pa.p
if s == 1: break
inc b1
if b1 == pa.p:
raise newException(PadicError, "Impossible to compute inverse modulo")
pa.v = Emx
while true:
# Find exponent of "p" in "a".
while a mod pa.p == 0:
a = a div pa.p
inc i
# Valuation.
if pa.v == Emx: pa.v = i
# Upper bound.
if i >= Emx: break
# Check precision.
if i - pa.v > pa.k: break
# Next digit.
pa.d[i] = floorMod(a * b1, pa.p)
# Remainder - digit * divisor.
dec a, pa.d[i] * b
if a == 0: break
func dsum(pa: Padic): int =
## Horner's rule.
let t = min(pa.v, 0)
for i in countdown(pa.k - 1 + t, t):
var r = result
result *= pa.p
if r != 0 and (result div r - pa.p) != 0:
return -1 # Overflow.
inc result, pa.d[i]
func `+`(pa, pb: Padic): Padic =
## Add two p-adic numbers.
assert pa.p == pb.p and pa.k == pb.k
result.p = pa.p
result.k = pa.k
var c = 0
result.v = min(pa.v, pb.v)
for i in result.v..(pa.k + result.v):
inc c, pa.d[i] + pb.d[i]
if c >= pa.p:
result.d[i] = c - pa.p
c = 1
else:
result.d[i] = c
c = 0
func cmpt(pa: Padic): Padic =
## Return the complement.
var c = 1
result.p = pa.p
result.k = pa.k
result.v = pa.v
for i in pa.v..(pa.k + pa.v):
inc c, pa.p - 1 - pa.d[i]
if c >= pa.p:
result.d[i] = c - pa.p
c = 1
else:
result.d[i] = c
c = 0
func crat(pa: Padic): string =
## Rational reconstruction.
var s = pa
# Denominator count.
var i = 1
var fl = false
while i <= Dmx:
# Check for integer.
var j = pa.k - 1 + pa.v
while j >= pa.v:
if s.d[j] != 0: break
dec j
fl = (j - pa.v) * 2 < pa.k
if fl:
fl = false
break
# Check negative integer.
j = pa.k - 1 + pa.v
while j >= pa.v:
if pa.p - 1 - s.d[j] != 0: break
dec j
fl = (j - pa.v) * 2 < pa.k
if fl: break
# Repeatedly add "pa" to "s".
s = s + pa
inc i
if fl: s = s.cmpt()
# Numerator: weighted digit sum.
var x = s.dsum()
var y = i
if x < 0 or y > Dmx:
raise newException(PadicError, &"Error during rational reconstruction: {x}, {y}")
# Negative powers.
for i in pa.v..(-1): y *= pa.p
# Negative rational.
if fl: x = -x
result = $x
if y > 1: result.add &"/{y}"
func `$`(pa: Padic): string =
## String representation.
let t = min(pa.v, 0)
for i in countdown(pa.k - 1 + t, t):
result.add $pa.d[i]
if i == 0 and pa.v < 0: result.add "."
result.add " "
proc print(pa: Padic; sw: int) =
echo pa
# Rational approximation.
if sw != 0: echo pa.crat()
when isMainModule:
# Rational reconstruction depends on the precision
# until the dsum-loop overflows.
const Data = [[2, 1, 2, 4, 1, 1],
[4, 1, 2, 4, 3, 1],
[4, 1, 2, 5, 3, 1],
[4, 9, 5, 4, 8, 9],
[26, 25, 5, 4, -109, 125],
[49, 2, 7, 6, -4851, 2],
[-9, 5, 3, 8, 27, 7],
[5, 19, 2, 12, -101, 384],
# Two decadic pairs.
[2, 7, 10, 7, -1, 7],
[34, 21, 10, 9, -39034, 791],
# Familiar digits.
[11, 4, 2, 43, 679001, 207],
[-8, 9, 23, 9, 302113, 92],
[-22, 7, 3, 23, 46071, 379],
[-22, 7, 32749, 3, 46071, 379],
[35, 61, 5, 20, 9400, 109],
[-101, 109, 61, 7, 583376, 6649],
[-25, 26, 7, 13, 5571, 137],
[1, 4, 7, 11, 9263, 2837],
[122, 407, 7, 11, -517, 1477],
# More subtle.
[5, 8, 7, 11, 353, 30809]]
for d in Data:
try:
var a, b = Padic(p: d[2], k: d[3])
r2pa(a, (d[0], d[1]), true)
print(a, 0)
r2pa(b, (d[4], d[5]), true)
print(b, 0)
echo "+ ="
print(a + b, 1)
echo ""
except PadicError:
echo getCurrentExceptionMsg() |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | ZapGremlins := function(s)
local upper, lower, c, i, n, t;
upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
lower := "abcdefghijklmnopqrstuvwxyz";
t := [ ];
i := 1;
for c in s do
n := Position(upper, c);
if n <> fail then
t[i] := lower[n];
i := i + 1;
else
n := Position(lower, c);
if n <> fail then
t[i] := c;
i := i + 1;
fi;
fi;
od;
return t;
end;
IsPalindrome := function(s)
local t;
t := ZapGremlins(s);
return t = Reversed(t);
end; |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #11l | 11l | F partitions(lengths)
[[[Int]]] r
[(Int, Int)] slices
V delta = -1
V idx = 0
L(length) lengths
assert(length >= 0, ‘lengths must not be negative.’)
delta += length
slices.append((idx, delta))
idx += length
V n = sum(lengths)
V perm = Array(1 .. n)
L
[[Int]] part
L(start, end) slices
V s = perm[start .. end]
I !s.is_sorted()
L.break
part.append(s)
L.was_no_break
r.append(part)
I !perm.next_permutation()
L.break
R r
F toString(part)
V result = ‘(’
L(s) part
I result.len > 1
result ‘’= ‘, ’
result ‘’= ‘{’s.join(‘, ’)‘}’
R result‘)’
F displayPermutations(lengths)
print(‘Ordered permutations for (’lengths.join(‘, ’)‘):’)
L(part) partitions(lengths)
print(toString(part))
:start:
I :argv.len > 1
displayPermutations(:argv[1..].map(Int))
E
displayPermutations([2, 0, 2]) |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #VBA | VBA |
Function pangram2(s As String) As Boolean
Const sKey As String = "abcdefghijklmnopqrstuvwxyz"
Dim sLow As String
Dim i As Integer
sLow = LCase(s)
For i = 1 To 26
If InStr(sLow, Mid(sKey, i, 1)) = 0 Then
pangram2 = False
Exit Function
End If
Next
pangram2 = True
End Function
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #VBScript | VBScript | function pangram( s )
dim i
dim sKey
dim sChar
dim nOffset
sKey = "abcdefghijklmnopqrstuvwxyz"
for i = 1 to len( s )
sChar = lcase(mid(s,i,1))
if sChar <> " " then
if instr(sKey, sChar) then
nOffset = asc( sChar ) - asc("a") + 1
if nOffset > 1 then
sKey = left(sKey, nOffset - 1) & " " & mid( sKey, nOffset + 1)
else
sKey = " " & mid( sKey, nOffset + 1)
end if
end if
end if
next
pangram = ( ltrim(sKey) = vbnullstring )
end function
function eef( bCond, exp1, exp2 )
if bCond then
eef = exp1
else
eef = exp2
end if
end function |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Go | Go | package main
import "fmt"
func padovanN(n, t int) []int {
if n < 2 || t < 3 {
ones := make([]int, t)
for i := 0; i < t; i++ {
ones[i] = 1
}
return ones
}
p := padovanN(n-1, t)
for i := n + 1; i < t; i++ {
p[i] = 0
for j := i - 2; j >= i-n-1; j-- {
p[i] += p[j]
}
}
return p
}
func main() {
t := 15
fmt.Println("First", t, "terms of the Padovan n-step number sequences:")
for n := 2; n <= 8; n++ {
fmt.Printf("%d: %3d\n", n, padovanN(n, t))
}
} |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Haskell | Haskell | import Data.Bifunctor (second)
import Data.List (transpose, uncons, unfoldr)
------------------ PADOVAN N-STEP SERIES -----------------
padovans :: Int -> [Int]
padovans n
| 0 > n = []
| otherwise = unfoldr (recurrence n) $ take (succ n) xs
where
xs
| 3 > n = repeat 1
| otherwise = padovans $ pred n
recurrence :: Int -> [Int] -> Maybe (Int, [Int])
recurrence n =
( fmap
. second
. flip (<>)
. pure
. sum
. take n
)
<*> uncons
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn $
"Padovan N-step series:\n\n"
<> spacedTable
justifyRight
( fmap
( \n ->
[show n <> " -> "]
<> fmap show (take 15 $ padovans n)
)
[2 .. 8]
)
------------------------ FORMATTING ----------------------
spacedTable ::
(Int -> Char -> String -> String) -> [[String]] -> String
spacedTable aligned rows =
unlines $
fmap
(unwords . zipWith (`aligned` ' ') columnWidths)
rows
where
columnWidths =
fmap
(maximum . fmap length)
(transpose rows)
justifyRight :: Int -> a -> [a] -> [a]
justifyRight n c = drop . length <*> (replicate n c <>) |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Nim | Nim | import sequtils, strutils
proc printPascalTriangle(n: int) =
## Print a Pascal triangle.
# Build the triangle.
var triangle: seq[seq[int]]
triangle.add @[1]
for _ in 1..<n:
triangle.add zip(triangle[^1] & @[0], @[0] & triangle[^1]).mapIt(it[0] + it[1])
# Build the lines to display.
let length = len($max(triangle[^1])) # Maximum length of number.
var lines: seq[string]
for row in triangle:
lines.add row.mapIt(($it).center(length)).join(" ")
# Display the lines.
let lineLength = lines[^1].len # Length of largest line (the last one).
for line in lines:
echo line.center(lineLength)
printPascalTriangle(10) |
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #Phix | Phix | // constants
constant EMX = 64 // exponent maximum (if indexing starts at -EMX)
constant DMX = 1e5 // approximation loop maximum
constant AMX = 1048576 // argument maximum
constant PMAX = 32749 // prime maximum
// global variables
integer p1 = 0
integer p = 7 // default prime
integer k = 11 // precision
type Ratio(sequence r)
return length(r)=2 and integer(r[1]) and integer(r[2])
end type
procedure pad_to(string fmt, sequence data, integer len)
fmt = sprintf(fmt,data)
puts(1,fmt&repeat(' ',len-length(fmt)))
end procedure
class Padic
integer v = 0
sequence d = repeat(0,EMX*2)
// (re)initialize 'this' from Ratio, set 'sw' to print
function r2pa(Ratio q, integer sw)
integer {a,b} = q
if b=0 then return 1 end if
if b<0 then
b = -b
a = -a
end if
if abs(a)>AMX or b>AMX then return -1 end if
if p<2 or k<1 then return 1 end if
p = min(p, PMAX) // maximum short prime
k = min(k, EMX-1) // maximum array length
if sw!=0 then
-- numerator, denominator, prime, precision
pad_to("%d/%d + O(%d^%d)",{a,b,p,k},30)
end if
// (re)initialize
v = 0
p1 = p - 1
sequence ntd = repeat(0,2*EMX) -- (new this.d)
if a=0 then return 0 end if
// find -exponent of p in b
integer i = 0
while remainder(b,p)=0 do
b /= p
i -= 1
end while
integer s = 0,
r = remainder(b,p)
// modular inverse for small P
integer b1 = 1
while b1<=p1 do
s += r
if s>p1 then s -= p end if
if s=1 then exit end if
b1 += 1
end while
if b1=p then
printf(1,"r2pa: impossible inverse mod")
return -1
end if
v = EMX
while true do
// find exponent of P in a
while remainder(a,p)=0 do
a /= p
i += 1
end while
// valuation
if v=EMX then v = i end if
// upper bound
if i>=EMX then exit end if
// check precision
if i-v>k then exit end if
// next digit
integer rdx = remainder(a*b1,p)
if rdx<0 then rdx += p end if
if rdx<0 or rdx>=p then ?9/0 end if -- sanity chk
ntd[i+EMX+1] = rdx
// remainder - digit * divisor
a -= rdx*b
if a=0 then exit end if
end while
this.d = ntd
return 0
end function
// Horner's rule
function dsum()
integer t = min(v, 0),
s = 0
for i=k-1+t to t by -1 do
integer r = s
s *= p
if r!=0 and floor(s/r)-p!=0 then
// overflow
s = -1
exit
end if
s += d[i+EMX+1]
end for
return s
end function
// add b to 'this'
function add(Padic b)
integer c = 0
Padic r = new({min(v,b.v)})
sequence rd = r.d
for i=r.v to k+r.v do
integer dx = i+EMX+1
c += d[dx] + b.d[dx]
if c>p1 then
rd[dx] = c - p
c = 1
else
rd[dx] = c
c = 0
end if
end for
r.d = rd
return r
end function
// complement
function complement()
integer c = 1
Padic r = new({v})
sequence rd = r.d
for i=v to k+v do
integer dx = i+EMX+1
c += p1 - this.d[dx]
if c>p1 then
rd[dx] = c - p
c = 1
else
rd[dx] = c
c = 0
end if
end for
r.d = rd
return r
end function
// rational reconstruction
procedure crat()
integer sgn = 1
Padic s = this
integer j = 0,
i = 1
// denominator count
while i<=DMX do
// check for integer
j = k-1+v
while j>=v and s.d[j+EMX+1]=0 do
j -= 1
end while
if ((j-v)*2)<k then exit end if
// check for negative integer
j = k-1+v
while j>=v and p1-s.d[j+EMX+1]=0 do
j -= 1
end while
if ((j-v)*2)<k then
s = s.complement()
sgn = -1
exit
end if
// repeatedly add self to s
s = s.add(this)
i += 1
end while
// numerator: weighted digit sum
integer x = s.dsum(),
y = i
if x<0 or y>DMX then
printf(1,"crat: fail")
else
// negative powers
for i=v to -1 do
y *= p
end for
pad_to(iff(y=1?"%d":"%d/%d"),{x*sgn,y},26)
printf(1,"+ = ")
end if
end procedure
// print expansion
procedure prntf(bool sw)
integer t = min(v, 0)
// rational approximation
if sw!=0 then crat() end if
for i=k-1+t to t by -1 do
printf(1,"%d",d[i+EMX+1])
printf(1,iff(i=0 and v<0?". ":" "))
end for
printf(1,"\n")
end procedure
end class
sequence data = {
/* rational reconstruction limits are relative to the precision */
{{2, 1}, 2, 4, {1, 1}},
{{4, 1}, 2, 4, {3, 1}},
{{4, 1}, 2, 5, {3, 1}},
{{4, 9}, 5, 4, {8, 9}},
-- all tested, but let's keep the output reasonable:
-- {{-7, 5}, 7, 4, {99, 70}},
-- {{26, 25}, 5, 4, {-109, 125}},
-- {{49, 2}, 7, 6, {-4851, 2}},
-- {{-9, 5}, 3, 8, {27, 7}},
-- {{5, 19}, 2, 12, {-101, 384}},
-- /* four decadic pairs */
-- {{6, 7}, 10, 7, {-5, 7}},
-- {{2, 7}, 10, 7, {-3, 7}},
-- {{2, 7}, 10, 7, {-1, 7}},
-- {{34, 21}, 10, 9, {-39034, 791}},
-- /* familiar digits */
-- {{11, 4}, 2, 43, {679001, 207}},
-- {{11, 4}, 3, 27, {679001, 207}},
-- {{11, 4}, 11, 13, {679001, 207}},
-- {{-22, 7}, 2, 37, {46071, 379}},
-- {{-22, 7}, 3, 23, {46071, 379}},
-- {{-22, 7}, 7, 13, {46071, 379}},
-- {{-101, 109}, 2, 40, {583376, 6649}},
-- {{-101, 109}, 61, 7, {583376, 6649}},
-- {{-101, 109}, 32749, 3, {583376, 6649}},
-- {{-25, 26}, 7, 13, {5571, 137}},
-- {{1, 4}, 7, 11, {9263, 2837}},
-- {{122, 407}, 7, 11, {-517, 1477}},
/* more subtle */
{{5, 8}, 7, 11, {353, 30809}}
}
integer sw = 0,qa,qb
Padic a = new()
Padic b = new()
for i=1 to length(data) do
{Ratio q, p, k, Ratio q2} = data[i]
sw = a.r2pa(q, 1)
if sw=1 then exit end if
a.prntf(0)
sw = sw or b.r2pa(q2, 1)
if sw=1 then exit end if
if sw=0 then
b.prntf(0)
Padic c = a.add(b)
c.prntf(1)
end if
printf(1,"\n")
end for |
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #Raku | Raku | # 20210225 Raku programming solution
#!/usr/bin/env raku
class Padic { has ($.p is default(2), %.v is default({})) is rw ;
method r2pa (Rat $x is copy, \p, \d) { # Reference: math.stackexchange.com/a/1187037
self.p = p ;
$x += p**d if $x < 0 ; # complement
my $lowerest = 0;
my ($num,$den) = $x.nude;
while ($den % p) == 0 { $den /= p and $lowerest-- }
$x = $num / $den;
while +self.v < d {
my %d = ^p Z=> (( $x «-« ^p ) »/» p )».&{ .denominator % p }; # .kv
for %d.keys { self.v.{$lowerest++} = $_ and last if %d{$_} != 0 }
$x = ($x - self.v.{$lowerest-1}) / p ;
}
self
}
method add (Padic \x, \d) {
my $div = 0;
my $lowerest = (self.v.keys.sort({.Int}).first,
x.v.keys.sort({.Int}).first ).min ;
return Padic.new:
p => self.p,
v => gather for ^d {
my $power = $lowerest + $_;
given ((self.v.{$power}//0)+(x.v.{$power}//0)+$div).polymod(x.p)
{ take ($power, .[0]).Slip and $div = .[1] }
}
}
method gist {
# en.wikipedia.org/wiki/P-adic_number#Notation
# my %H = (0..9) Z=> ('₀'..'₉'); # (0x2080 .. 0x2089);
# '⋯ ' ~ self.v ~ ' ' ~ [~] self.p.comb».&{ %H{$_} }
# express as a series
my %H = ( 0…9 ,'-') Z=> ( '⁰','¹','²','³','⁴'…'⁹','⁻');
[~] self.v.keys.sort({.Int}).map: {
' + ' ~ self.v.{$_} ~ '*' ~ self.p ~ [~] $_.comb».&{ %H{$_}} }
}
}
my @T;
for my \D = (
#`[[ these are not working
< 26/25 -109/125 5 4 >,
< 6/7 -5/7 10 7 >,
< 2/7 -3/7 10 7 >,
< 2/7 -1/7 10 7 >,
< 34/21 -39034/791 10 9 >,
#]]
#`[[[[[ Works
< 11/4 679001/207 2 43>,
< 11/4 679001/207 3 27 >,
< 5/19 -101/384 2 12>,
< -22/7 46071/379 7 13 >,
< -7/5 99/70 7 4> ,
< -101/109 583376/6649 61 7>,
< 122/407 -517/1477 7 11>,
< 2/1 1/1 2 4>,
< 4/1 3/1 2 4>,
< 4/1 3/1 2 5>,
< 4/9 8/9 5 4>,
< 11/4 679001/207 11 13 >,
< 1/4 9263/2837 7 11 >,
< 49/2 -4851/2 7 6 >,
< -9/5 27/7 3 8>,
< -22/7 46071/379 2 37 >,
< -22/7 46071/379 3 23 >,
< -101/109 583376/6649 2 40>,
< -101/109 583376/6649 32749 3>,
< -25/26 5571/137 7 13>,
#]]]]]
< 5/8 353/30809 7 11 >,
) -> \D {
given @T[0] = Padic.new { say D[0]~' = ', .r2pa: D[0],D[2],D[3] }
given @T[1] = Padic.new { say D[1]~' = ', .r2pa: D[1],D[2],D[3] }
given @T[0].add: @T[1], D[3] {
given @T[2] = Padic.new { .r2pa: D[0]+D[1], D[2], D[3] }
say "Addition result = ", $_.gist; #
unless ( $_.v.Str eq @T[2].v.Str ) {
say 'but ' ~ (D[0]+D[1]).nude.join('/') ~ ' = ' ~ @T[2].gist
}
}
}
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #GAP | GAP | ZapGremlins := function(s)
local upper, lower, c, i, n, t;
upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
lower := "abcdefghijklmnopqrstuvwxyz";
t := [ ];
i := 1;
for c in s do
n := Position(upper, c);
if n <> fail then
t[i] := lower[n];
i := i + 1;
else
n := Position(lower, c);
if n <> fail then
t[i] := c;
i := i + 1;
fi;
fi;
od;
return t;
end;
IsPalindrome := function(s)
local t;
t := ZapGremlins(s);
return t = Reversed(t);
end; |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Ada | Ada | with Ada.Containers.Indefinite_Ordered_Sets;
with Ada.Containers.Ordered_Sets;
package Partitions is
-- Argument type for Create_Partitions: Array of Numbers
type Arguments is array (Positive range <>) of Natural;
package Number_Sets is new Ada.Containers.Ordered_Sets
(Natural);
type Partition is array (Positive range <>) of Number_Sets.Set;
function "<" (Left, Right : Partition) return Boolean;
package Partition_Sets is new Ada.Containers.Indefinite_Ordered_Sets
(Partition);
function Create_Partitions (Args : Arguments) return Partition_Sets.Set;
end Partitions; |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #VTL-2 | VTL-2 | 10 I=1
20 :I)=0
30 I=I+1
40 #=26>I*20
50 ?="Enter sentence: ";
60 C=$
70 #=C=13*120
80 C=C<97*32+C-96
90 #=C>27*60
100 :C)=1
110 #=60
120 ?=""
130 I=1
140 N=0
150 N=N+:I)
160 I=I+1
170 #=26>I*150
180 #=N=26*200
190 ?="not ";
200 ?="a pangram" |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Wren | Wren | import "/str" for Str
var isPangram = Fn.new { |s|
s = Str.lower(s)
var used = List.filled(26, false)
for (cp in s.codePoints) {
if (cp >= 97 && cp <= 122) used[cp-97] = true
}
for (u in used) if (!u) return false
return true
}
var candidates = [
"The quick brown fox jumps over the lazy dog.",
"New job: fix Mr. Gluck's hazy TV, PDQ!",
"Peter Piper picked a peck of pickled peppers.",
"Sphinx of black quartz, judge my vow.",
"Foxy diva Jennifer Lopez wasn’t baking my quiche.",
"Grumpy wizards make a toxic stew for the jovial queen."
]
System.print("Are the following pangrams?")
for (candidate in candidates) {
System.print(" %(candidate) -> %(isPangram.call(candidate))")
} |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #JavaScript | JavaScript | (() => {
"use strict";
// ---------- PADOVAN N-STEP NUMBER SERIES -----------
// padovans :: Int -> [Int]
const padovans = n => {
// Padovan number series of step N
const recurrence = ns => [
ns[0],
ns.slice(1).concat(
sum(take(n)(ns))
)
];
return 0 > n ? (
[]
) : unfoldr(recurrence)(
take(1 + n)(
3 > n ? (
repeat(1)
) : padovans(n - 1)
)
);
};
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
fTable("Padovan N-step series:")(str)(
xs => xs.map(
compose(justifyRight(4)(" "), str)
)
.join("")
)(
compose(take(15), padovans)
)(
enumFromTo(2)(8)
);
// --------------------- GENERIC ---------------------
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// repeat :: a -> Generator [a]
const repeat = function* (x) {
while (true) {
yield x;
}
};
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat(...Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// unfoldr :: (b -> Maybe (a, b)) -> b -> Gen [a]
const unfoldr = f =>
// A lazy (generator) list unfolded from a seed value
// by repeated application of f to a value until no
// residue remains. Dual to fold/reduce.
// f returns either Nothing or Just (value, residue).
// For a strict output list,
// wrap with `list` or Array.from
x => (
function* () {
let valueResidue = f(x);
while (null !== valueResidue) {
yield valueResidue[0];
valueResidue = f(valueResidue[1]);
}
}()
);
// ------------------- FORMATTING --------------------
// fTable :: String -> (a -> String) ->
// (b -> String) -> (a -> b) -> [a] -> String
const fTable = s =>
// Heading -> x display function ->
// fx display function ->
// f -> values -> tabular string
xShow => fxShow => f => xs => {
const
ys = xs.map(xShow),
w = Math.max(...ys.map(y => [...y].length)),
table = zipWith(
a => b => `${a.padStart(w, " ")} ->${b}`
)(ys)(
xs.map(x => fxShow(f(x)))
).join("\n");
return `${s}\n${table}`;
};
// justifyRight :: Int -> Char -> String -> String
const justifyRight = n =>
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s => n > s.length ? (
s.padStart(n, c)
) : s;
// str :: a -> String
const str = x => `${x}`;
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple constructor.
xs => ys => take(
Math.min(xs.length, ys.length)
)(
xs.map((x, i) => f(x)(ys[i]))
);
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #OCaml | OCaml | (* generate next row from current row *)
let next_row row =
List.map2 (+) ([0] @ row) (row @ [0])
(* returns the first n rows *)
let pascal n =
let rec loop i row =
if i = n then []
else row :: loop (i+1) (next_row row)
in loop 0 [1] |
http://rosettacode.org/wiki/P-Adic_numbers,_basic | P-Adic numbers, basic | Conversion and addition of p-adic Numbers.
Task.
Convert two rationals to p-adic numbers and add them up.
Rational reconstruction is needed to interpret the result.
p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions
(a series of digits 0 ≤ d < p times p-power weights)
are finite-tailed and tend to zero in the direction of higher positive
powers of p (to the left in the notation used here).
For example, the number 4 (100.0) has smaller 2-adic norm than 1/4 (0.01).
If we convert a natural number, the familiar p-ary expansion is obtained:
10 decimal is 1010 both binary and 2-adic. To convert a rational number a/b
we perform p-adic long division. If p is actually prime, this is always possible
if first the 'p-part' is removed from b (and the p-adic point shifted accordingly).
The inverse of b modulo p is then used in the conversion.
Recipe: at each step the most significant digit of the partial remainder
(initially a) is zeroed by subtracting a proper multiple of the divisor b.
Shift out the zero digit (divide by p) and repeat until the remainder is zero
or the precision limit is reached. Because p-adic division starts from the right,
the 'proper multiplier' is simply
d = partial remainder * 1/b (mod p).
The d's are the successive p-adic digits to find.
Addition proceeds as usual, with carry from the right to the leftmost term,
where it has least magnitude and just drops off. We can work with approximate rationals
and obtain exact results. The routine for rational reconstruction demonstrates this:
repeatedly add a p-adic to itself (keeping count to determine the denominator),
until an integer is reached (the numerator then equals the weighted digit sum).
But even p-adic arithmetic fails if the precision is too low. The examples mostly
set the shortest prime-exponent combinations that allow valid reconstruction.
Related task.
p-Adic square roots
Reference.
[1] p-Adic expansions
| #Wren | Wren | import "/dynamic" for Struct
// constants
var EMX = 64 // exponent maximum (if indexing starts at -EMX)
var DMX = 1e5 // approximation loop maximum
var AMX = 1048576 // argument maximum
var PMAX = 32749 // prime maximum
// global variables
var P1 = 0
var P = 7 // default prime
var K = 11 // precision
var Ratio = Struct.create("Ratio", ["a", "b"])
class Padic {
// uninitialized
construct new() {
_v = 0
_d = List.filled(2 * EMX, 0) // add EMX to index to be consistent wih FB
}
// properties
v { _v }
v=(o) { _v = o }
d { _d }
// (re)initialize 'this' from Ratio, set 'sw' to print
r2pa(q, sw) {
var a = q.a
var b = q.b
if (b == 0) return 1
if (b < 0) {
b = -b
a = -a
}
if (a.abs > AMX || b > AMX) return -1
if (P < 2 || K < 1) return 1
P = P.min(PMAX) // maximum short prime
K = K.min(EMX-1) // maximum array length
if (sw != 0) {
System.write("%(a)/%(b) + ") // numerator, denominator
System.print("0(%(P)^%(K))") // prime, precision
}
// (re)initialize
_v = 0
P1 = P - 1
_d = List.filled(2 * EMX, 0)
if (a == 0) return 0
var i = 0
// find -exponent of P in b
while (b%P == 0) {
b = (b/P).truncate
i = i - 1
}
var s = 0
var r = b % P
// modular inverse for small P
var b1 = 1
while (b1 <= P1) {
s = s + r
if (s > P1) s = s - P
if (s == 1) break
b1 = b1 + 1
}
if (b1 == P) {
System.print("r2pa: impossible inverse mod")
return -1
}
_v = EMX
while (true) {
// find exponent of P in a
while (a%P == 0) {
a = (a/P).truncate
i = i + 1
}
// valuation
if (_v == EMX) _v = i
// upper bound
if (i >= EMX) break
// check precision
if ((i - _v) > K) break
// next digit
_d[i+EMX] = a * b1 % P
if (_d[i+EMX] < 0) _d[i+EMX] = _d[i+EMX] + P
// remainder - digit * divisor
a = a - _d[i+EMX]*b
if (a == 0) break
}
return 0
}
// Horner's rule
dsum() {
var t = _v.min(0)
var s = 0
for (i in K - 1 + t..t) {
var r = s
s = s * P
if (r != 0 && ((s/r).truncate - P) != 0) {
// overflow
s = -1
break
}
s = s + _d[i+EMX]
}
return s
}
// rational reconstruction
crat() {
var fl = false
var s = this
var j = 0
var i = 1
// denominator count
while (i <= DMX) {
// check for integer
j = K - 1 + _v
while (j >= _v) {
if (s.d[j+EMX] != 0) break
j = j - 1
}
fl = ((j - _v) * 2) < K
if (fl) {
fl = false
break
}
// check negative integer
j = K - 1 + _v
while (j >= _v) {
if (P1 - s.d[j+EMX] != 0) break
j = j - 1
}
fl = ((j - _v) * 2) < K
if (fl) break
// repeatedly add self to s
s = s + this
i = i + 1
}
if (fl) s = s.cmpt
// numerator: weighted digit sum
var x = s.dsum()
var y = i
if (x < 0 || y > DMX) {
System.print("crat: fail")
} else {
// negative powers
i = _v
while (i <= -1) {
y = y * P
i = i + 1
}
// negative rational
if (fl) x = -x
System.write(x)
if (y > 1) System.write("/%(y)")
System.print()
}
}
// print expansion
printf(sw) {
var t = _v.min(0)
for (i in K - 1 + t..t) {
System.write(_d[i + EMX])
if (i == 0 && _v < 0) System.write(".")
System.write(" ")
}
System.print()
// rational approximation
if (sw != 0) crat()
}
// add b to 'this'
+(b) {
var c = 0
var r = Padic.new()
r.v = _v.min(b.v)
for (i in r.v..K + r.v) {
c = c + _d[i+EMX] + b.d[i+EMX]
if (c > P1) {
r.d[i+EMX] = c - P
c = 1
} else {
r.d[i+EMX] = c
c = 0
}
}
return r
}
// complement
cmpt {
var c = 1
var r = Padic.new()
r.v = _v
for (i in _v..K + _v) {
c = c + P1 - _d[i+EMX]
if (c > P1) {
r.d[i+EMX] = c - P
c = 1
} else {
r.d[i+EMX] = c
c = 0
}
}
return r
}
}
var data = [
/* rational reconstruction depends on the precision
until the dsum-loop overflows */
[2, 1, 2, 4, 1, 1],
[4, 1, 2, 4, 3, 1],
[4, 1, 2, 5, 3, 1],
[4, 9, 5, 4, 8, 9],
[26, 25, 5, 4, -109, 125],
[49, 2, 7, 6, -4851, 2],
[-9, 5, 3, 8, 27, 7],
[5, 19, 2, 12, -101, 384],
/* two decadic pairs */
[2, 7, 10, 7, -1, 7],
[34, 21, 10, 9, -39034, 791],
/* familiar digits */
[11, 4, 2, 43, 679001, 207],
[-8, 9, 23, 9, 302113, 92],
[-22, 7, 3, 23, 46071, 379],
[-22, 7, 32749, 3, 46071, 379],
[35, 61, 5, 20, 9400, 109],
[-101, 109, 61, 7, 583376, 6649],
[-25, 26, 7, 13, 5571, 137],
[1, 4, 7, 11, 9263, 2837],
[122, 407, 7, 11, -517, 1477],
/* more subtle */
[5, 8, 7, 11, 353, 30809]
]
var sw = 0
var a = Padic.new()
var b = Padic.new()
for (d in data) {
var q = Ratio.new(d[0], d[1])
P = d[2]
K = d[3]
sw = a.r2pa(q, 1)
if (sw == 1) break
a.printf(0)
q.a = d[4]
q.b = d[5]
sw = sw | b.r2pa(q, 1)
if (sw == 1) break
if (sw == 0) {
b.printf(0)
var c = a + b
System.print("+ =")
c.printf(1)
}
System.print()
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #GML | GML |
//Setting a var from an argument passed to the script
var str;
str = argument0
//Takes out all spaces/anything that is not a letter or a number and turns uppercase letters to lowercase
str = string_lettersdigits(string_lower(string_replace(str,' ','')));
var inv;
inv = '';
//for loop that reverses the sequence
var i;
for (i = 0; i < string_length(str); i += 1;)
{
inv += string_copy(str,string_length(str)-i,1);
}
//returns true if the sequence is a palindrome else returns false
return (str == inv);
|
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #11l | 11l | V date = Time(2020, 2, 3)
print(‘First 15 palindrome dates after 2020-02-02 are:’)
V count = 0
L count < 15
V date_formatted = date.format(‘YYYYMMDD’)
I date_formatted == reversed(date_formatted)
print(‘date = ’date.format(‘YYYY-MM-DD’))
count++
date += TimeDelta(days' 1) |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #BBC_BASIC | BBC BASIC | DIM list1%(2) : list1%() = 2, 0, 2
PRINT "partitions(2,0,2):"
PRINT FNpartitions(list1%())
DIM list2%(2) : list2%() = 1, 1, 1
PRINT "partitions(1,1,1):"
PRINT FNpartitions(list2%())
DIM list3%(3) : list3%() = 1, 2, 0, 1
PRINT "partitions(1,2,0,1):"
PRINT FNpartitions(list3%())
END
DEF FNpartitions(list%())
LOCAL i%, j%, n%, p%, o$, x%()
n% = DIM(list%(),1)
DIM x%(SUM(list%())-1)
FOR i% = 0 TO n%
IF list%(i%) THEN
FOR j% = 1 TO list%(i%)
x%(p%) = i%
p% += 1
NEXT
ENDIF
NEXT i%
REPEAT
FOR i% = 0 TO n%
o$ += " ( "
FOR j% = 0 TO DIM(x%(),1)
IF x%(j%) = i% o$ += STR$(j%+1) + " "
NEXT
o$ += ")"
NEXT i%
o$ += CHR$13 + CHR$10
UNTIL NOT FNperm(x%())
= o$
DEF FNperm(x%())
LOCAL i%, j%
FOR i% = DIM(x%(),1)-1 TO 0 STEP -1
IF x%(i%) < x%(i%+1) EXIT FOR
NEXT
IF i% < 0 THEN = FALSE
j% = DIM(x%(),1)
WHILE x%(j%) <= x%(i%) j% -= 1 : ENDWHILE
SWAP x%(i%), x%(j%)
i% += 1
j% = DIM(x%(),1)
WHILE i% < j%
SWAP x%(i%), x%(j%)
i% += 1
j% -= 1
ENDWHILE
= TRUE |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #C | C | #include <stdio.h>
int next_perm(int size, int * nums)
{
int *l, *k, tmp;
for (k = nums + size - 2; k >= nums && k[0] >= k[1]; k--) {};
if (k < nums) return 0;
for (l = nums + size - 1; *l <= *k; l--) {};
tmp = *k; *k = *l; *l = tmp;
for (l = nums + size - 1, k++; k < l; k++, l--) {
tmp = *k; *k = *l; *l = tmp;
}
return 1;
}
void make_part(int n, int * sizes)
{
int x[1024], i, j, *ptr, len = 0;
for (ptr = x, i = 0; i < n; i++)
for (j = 0, len += sizes[i]; j < sizes[i]; j++, *(ptr++) = i);
do {
for (i = 0; i < n; i++) {
printf(" { ");
for (j = 0; j < len; j++)
if (x[j] == i) printf("%d ", j);
printf("}");
}
printf("\n");
} while (next_perm(len, x));
}
int main()
{
int s1[] = {2, 0, 2};
int s2[] = {1, 2, 3, 4};
printf("Part 2 0 2:\n");
make_part(3, s1);
printf("\nPart 1 2 3 4:\n");
make_part(4, s2);
return 1;
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
func StrLen(Str); \Return number of characters in an ASCIIZ string
char Str;
int I;
for I:= 0 to -1>>1-1 do
if Str(I) = 0 then return I;
func Pangram(S);
char S;
int A, I, C;
[A:= 0;
for I:= 0 to StrLen(S)-1 do
[C:= S(I);
if C>=^A & C<=^Z then C:= C or $20;
if C>=^a & C<=^z then [C:= C - ^a; A:= A or 1<<C];
];
return A = $3FFFFFF;
]; \Pangram
int Sentence, I;
[Sentence:=
["The quick brown fox jumps over the lazy dog.",
"Pack my box with five dozen liquor jugs.",
"Now is the time for all good men to come to the aid of their country."];
for I:= 0 to 3-1 do
[Text(0, if Pangram(Sentence(I)) then "yes" else "no");
CrLf(0);
];
] |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Yabasic | Yabasic | sub isPangram$(t$, l1$)
local lt, ll, r$, i, cc, ic
if numparams = 1 then
l1$ = "abcdefghijklmnopqrstuvwxyz"
end if
t$ = lower$(t$)
ll = len(l1$)
for i = 1 to ll
r$ = r$ + " "
next
lt = len(t$)
cc = asc("a")
for i = 1 to lt
ic = asc(mid$(t$, i, 1)) - cc + 1
if ic > 0 and ic <= ll then
mid$(r$, ic, 1) = chr$(ic + cc - 1)
end if
next i
if l1$ = r$ then return "true" else return "false" end if
end sub
print isPangram$("The quick brown fox jumps over the lazy dog.") // --> true
print isPangram$("The quick brown fox jumped over the lazy dog.") // --> false
print isPangram$("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ") // --> true |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Julia | Julia |
"""
First nterms terms of the first 2..max_nstep -step Padovan sequences.
"""
function nstep_Padovan(max_nstep=8, nterms=15)
start = [[], [1, 1, 1]] # for n=0 and n=1 (hidden).
for n in 2:max_nstep
this = start[n][1:n+1] # Initialise from last
while length(this) < nterms
push!(this, sum(this[end - i] for i in 1:n))
end
push!(start, this)
end
return start[3:end]
end
function print_Padovan_seq(p)
println(strip("""
:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Padovan <math>n</math>-step sequences
|- style="background-color: rgb(255, 204, 255);"
! <math>n</math> !! Values
|-
"""))
for (n, seq) in enumerate(p)
println("| $n || $(replace(string(seq[2:end]), r"[ a-zA-Z\[\]]+" => "")), ...\n|-")
end
println("|}")
end
print_Padovan_seq(nstep_Padovan())
|
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[Padovan]
Padovan[2,tmax_]:=Module[{start,a,m},
start={1,1,1};
start=MapIndexed[a[#2[[1]]]==#1&,start];
RecurrenceTable[{a[m]==a[m-2]+a[m-3]}~Join~start,a, {m,tmax}]
]
Padovan[n_,tmax_]:=Module[{start,eq,a,m},
start=Padovan[n-1,n+1];
start=MapIndexed[a[#2[[1]]]==#1&,start];
eq=Range[2,n+1];
eq=Append[start,a[m]==Total[a[m-#]&/@eq]];
RecurrenceTable[eq,a, {m,tmax}]
]
Padovan[2,15]
Padovan[3,15]
Padovan[4,15]
Padovan[5,15]
Padovan[6,15]
Padovan[7,15]
Padovan[8,15] |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Octave | Octave | function pascaltriangle(h)
for i = 0:h-1
for k = 0:h-i
printf(" ");
endfor
for j = 0:i
printf("%3d ", bincoeff(i, j));
endfor
printf("\n");
endfor
endfunction
pascaltriangle(4); |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package pal
func IsPal(s string) bool {
mid := len(s) / 2
last := len(s) - 1
for i := 0; i < mid; i++ {
if s[i] != s[last-i] {
return false
}
}
return true
} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Action.21 | Action! | TYPE Date=[
INT year
BYTE month
BYTE day]
BYTE FUNC IsLeapYear(INT y)
IF y MOD 100=0 THEN
IF y MOD 400=0 THEN
RETURN (1)
ELSE
RETURN (0)
FI
FI
IF y MOD 4=0 THEN
RETURN (1)
FI
RETURN (0)
BYTE FUNC GetMaxDay(INT y BYTE m)
BYTE ARRAY MaxDay=[31 28 31 30 31 30 31 31 30 31 30 31]
IF m=2 AND IsLeapYear(y)=1 THEN
RETURN (29)
FI
RETURN (MaxDay(m-1))
PROC NextDay(Date POINTER d)
BYTE maxD
d.day==+1
maxD=GetMaxDay(d.year,d.month)
IF d.day>maxD THEN
d.day=1
d.month==+1
IF d.month>12 THEN
d.month=1
d.year==+1
FI
FI
RETURN
BYTE FUNC IsPalindrome(Date POINTER d)
INT y
y=d.year
IF y/1000#d.day MOD 10 THEN
RETURN (0)
FI
y==MOD 1000
IF y/100#d.day/10 THEN
RETURN (0)
FI
y==MOD 100
IF y/10#d.month MOD 10 THEN
RETURN (0)
FI
y==MOD 10
IF y#d.month/10 THEN
RETURN (0)
FI
RETURN (1)
PROC PrintB2(BYTE x)
IF x<10 THEN
Put('0)
FI
PrintB(x)
RETURN
PROC PrintDateShort(Date POINTER d)
PrintI(d.year) Put('-)
PrintB2(d.month) Put('-)
PrintB2(d.day)
RETURN
PROC Main()
BYTE count
Date d
count=0
d.year=2020 d.month=2 d.day=3
WHILE count<15
DO
IF IsPalindrome(d) THEN
PrintDateShort(d) PutE()
count==+1
FI
NextDay(d)
OD
RETURN |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #ALGOL_68 | ALGOL 68 | BEGIN # print future palindromic dates #
# a palindromic date must be of the form demn-nm-ed #
# returns a string representation of n with at least 2 digits #
PROC two digits = ( INT n )STRING:
BEGIN
STRING result := whole( ABS n, 0 );
IF ( UPB result - LWB result ) + 1 < 2 THEN "0" +=: result FI;
IF n < 0 THEN "-" +=: result FI;
result
END # two digits # ;
# possible years for a palindromic date #
[]INT mn = ( 1, 10, 11, 20, 21, 30, 40, 50, 60, 70, 80, 90 );
# months corresponding to the year for for a palindromic date #
[]INT nm = ( 10, 1, 11, 2, 12, 3, 4, 5, 6, 7, 8, 9 );
# possible centuaries for a palindromic date #
[]INT de = ( 10, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50
, 51, 52, 60, 61, 62, 70, 71, 72, 80, 81, 82, 90, 91, 92
);
# days corresponding to the centuary for a palindromic date #
[]INT ed = ( 1, 11, 21, 31, 2, 12, 22, 3, 13, 23, 4, 14, 24, 5
, 15, 25, 6, 16, 26, 7, 17, 27, 8, 18, 28, 9, 19, 29
);
# max days per month ( february handled specifically in code ) #
[]INT max dd = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
# current date in local time (Algol 68G extension) #
[]INT date = local time;
INT yy now = local time[ 1 ] MOD 100;
INT cc now = local time[ 1 ] OVER 100;
INT dates to print := 15; # maximum number of dates to print #
FOR c pos FROM LWB de TO UPB de WHILE dates to print > 0 DO
INT cc = de[ c pos ];
INT dd = ed[ c pos ];
FOR y pos FROM LWB nm TO UPB nm WHILE dates to print > 0 DO
INT mm = nm[ y pos ];
INT yy = mn[ y pos ];
IF cc > cc now OR ( cc = cc now AND yy > yy now ) THEN
# have a possible future date #
IF dd <= max dd[ mm ]
OR ( mm = 2 AND dd = 29 AND yy MOD 4 = 0 )
THEN
# have a valid future date #
# no need to test yy = 0 as dd = 0 is impossible #
dates to print -:= 1;
print( ( two digits( cc )
, two digits( yy )
, "-"
, two digits( mm )
, "-"
, two digits( dd )
, newline
)
)
FI
FI
OD
OD
END |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #C.23 | C# | using System;
using System.Linq;
using System.Collections.Generic;
public static class OrderedPartitions
{
public static void Main() {
var input = new [] { new[] { 0, 0, 0, 0, 0 }, new[] { 2, 0, 2 }, new[] { 1, 1, 1 } };
foreach (int[] sizes in input) {
foreach (var partition in Partitions(sizes)) {
Console.WriteLine(partition.Select(set => set.Delimit(", ").Encase('{','}')).Delimit(", ").Encase('(', ')'));
}
Console.WriteLine();
}
}
static IEnumerable<IEnumerable<int[]>> Partitions(params int[] sizes) {
var enumerators = new IEnumerator<int[]>[sizes.Length];
var unused = Enumerable.Range(1, sizes.Sum()).ToSortedSet();
var arrays = sizes.Select(size => new int[size]).ToArray();
for (int s = 0; s >= 0; ) {
if (s == sizes.Length) {
yield return arrays;
s--;
}
if (enumerators[s] == null) {
enumerators[s] = Combinations(sizes[s], unused.ToArray()).GetEnumerator();
} else {
unused.UnionWith(arrays[s]);
}
if (enumerators[s].MoveNext()) {
enumerators[s].Current.CopyTo(arrays[s], 0);
unused.ExceptWith(arrays[s]);
s++;
} else {
enumerators[s] = null;
s--;
}
}
}
static IEnumerable<T[]> Combinations<T>(int count, params T[] array) {
T[] result = new T[count];
foreach (int pattern in BitPatterns(array.Length - count, array.Length)) {
for (int b = 1 << (array.Length - 1), i = 0, r = 0; b > 0; b >>= 1, i++) {
if ((pattern & b) == 0) result[r++] = array[i];
}
yield return result;
}
}
static IEnumerable<int> BitPatterns(int ones, int length) {
int initial = (1 << ones) - 1;
int blockMask = (1 << length) - 1;
for (int v = initial; v >= initial; ) {
yield return v;
if (v == 0) break;
int w = (v | (v - 1)) + 1;
w |= (((w & -w) / (v & -v)) >> 1) - 1;
v = w & blockMask;
}
}
static string Delimit<T>(this IEnumerable<T> source, string separator) => string.Join(separator, source);
static string Encase(this string s, char start, char end) => start + s + end;
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #zkl | zkl | var letters=["a".."z"].pump(String); //-->"abcdefghijklmnopqrstuvwxyz"
fcn isPangram(text){(not (letters-text.toLower()))} |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Nim | Nim | import math, sequtils, strutils
proc rn(n, k: Positive): seq[int] =
assert k >= 2
result = if n == 2: @[1, 1, 1] else: rn(n - 1, n + 1)
while result.len != k:
result.add sum(result[^(n + 1)..^2])
for n in 2..8:
echo n, ": ", rn(n, 15).mapIt(($it).align(3)).join(" ") |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Perl | Perl | use strict;
use warnings;
use feature <state say>;
use List::Util 'sum';
use List::Lazy 'lazy_list';
say 'Padovan N-step sequences; first 25 terms:';
for our $N (2..8) {
my $pad_n = lazy_list {
state $n = 2;
state @pn = (1, 1, 1);
push @pn, sum @pn[ grep { $_ >= 0 } $n-$N .. $n++ - 1 ];
$pn[-4]
};
print "N = $N |";
print ' ' . $pad_n->next() for 1..25;
print "\n"
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Oforth | Oforth | : pascal(n) [ 1 ] #[ dup println dup 0 + 0 rot + zipWith(#+) ] times(n) drop ; |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Groovy | Groovy | def isPalindrome = { String s ->
s == s?.reverse()
} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #Ada | Ada | with Ada.Text_IO;
with Ada.Calendar.Formatting;
with Ada.Calendar.Arithmetic;
procedure Palindrome_Dates is
Desired_Count : constant := 15;
Start_Date : constant String := "2020-01-01 00:00:00";
use Ada.Calendar;
function Is_Palindrome_Date (Date : Time) return Boolean is
Image : String renames Formatting.Image (Date);
begin
return
Image (1) = Image (10) and
Image (2) = Image (9) and
Image (3) = Image (7) and
Image (4) = Image (6);
end Is_Palindrome_Date;
Date : Ada.Calendar.Time := Formatting.Value (Start_Date);
Count : Natural := 0;
use type Ada.Calendar.Arithmetic.Day_Count;
begin
loop
if Is_Palindrome_Date (Date) then
Ada.Text_IO.Put_Line (Formatting.Image (Date) (1 .. 10));
Count := Count + 1;
end if;
exit when Count = Desired_Count;
Date := Date + 1;
end loop;
end Palindrome_Dates; |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #C.2B.2B | C++ |
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
void partitions(std::vector<size_t> args) {
size_t sum = std::accumulate(std::begin(args), std::end(args), 0);
std::vector<size_t> nums(sum);
std::iota(std::begin(nums), std::end(nums), 1);
do {
size_t total_index = 0;
std::vector<std::vector<size_t>> parts;
for (const auto& a : args) {
std::vector<size_t> part;
bool cont = true;
for (size_t j = 0; j < a; ++j) {
for (const auto& p : part) {
if (nums[total_index] < p) {
cont = false;
break;
}
}
if (cont) {
part.push_back(nums[total_index]);
++total_index;
}
}
if (part.size() != a) {
break;
}
parts.push_back(part);
}
if (parts.size() == args.size()) {
std::cout << "(";
for (const auto& p : parts) {
std::cout << "{ ";
for (const auto& e : p) {
std::cout << e << " ";
}
std::cout << "},";
}
std::cout << ")," << std::endl;
}
} while (std::next_permutation(std::begin(nums), std::end(nums)));
}
int main() {
std::vector<size_t> args = { 2, 0, 2 };
partitions(args);
std::cin.ignore();
std::cin.get();
return 0;
} |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Phix | Phix | with javascript_semantics
function padovann(integer n,t)
if n<2 or t<3 then return repeat(1,t) end if
sequence p = padovann(n-1, t)
for i=n+2 to t do
p[i] = sum(p[i-n-1..i-2])
end for
return p
end function
constant t = 15,
fmt = "%d: %d %d %d %d %d %d %d %2d %2d %2d %2d %2d %3d %3d %3d\n"
printf(1,"First %d terms of the Padovan n-step number sequences:\n",t)
for n=2 to 8 do
printf(1,fmt,n&padovann(n,t))
end for
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Oz | Oz | declare
fun {NextLine Xs}
{List.zip 0|Xs {Append Xs [0]}
fun {$ Left Right}
Left + Right
end}
end
fun {Triangle N}
{List.take {Iterate [1] NextLine} N}
end
fun lazy {Iterate I F}
I|{Iterate {F I} F}
end
%% Only works nicely for N =< 5.
proc {PrintTriangle T}
N = {Length T}
in
for
Line in T
Indent in N-1..0;~1
do
for _ in 1..Indent do {System.printInfo " "} end
for L in Line do {System.printInfo L#" "} end
{System.printInfo "\n"}
end
end
in
{PrintTriangle {Triangle 5}} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Haskell | Haskell | is_palindrome x = x == reverse x |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #AppleScript | AppleScript | on palindromeDates(startYear, targetNumber)
script o
property output : {}
end script
set counter to 0
set y to startYear
repeat until ((counter = targetNumber) or (y > 9999))
-- Derive a month number from the last two digits of the current year number. It's valid if it's in the range 1 to 12.
set m to y mod 10 * 10 + y mod 100 div 10
if ((m > 0) and (m < 13)) then
-- Derive a day number from the first two digits of the year number.
set d to y div 100 mod 10 * 10 + y div 1000
-- It's valid if it's between 1 and 28. Otherwise, if it's between 29 and 31, check that it fits the month and year.
-- In fact though, it'll only ever be 2 or 12 in the period containing the 15 palindromic dates after 2020.
if ((d > 0) and ¬
((d < 29) ¬
or ((d < 31) and ((m is not 2) or ((d is 29) and (y mod 4 is 0) and ((y mod 100 > 0) or (y mod 400 is 0))))) ¬
or ((d is 31) and (m is not in {2, 4, 9, 6, 11})))) then
-- If the figures represent a valid date, add a yyyy-mm-dd format text to the end of the output list.
tell ((100000000 + y * 10000 + m * 100 + d) as text) to ¬
set end of o's output to text 2 thru 5 & ("-" & text 6 thru 7) & ("-" & text 8 thru 9)
set counter to counter + 1
end if
end if
set y to y + 1
end repeat
return o's output
end palindromeDates
palindromeDates(2021, 15) |
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #Common_Lisp | Common Lisp | (defun fill-part (x i j l)
(let ((e (elt x i)))
(loop for c in l do
(loop while (>= j (length e)) do
(setf j 0 e (elt x (incf i))))
(setf (elt e j) c)
(incf j))))
;;; take a list of lists and return next partitioning
;;; it's caller's responsibility to ensure each sublist is sorted
(defun next-part (list cmp)
(let* ((l (coerce list 'vector))
(i (1- (length l)))
(e (elt l i)))
(loop while (<= 0 (decf i)) do
;; e holds all the right most elements
(let ((p (elt l i)) (q (car (last e))))
;; find the right-most list that has an element that's smaller
;; than _something_ in later lists
(when (and p (funcall cmp (first p) q))
;; find largest element that can be increased
(loop for j from (1- (length p)) downto 0 do
(when (funcall cmp (elt p j) q)
;; find the smallest element that's larger than
;; that largest
(loop for x from 0 to (1- (length e)) do
(when (funcall cmp (elt p j) (elt e x))
(rotatef (elt p j) (elt e x))
(loop while (< (incf j) (length p)) do
(setf (elt p j) (elt e (incf x))
(elt e x) nil))
(fill-part l i j (remove nil e))
(return-from next-part l))))
(setf e (append e (list (elt p j))))))
(setf e (append e p))))))
(let ((a '#((1 2) () (3 4))))
(loop while a do
(format t "~a~%" a)
(setf a (next-part a #'<))))
(write-line "with dupe elements:")
(let ((a '#((a c) (c c d))))
(loop while a do
(format t "~a~%" a)
(setf a (next-part a #'string<)))) |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Python | Python | def pad_like(max_n=8, t=15):
"""
First t terms of the first 2..max_n-step Padovan sequences.
"""
start = [[], [1, 1, 1]] # for n=0 and n=1 (hidden).
for n in range(2, max_n+1):
this = start[n-1][:n+1] # Initialise from last
while len(this) < t:
this.append(sum(this[i] for i in range(-2, -n - 2, -1)))
start.append(this)
return start[2:]
def pr(p):
print('''
:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Padovan <math>n</math>-step sequences
|- style="background-color: rgb(255, 204, 255);"
! <math>n</math> !! Values
|-
'''.strip())
for n, seq in enumerate(p, 2):
print(f"| {n:2} || {str(seq)[1:-1].replace(' ', '')+', ...'}\n|-")
print('|}')
if __name__ == '__main__':
p = pad_like()
pr(p) |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #Raku | Raku | say 'Padovan N-step sequences; first 25 terms:';
for 2..8 -> \N {
my @n-step = 1, 1, 1, { state $n = 2; @n-step[ ($n - N .. $n++ - 1).grep: * >= 0 ].sum } … *;
put "N = {N} |" ~ @n-step[^25]».fmt: "%5d";
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #PARI.2FGP | PARI/GP | pascals_triangle(N)= {
my(row=[],prevrow=[]);
for(x=1,N,
if(x>5,break(1));
row=eval(Vec(Str(11^(x-1))));
print(row));
prevrow=row;
for(y=6,N,
for(p=2,#prevrow,
row[p]=prevrow[p-1]+prevrow[p]);
row=concat(row,1);
prevrow=row;
print(row);
);
} |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #HicEst | HicEst | result = Palindrome( "In girum imus nocte et consumimur igni" ) ! returns 1
END
FUNCTION Palindrome(string)
CHARACTER string, CopyOfString
L = LEN(string)
ALLOCATE(CopyOfString, L)
CopyOfString = string
EDIT(Text=CopyOfString, UpperCase=L)
L = L - EDIT(Text=CopyOfString, End, Left=' ', Delete, DO=L) ! EDIT returns number of deleted spaces
DO i = 1, L/2
Palindrome = CopyOfString(i) == CopyOfString(L - i + 1)
IF( Palindrome == 0 ) RETURN
ENDDO
END |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #AutoHotkey | AutoHotkey | date := 20200202
counter := 0
while (counter < 15) {
date += 1, days
date := SubStr(date, 1, 8)
if (date = reverse(date))
{
FormatTime, fdate, % date, yyyy-MM-dd
output .= fdate "`n"
counter++
}
}
MsgBox, 262144, , % output
return
reverse(n){
for i, v in StrSplit(n)
output := v output
return output
} |
http://rosettacode.org/wiki/Palindrome_dates | Palindrome dates | Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Task
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
| #AWK | AWK |
# syntax: GAWK -f PALINDROME_DATES.AWK
BEGIN {
show = 15
year_b = 2020
year_e = 9999
split("31,28,31,30,31,30,31,31,30,31,30,31",daynum_array,",") # days per month in non leap year
for (y=year_b; y<=year_e; y++) {
daynum_array[2] = (y % 400 == 0 || (y % 4 == 0 && y % 100)) ? 29 : 28
for (m=1; m<=12; m++) {
for (d=1; d<=daynum_array[m]; d++) {
ymd = sprintf("%04d%02d%02d",y,m,d)
if (substr(ymd,1,1) == substr(ymd,8,1)) { # speed up
if (ymd == reverse(ymd)) {
arr[++n] = ymd
}
}
}
}
}
printf("%04d0101-%04d1231=%d years, %d palindromes, showing first and last %d\n",year_b,year_e,year_e-year_b+1,n,show)
printf("YYYYMMDD YYYYMMDD\n")
for (i=1; i<=show; i++) {
printf("%s %s\n",arr[i],arr[n-show+i])
}
exit(0)
}
function reverse(str, i,rts) {
for (i=length(str); i>=1; i--) {
rts = rts substr(str,i,1)
}
return(rts)
}
|
http://rosettacode.org/wiki/Ordered_partitions | Ordered partitions | In this task we want to find the ordered partitions into fixed-size blocks.
This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task.
p
a
r
t
i
t
i
o
n
s
(
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
)
{\displaystyle partitions({\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n})}
should generate all distributions of the elements in
{
1
,
.
.
.
,
Σ
i
=
1
n
a
r
g
i
}
{\displaystyle \{1,...,\Sigma _{i=1}^{n}{\mathit {arg}}_{i}\}}
into
n
{\displaystyle n}
blocks of respective size
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
.
Example 1:
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
would create:
{({1, 2}, {}, {3, 4}),
({1, 3}, {}, {2, 4}),
({1, 4}, {}, {2, 3}),
({2, 3}, {}, {1, 4}),
({2, 4}, {}, {1, 3}),
({3, 4}, {}, {1, 2})}
Example 2:
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
would create:
{({1}, {2}, {3}),
({1}, {3}, {2}),
({2}, {1}, {3}),
({2}, {3}, {1}),
({3}, {1}, {2}),
({3}, {2}, {1})}
Note that the number of elements in the list is
(
a
r
g
1
+
a
r
g
2
+
.
.
.
+
a
r
g
n
a
r
g
1
)
⋅
(
a
r
g
2
+
a
r
g
3
+
.
.
.
+
a
r
g
n
a
r
g
2
)
⋅
…
⋅
(
a
r
g
n
a
r
g
n
)
{\displaystyle {{\mathit {arg}}_{1}+{\mathit {arg}}_{2}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{1}}\cdot {{\mathit {arg}}_{2}+{\mathit {arg}}_{3}+...+{\mathit {arg}}_{n} \choose {\mathit {arg}}_{2}}\cdot \ldots \cdot {{\mathit {arg}}_{n} \choose {\mathit {arg}}_{n}}}
(see the definition of the binomial coefficient if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted
(i.e. the multinomial coefficient).
Also,
p
a
r
t
i
t
i
o
n
s
(
1
,
1
,
1
)
{\displaystyle partitions(1,1,1)}
creates the permutations of
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
and thus there would be
3
!
=
6
{\displaystyle 3!=6}
elements in the list.
Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of
p
a
r
t
i
t
i
o
n
s
(
2
,
0
,
2
)
{\displaystyle partitions(2,0,2)}
. If the programming language does not support polyvariadic functions pass a list as an argument.
Notation
Here are some explanatory remarks on the notation used in the task description:
{
1
,
…
,
n
}
{\displaystyle \{1,\ldots ,n\}}
denotes the set of consecutive numbers from
1
{\displaystyle 1}
to
n
{\displaystyle n}
, e.g.
{
1
,
2
,
3
}
{\displaystyle \{1,2,3\}}
if
n
=
3
{\displaystyle n=3}
.
Σ
{\displaystyle \Sigma }
is the mathematical notation for summation, e.g.
Σ
i
=
1
3
i
=
6
{\displaystyle \Sigma _{i=1}^{3}i=6}
(see also [1]).
a
r
g
1
,
a
r
g
2
,
.
.
.
,
a
r
g
n
{\displaystyle {\mathit {arg}}_{1},{\mathit {arg}}_{2},...,{\mathit {arg}}_{n}}
are the arguments — natural numbers — that the sought function receives.
| #D | D | import std.stdio, std.algorithm, std.range, std.array, std.conv,
combinations3;
alias iRNG = int[];
iRNG[][] orderPart(iRNG blockSize...) {
iRNG tot = iota(1, 1 + blockSize.sum).array;
iRNG[][] p(iRNG s, in iRNG b) {
if (b.empty)
return [[]];
iRNG[][] res;
foreach (c; s.combinations(b[0]))
foreach (r; p(setDifference(s, c).array, b.dropOne))
res ~= c.dup ~ r;
return res;
}
return p(tot, blockSize);
}
void main(in string[] args) {
auto b = args.length > 1 ? args.dropOne.to!(int[]) : [2, 0, 2];
writefln("%(%s\n%)", b.orderPart);
} |
http://rosettacode.org/wiki/Padovan_n-step_number_sequences | Padovan n-step number sequences | As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences.
The Fibonacci-like sequences can be defined like this:
For n == 2:
start: 1, 1
Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n == 2
For n == N:
start: First N terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-1) + R(N, x-2) + ... R(N, x-N))
For this task we similarly define terms of the first 2..n-step Padovan sequences as:
For n == 2:
start: 1, 1, 1
Recurrence: R(n, x) = R(n, x-2) + R(n, x-3); for n == 2
For n == N:
start: First N + 1 terms of R(N-1, x)
Recurrence: R(N, x) = sum(R(N, x-2) + R(N, x-3) + ... R(N, x-N-1))
The initial values of the sequences are:
Padovan
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Values
OEIS Entry
2
1,1,1,2,2,3,4,5,7,9,12,16,21,28,37, ...
A134816: 'Padovan's spiral numbers'
3
1,1,1,2,3,4,6,9,13,19,28,41,60,88,129, ...
A000930: 'Narayana's cows sequence'
4
1,1,1,2,3,5,7,11,17,26,40,61,94,144,221, ...
A072465: 'A Fibonacci-like model in which each pair of rabbits dies after the birth of their 4th litter'
5
1,1,1,2,3,5,8,12,19,30,47,74,116,182,286, ...
A060961: 'Number of compositions (ordered partitions) of n into 1's, 3's and 5's'
6
1,1,1,2,3,5,8,13,20,32,51,81,129,205,326, ...
<not found>
7
1,1,1,2,3,5,8,13,21,33,53,85,136,218,349, ...
A117760: 'Expansion of 1/(1 - x - x^3 - x^5 - x^7)'
8
1,1,1,2,3,5,8,13,21,34,54,87,140,225,362, ...
<not found>
Task
Write a function to generate the first
t
{\displaystyle t}
terms, of the first 2..max_n Padovan
n
{\displaystyle n}
-step number sequences as defined above.
Use this to print and show here at least the first t=15 values of the first 2..8
n
{\displaystyle n}
-step sequences.
(The OEIS column in the table above should be omitted).
| #REXX | REXX | /*REXX program computes and shows the Padovan sequences for M steps for N numbers. */
parse arg n m . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 15 /*Not specified? Then use the default.*/
if m=='' | m=="," then m= 8 /* " " " " " " */
w.= 1 /*W.c: the maximum width of a column. */
do #=2 for m-1
@.= 0; @.0= 1; @.1= 1; @.2= 1 /*initialize 3 terms of the Padovan seq*/
$= @.0 /*initials the list with the zeroth #. */
do k=2 for n-1; z= pd(k-1)
w.k= max(w.k, length(z)); $= $ z /*find maximum width for a specific col*/
end /*k*/
$.#= $ /*save each unaligned line for later. */
end /*#*/
oW= 1
do col=1 for n; oW= oW + w.col + 1 /*add up the width of each column. */
end /*col*/
iW= length(m) + 2; pad= left('', 20*(n<21)) /*maybe indent.*/
say pad center('M', iW, " ")"│"center('first ' n " Padovan sequence with step M", oW)
say pad center('', iW, "─")"┼"center('', oW, "─")
do out=2 for m-1; $= /*align columnar elements for outputs. */
do j=1 for n; $= $ right(word($.out, j), w.j) /*align the columns. */
end /*j*/
say pad center(out,length(m)+2)'│'$ /*display a line of columnar elements. */
end /*out*/
say pad center('', length(m)+2, "─")"┴"center('', oW, "─")
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
pd: procedure expose @. #; parse arg x; if @.x\==0 then return @.x /*@.x defined?*/
do k=1 for #; _= x-1-k; @.x= @.x + @._; end; return @.x |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Pascal | Pascal | Program PascalsTriangle(output);
procedure Pascal(r : Integer);
var
i, c, k : Integer;
begin
for i := 0 to r-1 do
begin
c := 1;
for k := 0 to i do
begin
write(c:3);
c := (c * (i-k)) div (k+1);
end;
writeln;
end;
end;
begin
Pascal(9)
end. |
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.