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/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
| #Go | Go |
package main
import "fmt"
func printTriangle(n int) {
// degenerate cases
if n <= 0 {
return
}
fmt.Println(1)
if n == 1 {
return
}
// iterate over rows, zero based
a := make([]int, (n+1)/2)
a[0] = 1
for row, middle := 1, 0; row < n; row++ {
// generate new row
even := row&1 == 0
if even {
a[middle+1] = a[middle] * 2
}
for i := middle; i > 0; i-- {
a[i] += a[i-1]
}
// print row
for i := 0; i <= middle; i++ {
fmt.Print(a[i], " ")
}
if even {
middle++
}
for i := middle; i >= 0; i-- {
fmt.Print(a[i], " ")
}
fmt.Println("")
}
}
func main() {
printTriangle(4)
}
|
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Prolog | Prolog | rpn(L) :-
writeln('Token Action Stack'),
parse(L, [],[X] ,[]),
format('~nThe final output value is ~w~n', [X]).
% skip spaces
parse([X|L], St) -->
{char_type(X, white)},
parse(L, St).
% detect operators
parse([Op|L], [Y, X | St]) -->
{ is_op(Op, X, Y, V),
writef(' %s', [[Op]]),
with_output_to(atom(Str2), writef('Apply %s on top of stack', [[Op]])),
writef(' %35l', [Str2]),
writef('%w\n', [[V | St]])},
parse(L, [V | St]).
% detect number
parse([N|L], St) -->
{char_type(N, digit)},
parse_number(L, [N], St).
% string is finished
parse([], St) --> St.
% compute numbers
parse_number([N|L], NC, St) -->
{char_type(N, digit)},
parse_number(L, [N|NC], St).
parse_number(S, NC, St) -->
{ reverse(NC, RNC),
number_chars(V, RNC),
writef('%5r', [V]),
with_output_to(atom(Str2), writef('Push num %w on top of stack', [V])),
writef(' %35l', [Str2]),
writef('%w\n', [[V | St]])},
parse(S, [V|St]).
% defining operations
is_op(42, X, Y, V) :- V is X*Y.
is_op(43, X, Y, V) :- V is X+Y.
is_op(45, X, Y, V) :- V is X-Y.
is_op(47, X, Y, V) :- V is X/Y.
is_op(94, X, Y, V) :- V is X**Y. |
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
| #CoffeeScript | CoffeeScript |
String::isPalindrome = ->
for i in [0...@length / 2] when @[i] isnt @[@length - (i + 1)]
return no
yes
String::stripped = -> @toLowerCase().replace /\W/gi, ''
console.log "'#{ str }' : #{ str.stripped().isPalindrome() }" for str in [
'In girum imus nocte et consumimur igni'
'A man, a plan, a canal: Panama!'
'There is no spoon.'
]
|
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
| #Logo | Logo | to remove.all :s :set
if empty? :s [output :set]
if word? :s [output remove.all butfirst :s remove first :s :set]
output remove.all butfirst :s remove.all first :s :set
end
to pangram? :s
output empty? remove.all :s "abcdefghijklmnopqrstuvwxyz
end
show pangram? [The five boxing wizards jump quickly.] ; 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
| #Lua | Lua | require"lpeg"
S, C = lpeg.S, lpeg.C
function ispangram(s)
return #(C(S(s)^0):match"abcdefghijklmnopqrstuvwxyz") == 26
end
print(ispangram"waltz, bad nymph, for quick jigs vex")
print(ispangram"bobby")
print(ispangram"long sentence") |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #VBScript | VBScript |
Function pascal_upper(i,j)
WScript.StdOut.Write "Pascal Upper"
WScript.StdOut.WriteLine
For l = i To j
For m = i To j
If l <= m Then
WScript.StdOut.Write binomial(m,l) & vbTab
Else
WScript.StdOut.Write 0 & vbTab
End If
Next
WScript.StdOut.WriteLine
Next
WScript.StdOut.WriteLine
End Function
Function pascal_lower(i,j)
WScript.StdOut.Write "Pascal Lower"
WScript.StdOut.WriteLine
For l = i To j
For m = i To j
If l >= m Then
WScript.StdOut.Write binomial(l,m) & vbTab
Else
WScript.StdOut.Write 0 & vbTab
End If
Next
WScript.StdOut.WriteLine
Next
WScript.StdOut.WriteLine
End Function
Function pascal_symmetric(i,j)
WScript.StdOut.Write "Pascal Symmetric"
WScript.StdOut.WriteLine
For l = i To j
For m = i To j
WScript.StdOut.Write binomial(l+m,m) & vbTab
Next
WScript.StdOut.WriteLine
Next
End Function
Function binomial(n,k)
binomial = factorial(n)/(factorial(n-k)*factorial(k))
End Function
Function factorial(n)
If n = 0 Then
factorial = 1
Else
For i = n To 1 Step -1
If i = n Then
factorial = n
Else
factorial = factorial * i
End If
Next
End If
End Function
'Test driving
Call pascal_upper(0,4)
Call pascal_lower(0,4)
Call pascal_symmetric(0,4)
|
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
| #Groovy | Groovy | def pascal
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } } |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Python | Python | def op_pow(stack):
b = stack.pop(); a = stack.pop()
stack.append( a ** b )
def op_mul(stack):
b = stack.pop(); a = stack.pop()
stack.append( a * b )
def op_div(stack):
b = stack.pop(); a = stack.pop()
stack.append( a / b )
def op_add(stack):
b = stack.pop(); a = stack.pop()
stack.append( a + b )
def op_sub(stack):
b = stack.pop(); a = stack.pop()
stack.append( a - b )
def op_num(stack, num):
stack.append( num )
ops = {
'^': op_pow,
'*': op_mul,
'/': op_div,
'+': op_add,
'-': op_sub,
}
def get_input(inp = None):
'Inputs an expression and returns list of tokens'
if inp is None:
inp = input('expression: ')
tokens = inp.strip().split()
return tokens
def rpn_calc(tokens):
stack = []
table = ['TOKEN,ACTION,STACK'.split(',')]
for token in tokens:
if token in ops:
action = 'Apply op to top of stack'
ops[token](stack)
table.append( (token, action, ' '.join(str(s) for s in stack)) )
else:
action = 'Push num onto top of stack'
op_num(stack, eval(token))
table.append( (token, action, ' '.join(str(s) for s in stack)) )
return table
if __name__ == '__main__':
rpn = '3 4 2 * 1 5 - 2 3 ^ ^ / +'
print( 'For RPN expression: %r\n' % rpn )
rp = rpn_calc(get_input(rpn))
maxcolwidths = [max(len(y) for y in x) for x in zip(*rp)]
row = rp[0]
print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
for row in rp[1:]:
print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row)))
print('\n The final output value is: %r' % rp[-1][2]) |
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
| #Common_Lisp | Common Lisp | (defun palindrome-p (s)
(string= s (reverse s))) |
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
| #Maple | Maple | #Used built-in StringTools package
is_pangram := proc(str)
local present := StringTools:-LowerCase~(select(StringTools:-HasAlpha, StringTools:-Explode(str)));
local alphabets := {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
present := convert(present, set);
return evalb(present = alphabets);
end proc;
|
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | pangramQ[msg_]:=Complement[CharacterRange["a", "z"], Characters[ToLowerCase[msg]]]=== {} |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
import "/matrix" for Matrix
var binomial = Fn.new { |n, k|
if (n == k) return 1
var prod = 1
var i = n - k + 1
while (i <= n) {
prod = prod * i
i = i + 1
}
return prod / Int.factorial(k)
}
var pascalUpperTriangular = Fn.new { |n|
var m = List.filled(n, null)
for (i in 0...n) {
m[i] = List.filled(n, 0)
for (j in 0...n) m[i][j] = binomial.call(j, i)
}
return Matrix.new(m)
}
var pascalSymmetric = Fn.new { |n|
var m = List.filled(n, null)
for (i in 0...n) {
m[i] = List.filled(n, 0)
for (j in 0...n) m[i][j] = binomial.call(i+j, i)
}
return Matrix.new(m)
}
var pascalLowerTriangular = Fn.new { |n| pascalSymmetric.call(n).cholesky() }
var n = 5
System.print("Pascal upper-triangular matrix:")
Fmt.mprint(pascalUpperTriangular.call(n), 2, 0)
System.print("\nPascal lower-triangular matrix:")
Fmt.mprint(pascalLowerTriangular.call(n), 2, 0)
System.print("\nPascal symmetric matrix:")
Fmt.mprint(pascalSymmetric.call(n), 2, 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
| #GW-BASIC | GW-BASIC | 10 INPUT "Number of rows? ",R
20 FOR I=0 TO R-1
30 C=1
40 FOR K=0 TO I
50 PRINT USING "####";C;
60 C=C*(I-K)/(K+1)
70 NEXT
80 PRINT
90 NEXT |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Quackery | Quackery |
[ stack ] is switch.arg ( --> [ )
[ switch.arg put ] is switch ( x --> )
[ switch.arg release ] is otherwise ( --> )
[ switch.arg share
!= iff ]else[ done
otherwise
]'[ do ]done[ ] is case ( x --> )
[ say "Applying: "
swap echo$ sp
temp take
temp take
swap rot do
temp put ] is apply ( $ x --> )
[ say "Pushing: " dup echo$ sp
$->n drop temp put ] is isnumber ( $ --> )
[ temp copy echo cr ] is display ( --> )
[ nest$ witheach
[ dup switch
[ $ '+' case [ ' + apply ]
$ '-' case [ ' - apply ]
$ '*' case [ ' * apply ]
$ '/' case [ ' / apply ]
$ '^' case [ ' ** apply ]
otherwise [ isnumber ] ]
display ]
temp take ] is rpncalc ( $ --> n )
$ "3 4 2 * 1 5 - 2 3 ^ ^ / +" rpncalc
say "Result: " echo |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Racket | Racket |
#lang racket
(define (calculate-RPN expr)
(for/fold ([stack '()]) ([token expr])
(printf "~a\t -> ~a~N" token stack)
(match* (token stack)
[((? number? n) s) (cons n s)]
[('+ (list x y s ___)) (cons (+ x y) s)]
[('- (list x y s ___)) (cons (- y x) s)]
[('* (list x y s ___)) (cons (* x y) s)]
[('/ (list x y s ___)) (cons (/ y x) s)]
[('^ (list x y s ___)) (cons (expt y x) s)]
[(x s) (error "calculate-RPN: Cannot calculate the expression:"
(reverse (cons x s)))])))
|
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
| #Component_Pascal | Component Pascal |
MODULE BbtPalindrome;
IMPORT StdLog;
PROCEDURE ReverseStr(str: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR;
VAR
top,middle,i: INTEGER;
c: CHAR;
rStr: POINTER TO ARRAY OF CHAR;
BEGIN
NEW(rStr,LEN(str$) + 1);
top := LEN(str$) - 1; middle := (top - 1) DIV 2;
FOR i := 0 TO middle DO
rStr[i] := str[top - i];
rStr[top - i] := str[i];
END;
IF ODD(LEN(str$)) THEN rStr[middle + 1] := str[middle + 1] END;
RETURN rStr;
END ReverseStr;
PROCEDURE IsPalindrome(str: ARRAY OF CHAR): BOOLEAN;
BEGIN
RETURN str = ReverseStr(str)$;
END IsPalindrome;
PROCEDURE Do*;
VAR
x: CHAR;
BEGIN
StdLog.String("'salalas' is palindrome?:> ");
StdLog.Bool(IsPalindrome("salalas"));StdLog.Ln;
StdLog.String("'madamimadam' is palindrome?:> ");
StdLog.Bool(IsPalindrome("madamimadam"));StdLog.Ln;
StdLog.String("'abcbda' is palindrome?:> ");
StdLog.Bool(IsPalindrome("abcbda"));StdLog.Ln;
END Do;
END BbtPalindrome.
|
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
| #MATLAB | MATLAB | function trueFalse = isPangram(string)
%This works by histogramming the ascii character codes for lower case
%letters contained in the string (which is first converted to all
%lower case letters). Then it finds the index of the first letter that
%is not contained in the string (this is faster than using the find
%without the second parameter). If the find returns an empty array then
%the original string is a pangram, if not then it isn't.
trueFalse = isempty(find( histc(lower(string),(97:122))==0,1 ));
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
| #MATLAB_.2F_Octave | MATLAB / Octave | function trueFalse = isPangram(string)
% X is a histogram of letters
X = sparse(abs(lower(string)),1,1,128,1);
trueFalse = full(all(X('a':'z') > 0));
end |
http://rosettacode.org/wiki/Pascal_matrix_generation | Pascal matrix generation | A pascal matrix is a two-dimensional square matrix holding numbers from Pascal's triangle, also known as binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
Task
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).
Note
The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| #zkl | zkl | fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) }
fcn pascal_upp(n){ [[(i,j); n; n; '{ binomial(j,i) }]]:toMatrix(_) } // [[..]] is list comprehension
fcn pascal_low(n){ [[(i,j); n; n; binomial]]:toMatrix(_) }
fcn pascal_sym(n){ [[(i,j); n; n; '{ binomial(i+j,i) }]]:toMatrix(_) }
fcn toMatrix(ns){ // turn a string of numbers into a square matrix (list of lists)
cols:=ns.len().toFloat().sqrt().toInt();
ns.pump(List,T(Void.Read,cols-1),List.create)
} |
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
| #Haskell | Haskell | zapWith :: (a -> a -> a) -> [a] -> [a] -> [a]
zapWith f xs [] = xs
zapWith f [] ys = ys
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Raku | Raku | my $proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +';
class RPN is Array {
method binop(&op) { self.push: self.pop R[&op] self.pop }
method run($p) {
for $p.words {
say "$_ ({self})";
when /\d/ { self.push: $_ }
when '+' { self.binop: &[+] }
when '-' { self.binop: &[-] }
when '*' { self.binop: &[*] }
when '/' { self.binop: &[/] }
when '^' { self.binop: &[**] }
default { die "$_ is bogus" }
}
say self;
}
}
RPN.new.run($proggie); |
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
| #Cowgol | Cowgol | include "cowgol.coh";
# Check if a string is a palindrome
sub palindrome(word: [uint8]): (r: uint8) is
r := 1;
# empty string is a palindrome
if [word] == 0 then
return;
end if;
# find the end of the word
var end_ := word;
while [@next end_] != 0 loop
end_ := @next end_;
end loop;
# check if bytes match in both directions
while word < end_ loop
if [word] != [end_] then
r := 0;
return;
end if;
word := @next word;
end_ := @prev end_;
end loop;
end sub;
# Check if a string is an inexact palindrome
sub inexact(word: [uint8]): (r: uint8) is
var buf: uint8[256];
var ptr := &buf[0];
# filter non-letters and non-numbers
while [word] != 0 loop
var c := [word];
if (c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') then
# copy lowercase letters and numbers over verbatim
[ptr] := c;
ptr := @next ptr;
elseif c >= 'A' and c <= 'Z' then
# make uppercase letters lowercase
[ptr] := c | 32;
ptr := @next ptr;
end if;
word := @next word;
end loop;
[ptr] := 0;
r := palindrome(&buf[0]);
end sub;
var tests: [uint8][] := {
"civic", "level", "racecar",
"A man, a plan, a canal: Panama",
"Egad, a base tone denotes a bad age",
"There is no spoon."
};
var i: @indexof tests := 0;
while i < @sizeof tests loop
print(tests[i]);
print(": ");
if palindrome(tests[i]) == 1 then
print("exact palindrome\n");
elseif inexact(tests[i]) == 1 then
print("inexact palindrome\n");
else
print("not a palindrome\n");
end if;
i := i + 1;
end loop; |
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
| #min | min | "abcdefghijklmnopqrstuvwxyz" "" split =alphabet
('alphabet dip lowercase (swap match) prepend all?) :pangram?
"The quick brown fox jumps over the lazy dog." pangram? puts |
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
| #MiniScript | MiniScript | sentences = ["The quick brown fox jumps over the lazy dog.",
"Peter Piper picked a peck of pickled peppers.",
"Waltz job vexed quick frog nymphs."]
alphabet = "abcdefghijklmnopqrstuvwxyz"
pangram = function (toCheck)
sentence = toCheck.lower
fail = false
for c in alphabet
if sentence.indexOf(c) == null then return false
end for
return true
end function
for sentence in sentences
if pangram(sentence) then
print """" + sentence + """ is a Pangram"
else
print """" + sentence + """ is not a Pangram"
end if
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
| #HicEst | HicEst | CALL Pascal(30)
SUBROUTINE Pascal(rows)
CHARACTER fmt*6
WRITE(Text=fmt, Format='"i", i5.5') 1+rows/4
DO row = 0, rows-1
n = 1
DO k = 0, row
col = rows*(rows-row+2*k)/4
WRITE(Row=row+1, Column=col, F=fmt) n
n = n * (row - k) / (k + 1)
ENDDO
ENDDO
END |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #REXX | REXX | /* REXX ***************************************************************
* 09.11.2012 Walter Pachl translates from PL/I
**********************************************************************/
fid='rpl.txt'
ex=linein(fid)
Say 'Input:' ex
/* ex=' 3 4 2 * 1 5 - 2 3 ^ ^ / +' */
Numeric Digits 15
expr=''
st.=0
Say 'Stack contents:'
do While ex<>''
Parse Var ex ch +1 ex
expr=expr||ch;
if ch<>' ' then do
select
When pos(ch,'0123456789')>0 Then Do
Call stack ch
Iterate
End
when ch='+' Then do; operand=getstack(); st.sti = st.sti + operand; end;
when ch='-' Then do; operand=getstack(); st.sti = st.sti - operand; end;
when ch='*' Then do; operand=getstack(); st.sti = st.sti * operand; end;
when ch='/' Then do; operand=getstack(); st.sti = st.sti / operand; end;
when ch='^' Then do; operand=getstack(); st.sti = st.sti ** operand; end;
end;
call show_stack
end
end
Say 'The reverse polish expression = 'expr
Say 'The evaluated expression = 'st.1
Exit
stack: Procedure Expose st.
/* put the argument on top of the stack */
z=st.0+1
st.z=arg(1)
st.0=z
Return
getstack: Procedure Expose st. sti
/* remove and return the stack's top element */
z=st.0
stk=st.z
st.0=st.0-1
sti=st.0
Return stk
show_stack: procedure Expose st.
/* show the stack's contents */
ol=''
do i=1 To st.0
ol=ol format(st.i,5,10)
End
Say ol
Return |
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
| #Crystal | Crystal |
def palindrome(s)
s == s.reverse
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
| #ML | ML | fun to_locase s = implode ` map (c_downcase) ` explode s
fun is_pangram
(h :: t, T) =
let
val flen = len (filter (fn c = c eql h) T)
in
if (flen = 0) then
false
else
is_pangram (t, T)
end
| ([], T) = true
| S = is_pangram (explode "abcdefghijklmnopqrstuvwxyz", explode ` to_locase S)
fun is_pangram_i
(h :: t, T) =
let
val flen = len (filter (fn c = c eql h) T)
in
if (flen = 0) then
false
else
is_pangram (t, T)
end
| ([], T) = true
| (A,S) = is_pangram (explode A, explode ` to_locase S)
fun test (f, arg, res, ok, notok) = if (f arg eql res) then ("'" @ arg @ "' " @ ok) else ("'" @ arg @ "' " @ notok)
fun test2 (f, arg, res, ok, notok) = if (f arg eql res) then ("'" @ ref (arg,1) @ "' " @ ok) else ("'" @ ref (arg,1) @ "' " @ notok)
;
println ` test (is_pangram, "The quick brown fox jumps over the lazy dog", true, "is a pangram", "is not a pangram");
println ` test (is_pangram, "abcdefghijklopqrstuvwxyz", true, "is a pangram", "is not a pangram");
val SValphabet = "abcdefghijklmnopqrstuvwxyzåäö";
val SVsentence = "Yxskaftbud, ge vår wczonmö iq hjälp";
println ` test2 (is_pangram_i, (SValphabet, SVsentence), true, "is a Swedish pangram", "is not a Swedish pangram");
|
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
| #Icon_and_Unicon | Icon and Unicon | link math
procedure main(A)
every n := !A do { # for each command line argument
n := integer(\n) | &null
pascal(n)
}
end
procedure pascal(n) #: Pascal triangle
/n := 16
write("width=", n, " height=", n) # carpet header
fw := *(2 ^ n)+1
every i := 0 to n - 1 do {
writes(repl(" ",fw*(n-i)/2))
every j := 0 to n - 1 do
writes(center(binocoef(i, j),fw) | break)
write()
}
end |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Ruby | Ruby | rpn = RPNExpression("3 4 2 * 1 5 - 2 3 ^ ^ / +")
value = rpn.eval |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Run_BASIC | Run BASIC | prn$ = "3 4 2 * 1 5 - 2 3 ^ ^ / + "
j = 0
while word$(prn$,i + 1," ") <> ""
i = i + 1
n$ = word$(prn$,i," ")
if n$ < "0" or n$ > "9" then
num1 = val(word$(stack$,s," "))
num2 = val(word$(stack$,s-1," "))
n = op(n$,num2,num1)
s = s - 1
stack$ = stk$(stack$,s -1,str$(n))
print "Push Opr ";n$;" to stack: ";stack$
else
s = s + 1
stack$ = stack$ + n$ + " "
print "Push Num ";n$;" to stack: ";stack$
end if
wend
function stk$(stack$,s,a$)
for i = 1 to s
stk$ = stk$ + word$(stack$,i," ") + " "
next i
stk$ = stk$ + a$ + " "
end function
FUNCTION op(op$,a,b)
if op$ = "*" then op = a * b
if op$ = "/" then op = a / b
if op$ = "^" then op = a ^ b
if op$ = "+" then op = a + b
if op$ = "-" then op = a - b
end function |
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
| #D | D | import std.traits, std.algorithm;
bool isPalindrome1(C)(in C[] s) pure /*nothrow*/
if (isSomeChar!C) {
auto s2 = s.dup;
s2.reverse(); // works on Unicode too, not nothrow.
return s == s2;
}
void main() {
alias pali = isPalindrome1;
assert(pali(""));
assert(pali("z"));
assert(pali("aha"));
assert(pali("sees"));
assert(!pali("oofoe"));
assert(pali("deified"));
assert(!pali("Deified"));
assert(pali("amanaplanacanalpanama"));
assert(pali("ingirumimusnocteetconsumimurigni"));
assert(pali("salà las"));
} |
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
| #Modula-2 | Modula-2 | MODULE Pangrams;
FROM InOut IMPORT WriteString, WriteLn;
FROM Strings IMPORT Length;
(* Check if a string is a pangram *)
PROCEDURE pangram(s: ARRAY OF CHAR): BOOLEAN;
VAR letters: ARRAY [0..25] OF BOOLEAN;
i: CARDINAL;
BEGIN
FOR i := 0 TO 25 DO letters[i] := FALSE; END;
FOR i := 0 TO Length(s)-1 DO
IF (s[i] >= 'A') AND (s[i] <= 'Z') THEN
letters[ORD(s[i]) - ORD('A')] := TRUE;
ELSIF (s[i] >= 'a') AND (s[i] <= 'z') THEN
letters[ORD(s[i]) - ORD('a')] := TRUE;
END;
END;
FOR i := 0 TO 25 DO
IF NOT letters[i] THEN
RETURN FALSE;
END;
END;
RETURN TRUE;
END pangram;
PROCEDURE example(s: ARRAY OF CHAR);
BEGIN
WriteString("'");
WriteString(s);
WriteString("' is ");
IF NOT pangram(s) THEN
WriteString("not ");
END;
WriteString("a pangram.");
WriteLn();
END example;
BEGIN
example("The quick brown fox jumps over the lazy dog");
example("The five boxing wizards dump quickly");
example("abcdefghijklmnopqrstuvwxyz");
END Pangrams. |
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
| #IDL | IDL | Pro Pascal, n
;n is the number of lines of the triangle to be displayed
r=[1]
print, r
for i=0, (n-2) do begin
pascalrow,r
endfor
End
Pro PascalRow, r
for i=0,(n_elements(r)-2) do begin
r[i]=r[i]+r[i+1]
endfor
r= [1, r]
print, r
End |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Rust | Rust | fn rpn(text: &str) -> f64 {
let tokens = text.split_whitespace();
let mut stack: Vec<f64> = vec![];
println!("input operation stack");
for token in tokens {
print!("{:^5} ", token);
match token.parse() {
Ok(num) => {
stack.push(num);
println!("push {:?}", stack);
}
Err(_) => {
match token {
"+" => {
let b = stack.pop().expect("missing first operand");
let a = stack.pop().expect("missing second operand");
stack.push(a + b);
}
"-" => {
let b = stack.pop().expect("missing first operand");
let a = stack.pop().expect("missing second operand");
stack.push(a - b);
}
"*" => {
let b = stack.pop().expect("missing first operand");
let a = stack.pop().expect("missing second operand");
stack.push(a * b);
}
"/" => {
let b = stack.pop().expect("missing first operand");
let a = stack.pop().expect("missing second operand");
stack.push(a / b);
}
"^" => {
let b = stack.pop().expect("missing first operand");
let a = stack.pop().expect("missing second operand");
stack.push(a.powf(b));
}
_ => panic!("unknown operator {}", token),
}
println!("calculate {:?}", stack);
}
}
}
stack.pop().unwrap_or(0.0)
}
fn main() {
let text = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
println!("\nresult: {}", rpn(text));
} |
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
| #Dart | Dart |
bool isPalindrome(String s){
for(int i = 0; i < s.length/2;i++){
if(s[i] != s[(s.length-1) -i])
return false;
}
return 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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
A2Z = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
pangrams = create_samples
loop p_ = 1 to pangrams[0]
pangram = pangrams[p_]
q_ = A2Z.verify(pangram.upper) -- <= it basically all happens in this function call!
say pangram.left(64)'\-'
if q_ == 0 then -
say ' [OK, a pangram]'
else -
say ' [Not a pangram. Missing:' A2Z.substr(q_, 1)']'
end p_
method create_samples public static returns Rexx
pangrams = ''
x_ = 0
x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumps over a lazy dog.' -- best/shortest pangram
x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumps over the lazy dog.' -- not as short but at least it's still a pangram
x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumped over the lazy dog.' -- common misquote; not a pangram
x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick onyx goblin jumps over the lazy dwarf.'
x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'Bored? Craving a pub quiz fix? Why, just come to the Royal Oak!' -- (Used to advertise a pub quiz in Bowness-on-Windermere)
return pangrams
|
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
| #IS-BASIC | IS-BASIC | 100 PROGRAM "PascalTr.bas"
110 TEXT 80
120 LET ROW=12
130 FOR I=0 TO ROW
140 LET C=1
150 PRINT TAB(37-I*3);
160 FOR K=0 TO I
170 PRINT USING " #### ":C;
180 LET C=C*(I-K)/(K+1)
190 NEXT
200 PRINT
210 NEXT |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Scala | Scala | object RPN {
val PRINT_STACK_CONTENTS: Boolean = true
def main(args: Array[String]): Unit = {
val result = evaluate("3 4 2 * 1 5 - 2 3 ^ ^ / +".split(" ").toList)
println("Answer: " + result)
}
def evaluate(tokens: List[String]): Double = {
import scala.collection.mutable.Stack
val stack: Stack[Double] = new Stack[Double]
for (token <- tokens) {
if (isOperator(token)) token match {
case "+" => stack.push(stack.pop + stack.pop)
case "-" => val x = stack.pop; stack.push(stack.pop - x)
case "*" => stack.push(stack.pop * stack.pop)
case "/" => val x = stack.pop; stack.push(stack.pop / x)
case "^" => val x = stack.pop; stack.push(math.pow(stack.pop, x))
case _ => throw new RuntimeException( s""""$token" is not an operator""")
}
else stack.push(token.toDouble)
if (PRINT_STACK_CONTENTS) {
print("Input: " + token)
print(" Stack: ")
for (element <- stack.seq.reverse) print(element + " ");
println("")
}
}
stack.pop
}
def isOperator(token: String): Boolean = {
token match {
case "+" => true; case "-" => true; case "*" => true; case "/" => true; case "^" => true
case _ => false
}
}
} |
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
| #Delphi | Delphi | uses
SysUtils, StrUtils;
function IsPalindrome(const aSrcString: string): Boolean;
begin
Result := SameText(aSrcString, ReverseString(aSrcString));
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
| #NewLISP | NewLISP |
(context 'PGR) ;; Switch to context (say namespace) PGR
(define (is-pangram? str)
(setf chars (explode (upper-case str))) ;; Uppercase + convert string into a list of chars
(setf is-pangram-status true) ;; Default return value of function
(for (c (char "A") (char "Z") 1 (nil? is-pangram-status)) ;; For loop with break condition
(if (not (find (char c) chars)) ;; If char not found in list, "is-pangram-status" becomes "nil"
(setf is-pangram-status nil)
)
)
is-pangram-status ;; Return current value of symbol "is-pangram-status"
)
(context 'MAIN) ;; Back to MAIN context
;; - - - - - - - - - -
(println (PGR:is-pangram? "abcdefghijklmnopqrstuvwxyz")) ;; Print true
(println (PGR:is-pangram? "abcdef")) ;; Print nil
(exit)
|
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
| #ivy | ivy |
op pascal N = transp (0 , iota N) o.! -1 , iota N
pascal 5
1 0 0 0 0 0
1 1 0 0 0 0
1 2 1 0 0 0
1 3 3 1 0 0
1 4 6 4 1 0
1 5 10 10 5 1
|
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Sidef | Sidef | var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +'
class RPN(arr=[]) {
method binop(op) {
var x = arr.pop
var y = arr.pop
arr << y.(op)(x)
}
method run(p) {
p.each_word { |w|
say "#{w} (#{arr})"
given (w) {
when (/\d/) {
arr << Num(w)
}
when (<+ - * />) {
self.binop(w)
}
when ('^') {
self.binop('**')
}
default {
die "#{w} is bogus"
}
}
}
say arr[0]
}
}
RPN.new.run(proggie) |
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
| #Dyalect | Dyalect | func isPalindrom(str) {
str == str.Reverse()
}
print(isPalindrom("ingirumimusnocteetconsumimurigni")) |
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
| #Nim | Nim | import rdstdin
proc isPangram(sentence: string, alphabet = {'a'..'z'}): bool =
var sentset: set[char] = {}
for c in sentence: sentset.incl c
alphabet <= sentset
echo isPangram(readLineFromStdin "Sentence: ") |
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
| #Objeck | Objeck |
bundle Default {
class Pangram {
function : native : IsPangram(test : String) ~ Bool {
for(a := 'A'; a <= 'Z'; a += 1;) {
if(test->Find(a) < 0 & test->Find(a->ToLower()) < 0) {
return false;
};
};
return true;
}
function : Main(args : String[]) ~ Nil {
IsPangram("the quick brown fox jumps over the lazy dog")->PrintLine(); # true
IsPangram("the quick brown fox jumped over the lazy dog")->PrintLine(); # false, no s
IsPangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ")->PrintLine(); # true
IsPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ")->PrintLine(); # false, no r
IsPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ")->PrintLine(); # false, no m
IsPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ")->PrintLine(); # true
IsPangram("")->PrintLine(); # false
}
}
}
|
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
| #J | J | !~/~ i.5
1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1 |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Sinclair_ZX81_BASIC | Sinclair ZX81 BASIC | 10 DIM S(5)
20 LET P=1
30 INPUT E$
40 LET I=0
50 LET I=I+1
60 IF E$(I)=" " THEN GOTO 110
70 IF I<LEN E$ THEN GOTO 50
80 LET W$=E$
90 GOSUB 150
100 STOP
110 LET W$=E$( TO I-1)
120 LET E$=E$(I+1 TO )
130 GOSUB 150
140 GOTO 40
150 IF W$="+" OR W$="-" OR W$="*" OR W$="/" OR W$="**" THEN GOTO 250
160 LET S(P)=VAL W$
170 LET P=P+1
180 PRINT W$;
190 PRINT ":";
200 FOR I=P-1 TO 1 STEP -1
210 PRINT " ";S(I);
220 NEXT I
230 PRINT
240 RETURN
250 IF W$="**" THEN LET S(P-2)=ABS S(P-2)
260 LET S(P-2)=VAL (STR$ S(P-2)+W$+STR$ S(P-1))
270 LET P=P-1
280 GOTO 180 |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Swift | Swift | let opa = [
"^": (prec: 4, rAssoc: true),
"*": (prec: 3, rAssoc: false),
"/": (prec: 3, rAssoc: false),
"+": (prec: 2, rAssoc: false),
"-": (prec: 2, rAssoc: false),
]
func rpn(tokens: [String]) -> [String] {
var rpn : [String] = []
var stack : [String] = [] // holds operators and left parenthesis
for tok in tokens {
switch tok {
case "(":
stack += [tok] // push "(" to stack
case ")":
while !stack.isEmpty {
let op = stack.removeLast() // pop item from stack
if op == "(" {
break // discard "("
} else {
rpn += [op] // add operator to result
}
}
default:
if let o1 = opa[tok] { // token is an operator?
for op in stack.reverse() {
if let o2 = opa[op] {
if !(o1.prec > o2.prec || (o1.prec == o2.prec && o1.rAssoc)) {
// top item is an operator that needs to come off
rpn += [stack.removeLast()] // pop and add it to the result
continue
}
}
break
}
stack += [tok] // push operator (the new one) to stack
} else { // token is not an operator
rpn += [tok] // add operand to result
}
}
}
return rpn + stack.reverse()
}
func parseInfix(e: String) -> String {
let tokens = e.characters.split{ $0 == " " }.map(String.init)
return rpn(tokens).joinWithSeparator(" ")
}
var input : String
input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
"infix: \(input)"
"postfix: \(parseInfix(input))" |
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
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | palindrome?:
local :seq chars
local :len-seq -- len seq
for i range 0 / len-seq 2:
if /= seq! i seq! - len-seq i:
return false
true
!. palindrome? "ingirumimusnocteetconsumimurigni"
!. palindrome? "nope" |
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
| #OCaml | OCaml | let pangram str =
let ar = Array.make 26 false in
String.iter (function
| 'a'..'z' as c -> ar.(Char.code c - Char.code 'a') <- true
| _ -> ()
) (String.lowercase str);
Array.fold_left ( && ) true ar |
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
| #Oz | Oz | declare
fun {IsPangram Xs}
{List.sub
{List.number &a &z 1}
{Sort {Map Xs Char.toLower} Value.'<'}}
end
in
{Show {IsPangram "The quick brown fox jumps over the lazy dog."}} |
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
| #Java | Java | import java.util.ArrayList;
...//class definition, etc.
public static void genPyrN(int rows){
if(rows < 0) return;
//save the last row here
ArrayList<Integer> last = new ArrayList<Integer>();
last.add(1);
System.out.println(last);
for(int i= 1;i <= rows;++i){
//work on the next row
ArrayList<Integer> thisRow= new ArrayList<Integer>();
thisRow.add(last.get(0)); //beginning
for(int j= 1;j < i;++j){//loop the number of elements in this row
//sum from the last row
thisRow.add(last.get(j - 1) + last.get(j));
}
thisRow.add(last.get(0)); //end
last= thisRow;//save this row
System.out.println(thisRow);
}
} |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Tcl | Tcl | # Helper
proc pop stk {
upvar 1 $stk s
set val [lindex $s end]
set s [lreplace $s end end]
return $val
}
proc evaluate rpn {
set stack {}
foreach token $rpn {
set act "apply"
switch $token {
"^" {
# Non-commutative operation
set a [pop stack]
lappend stack [expr {[pop stack] ** $a}]
}
"/" {
# Non-commutative, special float handling
set a [pop stack]
set b [expr {[pop stack] / double($a)}]
if {$b == round($b)} {set b [expr {round($b)}]}
lappend stack $b
}
"*" {
# Commutative operation
lappend stack [expr {[pop stack] * [pop stack]}]
}
"-" {
# Non-commutative operation
set a [pop stack]
lappend stack [expr {[pop stack] - $a}]
}
"+" {
# Commutative operation
lappend stack [expr {[pop stack] + [pop stack]}]
}
default {
set act "push"
lappend stack $token
}
}
puts "$token\t$act\t$stack"
}
return [lindex $stack end]
}
puts [evaluate {3 4 2 * 1 5 - 2 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
| #E | E | def isPalindrome(string :String) {
def upper := string.toUpperCase()
def last := upper.size() - 1
for i => c ? (upper[last - i] != c) in upper(0, upper.size() // 2) {
return false
}
return 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
| #PARI.2FGP | PARI/GP | pangram(s)={
s=vecsort(Vec(s),,8);
for(i=97,122,
if(!setsearch(s,Strchr(i)) && !setsearch(s,Strchr(i-32)),
return(0)
)
);
1
};
pangram("The quick brown fox jumps over the lazy dog.")
pangram("The quick brown fox jumps over the lazy doe.") |
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
| #Pascal | Pascal | use strict;
use warnings;
use feature 'say';
sub pangram1 {
my($str,@set) = @_;
use List::MoreUtils 'all';
all { $str =~ /$_/i } @set;
}
sub pangram2 {
my($str,@set) = @_;
'' eq (join '',@set) =~ s/[$str]//gir;
}
my @alpha = 'a' .. 'z';
for (
'Cozy Lummox Gives Smart Squid Who Asks For Job Pen.',
'Crabby Lummox Gives Smart Squid Who Asks For Job Pen.'
) {
say pangram1($_,@alpha) ? 'Yes' : 'No';
say pangram2($_,@alpha) ? 'Yes' : 'No';
} |
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
| #JavaScript | JavaScript | // Pascal's triangle object
function pascalTriangle (rows) {
// Number of rows the triangle contains
this.rows = rows;
// The 2D array holding the rows of the triangle
this.triangle = new Array();
for (var r = 0; r < rows; r++) {
this.triangle[r] = new Array();
for (var i = 0; i <= r; i++) {
if (i == 0 || i == r)
this.triangle[r][i] = 1;
else
this.triangle[r][i] = this.triangle[r-1][i-1]+this.triangle[r-1][i];
}
}
// Method to print the triangle
this.print = function(base) {
if (!base)
base = 10;
// Private method to calculate digits in number
var digits = function(n,b) {
var d = 0;
while (n >= 1) {
d++;
n /= b;
}
return d;
}
// Calculate max spaces needed
var spacing = digits(this.triangle[this.rows-1][Math.round(this.rows/2)],base);
// Private method to add spacing between numbers
var insertSpaces = function(s) {
var buf = "";
while (s > 0) {
s--;
buf += " ";
}
return buf;
}
// Print the triangle line by line
for (var r = 0; r < this.triangle.length; r++) {
var l = "";
for (var s = 0; s < Math.round(this.rows-1-r); s++) {
l += insertSpaces(spacing);
}
for (var i = 0; i < this.triangle[r].length; i++) {
if (i != 0)
l += insertSpaces(spacing-Math.ceil(digits(this.triangle[r][i],base)/2));
l += this.triangle[r][i].toString(base);
if (i < this.triangle[r].length-1)
l += insertSpaces(spacing-Math.floor(digits(this.triangle[r][i],base)/2));
}
print(l);
}
}
}
// Display 4 row triangle in base 10
var tri = new pascalTriangle(4);
tri.print();
// Display 8 row triangle in base 16
tri = new pascalTriangle(8);
tri.print(16); |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
exp() {
R=1
local i=1
while [ $i -le $2 ]; do
R=$(($R * $1))
i=$(($i + 1))
done
}
rpn() {
local O1 O2 stack
while [ $# -ge 1 ]; do
grep -iE '^-?[0-9]+$' <<< "$1" > /dev/null 2>&1
if [ "$?" -eq 0 ]; then
stack=`sed -e '$a'"$1" -e '/^$/d' <<< "$stack"`
else
grep -iE '^[-\+\*\/\%\^]$' <<< "$1" > /dev/null 2>&1
if [ "$?" -eq 0 ]; then
O2=`sed -n '$p' <<< "$stack"`
stack=`sed '$d' <<< "$stack"`
O1=`sed -n '$p' <<< "$stack"`
case "$1" in
'+')
stack=`sed -e '$a'"$(($O1 + $O2))" -e '/^$/d' -e '$d' \
<<< "$stack"`;;
'-')
stack=`sed -e '$a'"$(($O1 - $O2))" -e '/^$/d' -e '$d' \
<<< "$stack"`;;
'*')
stack=`sed -e '$a'"$(($O1 * $O2))" -e '/^$/d' -e '$d' \
<<< "$stack"`;;
'/')
stack=`sed -e '$a'"$(($O1 / $O2))" -e '/^$/d' -e '$d' \
<<< "$stack"`;;
'%')
stack=`sed -e '$a'"$(($O1 % $O2))" -e '/^$/d' -e '$d' \
<<< "$stack"`;;
'^')
exp $O1 $O2
stack=`sed -e '$a'"$(($R))" -e '/^$/d' -e '$d' <<< \
"$stack"`;;
esac
else
echo "Unknown RPN token \`\`$1''"
fi
fi
echo "$1" ":" $stack
shift
done
sed -n '1p' <<< "$stack"
if [ "`wc -l <<< "$stack"`" -gt 1 ]; then
echo "Malformed input expression" > /dev/stderr
return 1
else
return 0
fi
}
rpn 3 4 2 '*' 1 5 '-' 2 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
| #EchoLisp | EchoLisp |
;; returns #t or #f
(define (palindrome? string)
(equal? (string->list string) (reverse (string->list string))))
;; to strip spaces, use the following
;;(define (palindrome? string)
;;(let ((string (string-replace string "/\ /" "" "g")))
;;(equal? (string->list string) (reverse (string->list string)))))
|
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
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub pangram1 {
my($str,@set) = @_;
use List::MoreUtils 'all';
all { $str =~ /$_/i } @set;
}
sub pangram2 {
my($str,@set) = @_;
'' eq (join '',@set) =~ s/[$str]//gir;
}
my @alpha = 'a' .. 'z';
for (
'Cozy Lummox Gives Smart Squid Who Asks For Job Pen.',
'Crabby Lummox Gives Smart Squid Who Asks For Job Pen.'
) {
say pangram1($_,@alpha) ? 'Yes' : 'No';
say pangram2($_,@alpha) ? 'Yes' : 'No';
} |
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
| #jq | jq | # pascal(n) for n>=0; pascal(0) emits an empty stream.
def pascal(n):
def _pascal: # input: the previous row
. as $in
| .,
if length >= n then empty
else
reduce range(0;length-1) as $i
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal
end;
if n <= 0 then empty else [1] | _pascal end ; |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #VBA | VBA | Global stack$
Function RPN(expr$)
Debug.Print "Expression:"
Debug.Print expr$
Debug.Print "Input", "Operation", "Stack after"
stack$ = ""
token$ = "#"
i = 1
token$ = Split(expr$)(i - 1) 'split is base 0
token2$ = " " + token$ + " "
Do
Debug.Print "Token "; i; ": "; token$,
'operation
If InStr("+-*/^", token$) <> 0 Then
Debug.Print "operate",
op2$ = pop$()
op1$ = pop$()
If op1$ = "" Then
Debug.Print "Error: stack empty for "; i; "-th token: "; token$
End
End If
op1 = Val(op1$)
op2 = Val(op2$)
Select Case token$
Case "+"
res = CDbl(op1) + CDbl(op2)
Case "-"
res = CDbl(op1) - CDbl(op2)
Case "*"
res = CDbl(op1) * CDbl(op2)
Case "/"
res = CDbl(op1) / CDbl(op2)
Case "^"
res = CDbl(op1) ^ CDbl(op2)
End Select
Call push2(str$(res))
'default:number
Else
Debug.Print "push",
Call push2(token$)
End If
Debug.Print "Stack: "; reverse$(stack$)
i = i + 1
If i > Len(Join(Split(expr, " "), "")) Then
token$ = ""
Else
token$ = Split(expr$)(i - 1) 'base 0
token2$ = " " + token$ + " "
End If
Loop Until token$ = ""
Debug.Print
Debug.Print "Result:"; pop$()
'extra$ = pop$()
If stack <> "" Then
Debug.Print "Error: extra things on a stack: "; stack$
End If
End
End Function
'---------------------------------------
Function reverse$(s$)
reverse$ = ""
token$ = "#"
While token$ <> ""
i = i + 1
token$ = Split(s$, "|")(i - 1) 'split is base 0
reverse$ = token$ & " " & reverse$
Wend
End Function
'---------------------------------------
Sub push2(s$)
stack$ = s$ + "|" + stack$ 'stack
End Sub
Function pop$()
'it does return empty on empty stack
pop$ = Split(stack$, "|")(0)
stack$ = Mid$(stack$, InStr(stack$, "|") + 1)
End Function |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Vlang | Vlang | import math
const (
supported_operations = ['+', '-', '*', '/', '^']
max_depth = 256
)
struct Stack {
mut:
data []f32 = [f32(0)].repeat(max_depth)
depth int
}
fn (mut stack Stack) push(value f32) {
if stack.depth >= max_depth {
println('Stack Overflow!!')
return
}
stack.data[stack.depth] = value
stack.depth++
}
fn (mut stack Stack) pop() ?f32 {
if stack.depth > 0 {
stack.depth--
result := stack.data[stack.depth]
return result
}
return error('Stack Underflow!!')
}
fn (stack Stack) peek() ?f32 {
if stack.depth > 0 {
result := stack.data[0]
return result
}
return error('Out of Bounds...')
}
fn (mut stack Stack) rpn(input string) ?f32 {
println('Input: $input')
tokens := input.split(' ')
mut a := f32(0)
mut b := f32(0)
println('Token Stack')
for token in tokens {
if token.str.is_digit() {
stack.push(token.f32())
} else if token in supported_operations {
b = stack.pop() or { f32(0) }
a = stack.pop() or { f32(0) }
match token {
'+' {
stack.push(a + b)
}
'-' {
stack.push(a - b)
}
'*' {
stack.push(a * b)
}
'/' {
stack.push(a / b)
}
'^' {
stack.push(f32(math.pow(a, b)))
}
else {
println('Oofffff')
}
}
}
print('${token:5s} ')
for i := 0; i < stack.depth; i++ {
if i == stack.depth - 1 {
println('${stack.data[i]:0.6f} |>')
} else {
print('${stack.data[i]:0.6f}, ')
}
}
}
return stack.peek()
}
fn main() {
mut calc := Stack{}
result := calc.rpn('3 4 2 * 1 5 - 2 3 ^ ^ / +') or { return }
println('\nResult: $result')
}
|
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
| #Eiffel | Eiffel |
is_palindrome (a_string: STRING): BOOLEAN
-- Is `a_string' a palindrome?
require
string_attached: a_string /= Void
local
l_index, l_count: INTEGER
do
from
Result := True
l_index := 1
l_count := a_string.count
until
l_index >= l_count - l_index + 1 or not Result
loop
Result := (Result and a_string [l_index] = a_string [l_count - l_index + 1])
l_index := l_index + 1
end
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
| #Phix | Phix | function pangram(string s)
sequence az = repeat(false,26)
integer count = 0
for i=1 to length(s) do
integer ch = lower(s[i])
if ch>='a'
and ch<='z'
and not az[ch-96] then
count += 1
if count=26 then return {true,0} end if
az[ch-96] = true
end if
end for
return {false,find(false,az)+96}
end function
sequence checks = {"The quick brown fox jumped over the lazy dog",
"The quick brown fox jumps over the lazy dog",
".!$\"AbCdEfghijklmnoprqstuvwxyz",
"THE FIVE BOXING WIZARDS DUMP QUICKLY.",
"THE FIVE BOXING WIZARDS JUMP QUICKLY.",
"HEAVY BOXES PERFORM WALTZES AND JIGS.",
"PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.",
"Big fjiords vex quick waltz nymph",
"The quick onyx goblin jumps over the lazy dwarf.",
"no"}
for i=1 to length(checks) do
string ci = checks[i]
integer {r,ch} = pangram(ci)
printf(1,"%-50s - %s\n",{ci,iff(r?"yes":"no "&ch)})
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
| #Julia | Julia | function pascal(n)
if n<=0
print("n has to have a positive value")
end
x=0
while x<=n
for a=0:x
print(binomial(x,a)," ")
end
println("")
x+=1
end
end
|
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Wren | Wren | import "/seq" for Stack
var rpnCalculate = Fn.new { |expr|
if (expr == "") Fiber.abort("Expression cannot be empty.")
System.print("For expression = %(expr)\n")
System.print("Token Action Stack")
var tokens = expr.split(" ").where { |t| t != "" }
var stack = Stack.new()
for (token in tokens) {
var d = Num.fromString(token)
if (d) {
stack.push(d)
System.print(" %(d) Push num onto top of stack %(stack)")
} else if ((token.count > 1) || !"+-*/^".contains(token)) {
Fiber.abort("%(token) is not a valid token.")
} else if (stack.count < 2) {
Fiber.abort("Stack contains too few operands.")
} else {
var d1 = stack.pop()
var d2 = stack.pop()
stack.push(token == "+" ? d2 + d1 :
token == "-" ? d2 - d1 :
token == "*" ? d2 * d1 :
token == "/" ? d2 / d1 : d2.pow(d1))
System.print(" %(token) Apply op to top of stack %(stack)")
}
}
System.print("\nThe final value is %(stack.pop())")
}
var expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
rpnCalculate.call(expr) |
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
| #Ela | Ela | open list string
isPalindrome xs = xs == reverse xs
isPalindrome <| toList "ingirumimusnocteetconsumimurigni"
|
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
| #PHP | PHP | function isPangram($text) {
foreach (str_split($text) as $c) {
if ($c >= 'a' && $c <= 'z')
$bitset |= (1 << (ord($c) - ord('a')));
else if ($c >= 'A' && $c <= 'Z')
$bitset |= (1 << (ord($c) - ord('A')));
}
return $bitset == 0x3ffffff;
}
$test = array(
"the quick brown fox jumps over the lazy dog",
"the quick brown fox jumped over the lazy dog",
"ABCDEFGHIJKLMNOPQSTUVWXYZ",
"ABCDEFGHIJKL.NOPQRSTUVWXYZ",
"ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ"
);
foreach ($test as $str)
echo "$str : ", isPangram($str) ? 'T' : 'F', '</br>'; |
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
| #K | K |
pascal:{(x-1){+':x,0}\1}
pascal 6
(1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1) |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #Xojo | Xojo |
Function RPN(expr As String) As String
Dim tokenArray() As String
Dim stack() As String
Dim Wert1 As Double
Dim Wert2 As Double
'Initialize array (removed later)
ReDim tokenArray(1)
ReDim stack(1)
tokenArray = Split(expr, " ")
Dim i As integer
i = 0
While i <= tokenArray.Ubound
If tokenArray(i) = "+" Then
Wert2 = Val(stack.pop)
Wert1 = Val(stack.pop)
stack.Append(Str(Wert1+Wert2))
ElseIf tokenArray(i) = "-" Then
Wert2 = Val(stack.pop)
Wert1 = Val(stack.pop)
stack.Append(Str(Wert1-Wert2))
ElseIf tokenArray(i) = "*" Then
Wert2 = Val(stack.pop)
Wert1 = Val(stack.pop)
stack.Append(Str(Wert1*Wert2))
ElseIf tokenArray(i) = "/" Then
Wert2 = Val(stack.pop)
Wert1 = Val(stack.pop)
stack.Append(Str(Wert1/Wert2))
ElseIf tokenArray(i) = "^" Then
Wert2 = Val(stack.pop)
Wert1 = Val(stack.pop)
stack.Append(Str(pow(Wert1,Wert2)))
Else
stack.Append(tokenArray(i))
End If
i = i +1
Wend
Return stack(2)
End Function |
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm | Parsing/RPN calculator algorithm | Task
Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed as a table.
Assume an input of a correct, space separated, string of tokens of an RPN expression
Test with the RPN expression generated from the Parsing/Shunting-yard algorithm task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
Print or display the output here
Notes
^ means exponentiation in the expression above.
/ means division.
See also
Parsing/Shunting-yard algorithm for a method of generating an RPN from an infix expression.
Several solutions to 24 game/Solve make use of RPN evaluators (although tracing how they work is not a part of that task).
Parsing/RPN to infix conversion.
Arithmetic evaluation.
| #zkl | zkl | var ops=D("^",True, "*",'*, "/",'/, "+",'+, "-",'-);
fcn parseRPN(e){
println("\npostfix: ", e);
stack:=L();
foreach tok in (e.split()){
op:=ops.find(tok);
if(op){
y := stack.pop(); x := stack.pop();
if(True==op) x=x.pow(y);
else x=op(x,y);
stack.append(x);
}
else stack.append(tok.toFloat());
println(tok," --> ",stack);
}
println("result: ", stack[0])
} |
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
| #Elixir | Elixir |
defmodule PalindromeDetection do
def is_palindrome(str), do: str == String.reverse(str)
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
| #Picat | Picat | go =>
S1 = "The quick brown fox jumps over the lazy dog",
S2 = "The slow brown fox jumps over the lazy dog",
println([S1, is_pangram(S1)]),
println([S2, is_pangram(S2)]),
nl,
println("With missing chars:"),
println([S1, is_pangram2(S1)]),
println([S2, is_pangram2(S2)]),
nl.
% Check if S is a pangram and get the missing chars
is_pangram(S) = P =>
Lower = S.to_lowercase,
Alpha = [chr(I+96) : I in 1..26],
foreach(A in Alpha) membchk(A,Lower) end -> P = true ; P = false.
% Check if S is a pangram and get the missing chars (if any)
is_pangram2(S) = [pangram=cond(Missing==[],true,false),missing=Missing] =>
Lower = S.to_lowercase,
Missing = [A : A in [chr(I+96) : I in 1..26], not membchk(A,Lower)]. |
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
| #PicoLisp | PicoLisp | (de isPangram (Str)
(not
(diff
'`(chop "abcdefghijklmnopqrstuvwxyz")
(chop (lowc Str)) ) ) ) |
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
| #Kotlin | Kotlin | fun pas(rows: Int) {
for (i in 0..rows - 1) {
for (j in 0..i)
print(ncr(i, j).toString() + " ")
println()
}
}
fun ncr(n: Int, r: Int) = fact(n) / (fact(r) * fact(n - r))
fun fact(n: Int) : Long {
var ans = 1.toLong()
for (i in 2..n)
ans *= i
return ans
}
fun main(args: Array<String>) = pas(args[0].toInt()) |
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
| #Elm | Elm | import String exposing (reverse, length)
import Html exposing (Html, Attribute, text, div, input)
import Html.Attributes exposing (placeholder, value, style)
import Html.Events exposing (on, targetValue)
import Html.App exposing (beginnerProgram)
-- The following function (copied from Haskell) satisfies the
-- rosettacode task description.
is_palindrome x = x == reverse x
-- The remainder of the code demonstrates the use of the function
-- in a complete Elm program.
main = beginnerProgram { model = "" , view = view , update = update }
update newStr oldStr = newStr
view : String -> Html String
view candidate =
div []
([ input
[ placeholder "Enter a string to check."
, value candidate
, on "input" targetValue
, myStyle
]
[]
] ++
[ let testResult =
is_palindrome candidate
statement =
if testResult then "PALINDROME!" else "not a palindrome"
in div [ myStyle] [text statement]
])
myStyle : Attribute msg
myStyle =
style
[ ("width", "100%")
, ("height", "20px")
, ("padding", "5px 0 0 5px")
, ("font-size", "1em")
, ("text-align", "left")
] |
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
| #PL.2FI | PL/I |
test_pangram: procedure options (main);
is_pangram: procedure() returns (bit(1) aligned);
declare text character (200) varying;
declare c character (1);
get edit (text) (L);
put skip list (text);
text = lowercase(text);
do c = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z';
if index(text, c) = 0 then return ('0'b);
end;
return ('1'b);
end is_pangram;
put skip list ('Please type a sentence');
if is_pangram() then
put skip list ('The sentence is a pangram.');
else
put skip list ('The sentence is not a pangram.');
end test_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
| #PowerShell | PowerShell |
function Test-Pangram ( [string]$Text, [string]$Alphabet = 'abcdefghijklmnopqrstuvwxyz' )
{
$Text = $Text.ToLower()
$Alphabet = $Alphabet.ToLower()
$IsPangram = @( $Alphabet.ToCharArray() | Where-Object { $Text.Contains( $_ ) } ).Count -eq $Alphabet.Length
return $IsPangram
}
Test-Pangram 'The quick brown fox jumped over the lazy dog.'
Test-Pangram 'The quick brown fox jumps over the lazy dog.'
Test-Pangram 'Съешь же ещё этих мягких французских булок, да выпей чаю' 'абвгдежзийклмнопрстуфхцчшщъыьэюяё'
|
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
| #Lambdatalk | Lambdatalk |
1) Based on this expression of pascalian binomial:
Cnp = [n*(n-1)...(n-p+1)]/[p*(p-1)...2*1]
2) we define the following function:
{def C
{lambda {:n :p}
{/ {* {S.serie :n {- :n :p -1} -1}}
{* {S.serie :p 1 -1}}}}}
{C 16 8}
-> 12870
3) Writing
1{S.map {lambda {:n} {br}1
{S.map {C :n} {S.serie 1 {- :n 1}}} 1}
{S.serie 2 16}}
displays:
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
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 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
| #Emacs_Lisp | Emacs Lisp | (defun palindrome (s)
(string= s (reverse s))) |
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
| #Prolog | Prolog | pangram(L) :-
numlist(0'a, 0'z, Alphabet),
forall(member(C, Alphabet), member(C, L)).
pangram_example :-
L1 = "the quick brown fox jumps over the lazy dog",
( pangram(L1) -> R1= ok; R1 = ko),
format('~s --> ~w ~n', [L1,R1]),
L2 = "the quick brown fox jumped over the lazy dog",
( pangram(L2) -> R2 = ok; R2 = ko),
format('~s --> ~w ~n', [L2, R2]).
|
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
| #PureBasic | PureBasic | Procedure IsPangram_fast(String$)
String$ = LCase(string$)
char_a=Asc("a")
; sets bits in a variable if a letter is found, reads string only once
For a = 1 To Len(string$)
char$ = Mid(String$, a, 1)
pos = Asc(char$) - char_a
check.l | 1 << pos
Next
If check & $3FFFFFF = $3FFFFFF
ProcedureReturn 1
EndIf
ProcedureReturn 0
EndProcedure
Procedure IsPangram_simple(String$)
String$ = LCase(string$)
found = 1
For a = Asc("a") To Asc("z")
; searches for every letter in whole string
If FindString(String$, Chr(a), 0) = 0
found = 0
EndIf
Next
ProcedureReturn found
EndProcedure
Debug IsPangram_fast("The quick brown fox jumps over lazy dogs.")
Debug IsPangram_simple("The quick brown fox jumps over lazy dogs.")
Debug IsPangram_fast("No pangram")
Debug IsPangram_simple("No pangram") |
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
| #Liberty_BASIC | Liberty BASIC | input "How much rows would you like? "; n
dim a$(n)
for i= 0 to n
c = 1
o$ =""
for k =0 to i
o$ =o$ ; c; " "
c =c *(i-k)/(k+1)
next k
a$(i)=o$
next i
maxLen = len(a$(n))
for i= 0 to n
print space$((maxLen-len(a$(i)))/2);a$(i)
next i
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
| #Erlang | Erlang |
-module( palindrome ).
-export( [is_palindrome/1, task/0] ).
is_palindrome( String ) -> String =:= lists:reverse(String).
task() ->
display( "abcba" ),
display( "abcdef" ),
Latin = "In girum imus nocte et consumimur igni",
No_spaces_same_case = lists:append( string:tokens(string:to_lower(Latin), " ") ),
display( Latin, No_spaces_same_case ).
display( String ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String, is_palindrome(String)] ).
display( String1, String2 ) -> io:fwrite( "Is ~p a palindrom? ~p~n", [String1, is_palindrome(String2)] ).
|
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
| #Python | Python | import string, sys
if sys.version_info[0] < 3:
input = raw_input
def ispangram(sentence, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return alphaset <= set(sentence.lower())
print ( ispangram(input('Sentence: ')) ) |
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
| #Quackery | Quackery |
[ dup char A char [ within
swap char a char { within
or ] is letter ( c --> b )
[ 0 26 of swap witheach
[ dup letter iff
[ 1 unrot lower
char a - poke ]
else drop ]
0 swap find 26 = ] is pangram ( $ --> b )
$ "This is a sentence." pangram echo cr ( 0 )
$ "The five boxing wizards jumped quickly." pangram echo cr ( 1 )
|
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)
| #FreeBASIC | FreeBASIC |
' ***********************************************
'subject: p-adic square roots, Hensel lifting.
'tested : FreeBasic 1.07.0
'The root is squared, approximated by a
'rational, and compared with radicand a/b.
const emx = 48
'exponent maximum
const amx = 700000
'tentative argument maximum
'------------------------------------------------
const Mxd = cdbl(2)^53 - 1
'max. float64 integer
const Pmax = 32749
'max. prime < 2^15
type ratio
as longint a, b
end type
type padic
declare function sqrt (byref q as ratio, byval sw as integer) as integer
'p-adic square root of q = a/b, set sw to print
declare sub printf (byval sw as integer)
'print expansion, set sw to print rational
declare function crat (byval sw as integer) as ratio
'rational reconstruction
declare sub cmpt (byref a as padic)
'let self:= complement_a
declare sub sqr (byref a as padic)
'let self:= a ^ 2
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)
'------------------------------------------------
'p-adic square root of g = a/b
function padic.sqrt (byref g as ratio, byval sw as integer) as integer
dim as longint a = g.a, b = g.b
dim as longint q, x, pk, pm
dim as long f1, r, s, t
dim i as integer, f as double
sqrt = 0
if b = 0 then return 1
if b < 0 then b = -b: a = -a
if p < 2 or k < 1 then return 1
'max. short prime
p = min(p, Pmax)
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
'valuation
do until b mod p
b \= p: v -= 1
loop
do until a mod p
a \= p: v += 1
loop
if (v and 1) = 1 then
'odd valuation
print "non-residue mod"; p
return -1
end if
'max. array length
k = min(k + v, emx - 1)
k -= v: v shr= 1
if abs(a) > amx or b > amx then return -1
if p = 2 then
'1 / b = b (mod 8)
'a / b = 1 (mod 8)
t = a * b
if (t and 7) - 1 then
print "non-residue mod 8"
return -1
end if
else
'find root for small p
for r = 1 to p1
q = b * r * r - a
if q mod p = 0 then exit for
next r
if r = p then
print "non-residue mod"; p
return -1
end if
'f'(r) = 2br
t = b * r shl 1
s = 0
t mod= p
'modular inverse for small p
for f1 = 1 to p1
s += t
if s > p1 then s -= p
if s = 1 then exit for
next f1
if f1 = p then
print "impossible inverse mod"
return -1
end if
end if
'evaluate f(x)
#macro evalf(x)
f = b * x * cdbl(x / pk)
f -= cdbl(a / pk)
'overflow
if f > Mxd then exit for
q = clngint(f)
#endmacro
if p = 2 then
'initialize
x = 1
d(v) = 1
d(v + 1) = 0
pk = 4
for i = v + 2 to k - 1 + v
pk shl= 1
'2-power overflow
if pk < 1 then exit for
evalf(x)
'next digit
d(i) = iif(q and 1, 1, 0)
'lift x
x += d(i) * (pk shr 1)
next i
else
'-1 / f'(x) mod p
f1 = p - f1
x = r
d(v) = x
pk = 1
for i = v + 1 to k - 1 + v
pm = pk: pk *= p
if pk \ pm - p then exit for
evalf(x)
d(i) = q * f1 mod p
if d(i) < 0 then d(i) += p
x += d(i) * pk
next i
end if
k = i - v
if sw then print "lift:";x;" mod";p;"^";str(k)
end function
'------------------------------------------------
'rational reconstruction
function padic.crat (byval sw as integer) as ratio
dim as integer i, j, t = min(v, 0)
dim as longint s, pk, pm
dim as long q, x, y
dim as double f, h
dim r as ratio
'weighted digit sum
s = 0: pk = 1
for i = t to k - 1 + v
pm = pk: pk *= p
if pk \ pm - p then
'overflow
pk = pm: exit for
end if
s += d(i) * pm '(mod pk)
next i
'lattice basis reduction
dim as longint m(1) = {pk, s}
dim as longint n(1) = {0, 1}
'norm(v)^2
h = cdbl(s) * s + 1
i = 0: j = 1
'Lagrange's algorithm
do
f = m(i) * (m(j) / h)
f += n(i) * (n(j) / h)
'Euclidean step
q = int(f +.5)
m(i) -= q * m(j)
n(i) -= q * n(j)
f = h
h = cdbl(m(i)) * m(i)
h += cdbl(n(i)) * n(i)
'compare norms
if h < f then
'interchange vectors
swap i, j
else
exit do
end if
loop
x = m(j): y = n(j)
if y < 0 then y = -y: x = -x
'check determinant
t = abs(m(i) * y - x * n(i)) = pk
if t = 0 then
print "crat: fail"
x = 0: y = 1
else
'negative powers
for i = v to -1
y *= p: next
if sw then
print x;
if y > 1 then print "/";str(y);
print
end if
end if
r.a = x: r.b = y
return r
end function
'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(sw)
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)
'carry
if c > p1 then
.d(i) = c - p: c = 1
else
.d(i) = c: c = 0
end if
next i
end with
this = r
end sub
'let self:= a ^ 2
sub padic.sqr (byref a as padic)
dim as long ptr rp, ap = @a.d(a.v)
dim as longint q, c = 0
dim as integer i, j
dim r as padic
with r
.v = a.v shl 1
rp = @.d(.v)
for i = 0 to k
for j = 0 to i
c += ap[j] * ap[i - j]
next j
'Euclidean step
q = c \ p
rp[i] = c - q * p
c = q
next i
end with
this = r
end sub
'main
'------------------------------------------------
dim as integer sw
dim as padic a, c
dim as ratio q, r
width 64, 30
cls
' -7 + O(2^7)
data -7,1, 2,7
data 9,1, 2,8
data 17,1, 2,9
data 497,10496, 2,18
data 10496,497, 2,19
data -577215,664901, 3,23
data 15403,26685, 3,18
data -1,1, 5,8
data 86,25, 5,8
data 2150,1, 5,8
data 2,1, 7,8
data 11696,621467, 7,11
data -27764,11521, 7,11
data -27584,12953, 7,11
data -166420,135131, 11,11
data 14142,135623, 5,15
data -255,256, 257,3
data 0,0, 0,0
print
do
read q.a,q.b, p,k
sw = a.sqrt(q, 1)
if sw = 1 then exit do
if sw then ? : continue do
print "sqrt +/-"
print "...";
a.printf(0)
a.cmpt(a)
print "...";
a.printf(0)
c.sqr(a)
print "sqrt^2"
print " ";
c.printf(0)
r = c.crat(1)
'{r = q}
if q.a * r.b - r.a * q.b then
print "fail: sqrt^2"
end if
print : ?
loop
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
| #Locomotive_Basic | Locomotive Basic | 10 CLS
20 INPUT "Number of rows? ", rows:GOSUB 40
30 END
40 FOR i=0 TO rows-1
50 c=1
60 FOR k=0 TO i
70 PRINT USING "####";c;
80 c=c*(i-k)/(k+1)
90 NEXT
100 PRINT
110 NEXT
120 RETURN |
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
| #Euphoria | Euphoria | function isPalindrome(sequence s)
for i = 1 to length(s)/2 do
if s[i] != s[$-i+1] then
return 0
end if
end for
return 1
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
| #R | R | checkPangram <- function(sentence){
my.letters <- tolower(unlist(strsplit(sentence, "")))
is.pangram <- all(letters %in% my.letters)
if (is.pangram){
cat("\"", sentence, "\" is a pangram! \n", sep="")
} else {
cat("\"", sentence, "\" is not a pangram! \n", sep="")
}
}
|
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
| #Racket | Racket |
#lang racket
(define (pangram? str)
(define chars (regexp-replace* #rx"[^a-z]+" (string-downcase str) ""))
(= 26 (length (remove-duplicates (string->list chars)))))
(pangram? "The quick Brown Fox jumps over the Lazy Dog")
|
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)
| #Haskell | Haskell | {-# LANGUAGE KindSignatures, DataKinds #-}
import Data.Ratio
import Data.List (find)
import GHC.TypeLits
import Padic
pSqrt :: KnownNat p => Rational -> Padic p
pSqrt r = res
where
res = maybe Null mkUnit series
(a, b) = (numerator r, denominator r)
series = case modulo res of
2 | eqMod 4 a 3 -> Nothing
| not (eqMod 8 a 1) -> Nothing
| otherwise -> Just $ 1 : 0 : go 8 1
where
go pk x =
let q = ((b*x*x - a) `div` pk) `mod` 2
in q : go (2*pk) (x + q * (pk `div` 2))
p -> do
y <- find (\x -> eqMod p (b*x*x) a) [1..p-1]
df <- recipMod p (2*b*y)
let go pk x =
let f = (b*x*x - a) `div` pk
d = (f * (p - df)) `mod` p
in x `div` (pk `div` p) : go (p*pk) (x + d*pk)
Just $ go p y
eqMod :: Integral a => a -> a -> a -> Bool
eqMod p a b = a `mod` p == b `mod` p |
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
| #Logo | Logo | to pascal :n
if :n = 1 [output [1]]
localmake "a pascal :n-1
output (sentence first :a (map "sum butfirst :a butlast :a) last :a)
end
for [i 1 10] [print pascal :i] |
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
| #Excel | Excel | ISPALINDROME
=LAMBDA(s,
LET(
lcs, FILTERP(
LAMBDA(c, " " <> c)
)(
CHARS(LOWER(s))
),
CONCAT(lcs) = CONCAT(REVERSE(lcs))
)
) |
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
| #Raku | Raku | constant Eng = set 'a' .. 'z';
constant Cyr = (set 'а' .. 'ё') (-) (set 'ъ', 'ѐ')
constant Hex = set 'a' .. 'f';
sub pangram($str, Set $alpha = Eng) {
$alpha ⊆ $str.lc.comb;
}
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/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
| #Retro | Retro | 'abcdefghijklmnopqrstuvwxyz 'FULL s:const
'__________________________ 'TEST s:const
:s:pangram? (s-f)
'__________________________ &TEST #26 copy
s:to-lower [ c:letter? ] s:filter
[ dup $a - &TEST + store ] s:for-each
&TEST &FULL s:eq? ;
|
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)
| #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 - 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=p, pad=k)
return prod([i == k + v && v != 0 ? "$x . " : "$x " for (i, x) in enumerate(reverse(d))])
end
const DATA = [
[-7, 1, 2, 7],
[9, 1, 2, 8],
[17, 1, 2, 9],
[-1, 1, 5, 8],
[86, 25, 5, 8],
[2150, 1, 5, 8],
[2, 1, 7, 8],
[3029, 4821, 7, 9],
[379, 449, 7, 8],
[717, 8, 11, 7],
[1414, 213, 41, 5],
[-255, 256, 257, 3]
]
for (num1, den1, P, K) in DATA
Qp = PadicField(P, K)
a = Qp(QQ(num1 // den1))
c = sqrt(a)
r = toRational(c * c)
println(a, "\nsqrt +/-\n", dstring(c), "\n", dstring(-c), "\nCheck sqrt^2:\n", dstring(c * c), "\n", r, "\n")
end
|
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)
| #Nim | Nim | import strformat
const
Emx = 64 # Exponent maximum.
Amx = 6000 # 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 sqrt(pa: var Padic; q: Ratio; sw: bool) =
## Return the p-adic square root of q = a/b. Set sw to print.
var (a, b) = q
var i, x: int
if b == 0:
raise newException(PadicError, &"Wrong rational: {a}/{b}" )
if b < 0:
b = -b
a = -a
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.
if sw: echo &"{a}/{b} + 0({pa.p}^{pa.k})"
# Initialize.
pa.v = 0
pa.d.reset()
if a == 0: return
# Valuation.
while b mod pa.p == 0:
b = b div pa.p
dec pa.v
while a mod pa.p == 0:
a = a div pa.p
inc pa.v
if (pa.v and 1) != 0:
# Odd valuation.
raise newException(PadicError, &"Non-residue mod {pa.p}.")
# Maximum array length.
pa.k = min(pa.k + pa.v, Emx - 1) - pa.v
pa.v = pa.v shr 1
if abs(a) > Amx or b > Amx:
raise newException(PadicError, &"Rational exceeding limits: {a}/{b}.")
if pa.p == 2:
# 1 / b = b (mod 8); a / b = 1 (mod 8).
if (a * b and 7) - 1 != 0:
raise newException(PadicError, "Non-residue mod 8.")
# Initialize.
x = 1
pa.d[pa.v] = 1
pa.d[pa.v + 1] = 0
var pk = 4
i = pa.v + 2
while i < pa.k + pa.v:
pk *= 2
let f = b * x * x - a
let q = f div pk
if f != q * pk: break # Overflow.
# Next digit.
pa.d[i] = if (q and 1) != 0: 1 else: 0
# Lift "x".
x += pa.d[i] * (pk shr 1)
inc i
else:
# Find root for small "p".
var r = 1
while r < pa.p:
if (b * r * r - a) mod pa.p == 0: break
inc r
if r == pa.p:
raise newException(PadicError, &"Non-residue mod {pa.p}.")
let t = (b * r shl 1) mod pa.p
var s = 0
# Modular inverse for small "p".
var f1 = 1
while f1 < pa.p:
inc s, t
if s >= pa.p: dec s, pa.p
if s == 1: break
inc f1
if f1 == pa.p:
raise newException(PadicError, "Impossible to compute inverse modulo")
f1 = pa.p - f1
x = r
pa.d[pa.v] = x
var pk = 1
i = pa.v + 1
while i < pa.k + pa.v:
pk *= pa.p
let f = b * x * x - a
let q = f div pk
if f != q * pk: break # Overflow.
pa.d[i] = q * f1 mod pa.p
if pa.d[i] < 0: pa.d[i] += pa.p
x += pa.d[i] * pk
inc i
pa.k = i - pa.v
if sw: echo &"lift: {x} mod {pa.p}^{pa.k}"
proc crat(pa: Padic; sw: bool): Ratio =
## Rational reconstruction.
# Weighted digit sum.
var
s = 0
pk = 1
for i in min(pa.v, 0)..<(pa.k + pa.v):
let pm = pk
pk *= pa.p
if pk div pm - pa.p != 0:
# Overflow.
pk = pm
break
s += pa.d[i] * pm
# Lattice basis reduction.
var
m = [pk, s]
n = [0, 1]
i = 0
j = 1
s = s * s + 1
# Lagrange's algorithm.
while true:
# Euclidean step.
var q = ((m[i] * m[j] + n[i] * n[j]) / s).toInt
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: swap i, j # Interchange vectors.
else: break
var x = m[j]
var y = n[j]
if y < 0:
y = -y
x = -x
# Check determinant.
if abs(m[i] * y - x * n[i]) != pk:
raise newException(PadicError, "Rational reconstruction failed.")
# Negative powers.
for i in pa.v..(-1): y *= pa.p
if sw: echo x, if y > 1: '/' & $y else: ""
result = (x, y)
func cmpt(pa: Padic): Padic =
## Return the complement.
result = Padic(p: pa.p, k: pa.k, v: pa.v)
var c = 1
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 sqr(pa: Padic): Padic =
## Return the square of a P-adic number.
result = Padic(p: pa.p, k: pa.k, v: pa.v * 2)
var c = 0
for i in 0..pa.k:
for j in 0..i:
c += pa.d[pa.v + j] * pa.d[pa.v + i - j]
# Euclidean step.
let q = c div pa.p
result.d[result.v + i] = c - q * pa.p
c = q
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 " "
when isMainModule:
const 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]]
for d in Data:
try:
let q: Ratio = (d[0], d[1])
var a = Padic(p: d[2], k: d[3])
a.sqrt(q, true)
echo "sqrt +/-"
echo "...", a
a = a.cmpt()
echo "...", a
let c = sqr(a)
echo "sqrt^2"
echo " ", c
let r = c.crat(true)
if q.a * r.b - r.a * q.b != 0:
echo "fail: sqrt^2"
echo ""
except PadicError:
echo getCurrentExceptionMsg() |
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.