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/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Swift | Swift | #include <stdlib.h>
#include <time.h>
void initRandom(const unsigned int seed){
if(seed==0){
srand((unsigned) time(NULL));
}
else{
srand(seed);
}
}
int getRand(const int upperBound){
return rand() % upperBound;
} |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Rpn_Calc {
Rem Form 80,60
function rpn_calc(a$) {
def m=0
dim token$()
token$()=piece$(a$," ")
l=len(token$())
dim type(l)=0, reg(l)
where=-1
for i=0 to l-1
c=val(token$(i),"",m)
if m>-1 then
where++
reg(where)=c
else
reg(where-1)=eval(str$(reg(where-1))+token$(i)+str$(reg(where)))
where--
end if
inf=each(reg(),1, where+1)
while inf
export$<=token$(i)+" ["+str$(inf^,"")+"] "+ str$(array(inf))+{
}
token$(i)=" "
end while
next i
=reg(0)
}
Global export$
document export$
example1=rpn_calc("3 4 2 * 1 5 - 2 3 ^ ^ / +")
example2=rpn_calc("1 2 + 3 4 + ^ 5 6 + ^")
Print example1, example2
Rem Print #-2, Export$
ClipBoard Export$
}
Rpn_Calc
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | calc[rpn_] :=
Module[{tokens = StringSplit[rpn], s = "(" <> ToString@InputForm@# <> ")" &, op, steps},
op[o_, x_, y_] := ToExpression[s@x <> o <> s@y];
steps = FoldList[Switch[#2, _?DigitQ, Append[#, FromDigits[#2]],
_, Append[#[[;; -3]], op[#2, #[[-2]], #[[-1]]]]
] &, {}, tokens][[2 ;;]];
Grid[Transpose[{# <> ":" & /@ tokens,
StringRiffle[ToString[#, InputForm] & /@ #] & /@ steps}]]];
Print[calc["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
| #BASIC | BASIC | ' OPTION _EXPLICIT ' For QB64. In VB-DOS remove the underscore.
DIM txt$
' Palindrome
CLS
PRINT "This is a palindrome detector program."
PRINT
INPUT "Please, type a word or phrase: ", txt$
IF IsPalindrome(txt$) THEN
PRINT "Is a palindrome."
ELSE
PRINT "Is Not a palindrome."
END IF
END
FUNCTION IsPalindrome (AText$)
' Var
DIM CleanTXT$, RvrsTXT$
CleanTXT$ = CleanText$(AText$)
RvrsTXT$ = RvrsText$(CleanTXT$)
IsPalindrome = (CleanTXT$ = RvrsTXT$)
END FUNCTION
FUNCTION CleanText$ (WhichText$)
' Var
DIM i%, j%, c$, NewText$, CpyTxt$, AddIt%, SubsTXT$
CONST False = 0, True = NOT False
SubsTXT$ = "AIOUE"
CpyTxt$ = UCASE$(WhichText$)
j% = LEN(CpyTxt$)
FOR i% = 1 TO j%
c$ = MID$(CpyTxt$, i%, 1)
' See if it is a letter. Includes Spanish letters.
SELECT CASE c$
CASE "A" TO "Z"
AddIt% = True
CASE " ", "¡", "¢", "£"
c$ = MID$(SubsTXT$, ASC(c$) - 159, 1)
AddIt% = True
CASE "‚"
c$ = "E"
AddIt% = True
CASE "¤"
c$ = "¥"
AddIt% = True
CASE ELSE
AddIt% = False
END SELECT
IF AddIt% THEN
NewText$ = NewText$ + c$
END IF
NEXT i%
CleanText$ = NewText$
END FUNCTION
FUNCTION RvrsText$ (WhichText$)
' Var
DIM i%, c$, NewText$, j%
j% = LEN(WhichText$)
FOR i% = 1 TO j%
NewText$ = MID$(WhichText$, i%, 1) + NewText$
NEXT i%
RvrsText$ = NewText$
END FUNCTION |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Ring | Ring |
load "stdlib.ring"
see "First 20 palindromic gapful numbers > 100 ending with each digit from 1 to 9:" + nl
limit = 9606069
for n = 1 to 9
sum = 0
for x = 101 to limit
flag = 0
strx = string(x)
xbegin = left(strx,1)
xend = right(strx,1)
xnew = number(xbegin+xend)
for y = 2 to ceil(x/2)+1
if ispalindrome(strx)
if y != xnew and x % y != 0
if x % xnew = 0 and number(xend) = n
flag = 1
else
flag = 0
exit
ok
ok
ok
next
if flag = 1
sum = sum + 1
if sum < 21
see "x = " + x + nl
else
exit
ok
ok
next
see nl
next
see "done..." + nl
|
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Standard_ML | Standard ML | structure Operator = struct
datatype associativity = LEFT | RIGHT
type operator = { symbol : char, assoc : associativity, precedence : int }
val operators : operator list = [
{ symbol = #"^", precedence = 4, assoc = RIGHT },
{ symbol = #"*", precedence = 3, assoc = LEFT },
{ symbol = #"/", precedence = 3, assoc = LEFT },
{ symbol = #"+", precedence = 2, assoc = LEFT },
{ symbol = #"-", precedence = 2, assoc = LEFT }
]
fun find (c : char) : operator option = List.find (fn ({symbol, ...} : operator) => symbol = c) operators
infix cmp
fun ({precedence=p1, assoc=a1, ...} : operator) cmp ({precedence=p2, ...} : operator) =
case a1 of
LEFT => p1 <= p2
| RIGHT => p1 < p2
end
signature SHUNTING_YARD = sig
type 'a tree
type content
val parse : string -> content tree
end
structure ShuntingYard : SHUNTING_YARD = struct
structure O = Operator
val cmp = O.cmp
(* did you know infixity doesn't "carry out" of a structure unless you open it? TIL *)
infix cmp
fun pop2 (b::a::rest) = ((a, b), rest)
| pop2 _ = raise Fail "bad input"
datatype content = Op of char
| Int of int
datatype 'a tree = Leaf
| Node of 'a tree * 'a * 'a tree
fun parse_int' tokens curr = case tokens of
[] => (List.rev curr, [])
| t::ts => if Char.isDigit t then parse_int' ts (t::curr)
else (List.rev curr, t::ts)
fun parse_int tokens = let
val (int_chars, rest) = parse_int' tokens []
in
((Option.valOf o Int.fromString o String.implode) int_chars, rest)
end
fun parse (s : string) : content tree = let
val tokens = String.explode s
(* parse': tokens operator_stack trees *)
fun parse' [] [] [result] = result
| parse' [] (opr::os) trees =
if opr = #"(" orelse opr = #")" then raise Fail "bad input"
else let
val ((a,b), trees') = pop2 trees
val trees'' = (Node (a, Op opr, b)) :: trees'
in
parse' [] os trees''
end
| parse' (t::ts) operators trees =
if Char.isSpace t then parse' ts operators trees else
if t = #"(" then parse' ts (t::operators) (trees : content tree list) else
if t = #")" then let
(* process_operators : operators trees *)
fun process_operators [] _ = raise Fail "bad input"
| process_operators (opr::os) trees =
if opr = #"(" then (os, trees)
else let
val ((a, b), trees') = pop2 trees
val trees'' = (Node (a, Op opr, b)) :: trees'
in
process_operators os trees''
end
val (operators', trees') = process_operators (operators : char list) (trees : content tree list)
in
parse' ts operators' trees'
end else
(case O.find (t : char) of
SOME o1 => let
(* process_operators : operators trees *)
fun process_operators [] trees = ([], trees)
| process_operators (o2::os) trees = (case O.find o2 of
SOME o2 =>
if o1 cmp o2 then let
val ((a, b), trees') = pop2 trees
val trees'' = (Node (a, Op (#symbol o2), b)) :: trees'
in
process_operators os trees''
end
else ((#symbol o2)::os, trees)
| NONE => (o2::os, trees))
val (operators', trees') = process_operators operators trees
in
parse' ts ((#symbol o1)::operators') trees'
end
| NONE => let
val (n, tokens') = parse_int (t::ts)
in
parse' tokens' operators ((Node (Leaf, Int n, Leaf)) :: trees)
end)
| parse' _ _ _ = raise Fail "bad input"
in
parse' tokens [] []
end
end |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Swift | Swift | import Foundation
// Using arrays for both stack and queue
struct Stack<T> {
private(set) var elements = [T]()
var isEmpty: Bool { return elements.isEmpty }
mutating func push(newElement: T) {
elements.append(newElement)
}
mutating func pop() -> T {
return elements.removeLast()
}
func top() -> T? {
return elements.last
}
}
struct Queue<T> {
private(set) var elements = [T]()
var isEmpty: Bool { return elements.isEmpty }
mutating func enqueue(newElement: T) {
elements.append(newElement)
}
mutating func dequeue() -> T {
return elements.removeFirst()
}
}
enum Associativity { case Left, Right }
// Define abstract interface, which can be used to restrict Set extension
protocol OperatorType: Comparable, Hashable {
var name: String { get }
var precedence: Int { get }
var associativity: Associativity { get }
}
struct Operator: OperatorType {
let name: String
let precedence: Int
let associativity: Associativity
// same operator names are not allowed
var hashValue: Int { return "\(name)".hashValue }
init(_ name: String, _ precedence: Int, _ associativity: Associativity) {
self.name = name; self.precedence = precedence; self.associativity = associativity
}
}
func ==(x: Operator, y: Operator) -> Bool {
// same operator names are not allowed
return x.name == y.name
}
func <(x: Operator, y: Operator) -> Bool {
// compare operators by their precedence and associavity
return (x.associativity == .Left && x.precedence == y.precedence) || x.precedence < y.precedence
}
extension Set where Element: OperatorType {
func contains(op: String?) -> Bool {
guard let operatorName = op else { return false }
return contains { $0.name == operatorName }
}
subscript (operatorName: String) -> Element? {
get {
return filter { $0.name == operatorName }.first
}
}
}
// Convenience
extension String {
var isNumber: Bool { return Double(self) != nil }
}
struct ShuntingYard {
enum Error: ErrorType {
case MismatchedParenthesis(String)
case UnrecognizedToken(String)
}
static func parse(input: String, operators: Set<Operator>) throws -> String {
var stack = Stack<String>()
var output = Queue<String>()
let tokens = input.componentsSeparatedByString(" ")
for token in tokens {
// Wikipedia: if token is a number add it to the output queue
if token.isNumber {
output.enqueue(token)
}
// Wikipedia: else if token is a operator:
else if operators.contains(token) {
// Wikipedia: while there is a operator on top of the stack and has lower precedence than current operator (token)
while operators.contains(stack.top()) && hasLowerPrecedence(token, stack.top()!, operators) {
// Wikipedia: pop it off to the output queue
output.enqueue(stack.pop())
}
// Wikipedia: push current operator (token) onto the operator stack
stack.push(token)
}
// Wikipedia: If the token is a left parenthesis, then push it onto the stack.
else if token == "(" {
stack.push(token)
}
// Wikipedia: If the token is a right parenthesis:
else if token == ")" {
// Wikipedia: Until the token at the top of the stack is a left parenthesis
while !stack.isEmpty && stack.top() != "(" {
// Wikipedia: pop operators off the stack onto the output queue.
output.enqueue(stack.pop())
}
// If the stack runs out, than there are mismatched parentheses.
if stack.isEmpty {
throw Error.MismatchedParenthesis(input)
}
// Wikipedia: Pop the left parenthesis from the stack, but not onto the output queue.
stack.pop()
}
// if token is not number, operator or a parenthesis, then is not recognized
else {
throw Error.UnrecognizedToken(token)
}
}
// Wikipedia: When there are no more tokens to read:
// Wikipedia: While there are still operator tokens in the stack:
while operators.contains(stack.top()) {
// Wikipedia: Pop the operator onto the output queue.
output.enqueue(stack.pop())
}
// Wikipedia: If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses
// Note: Assume that all operators has been poped onto the output queue.
if stack.isEmpty == false {
throw Error.MismatchedParenthesis(input)
}
return output.elements.joinWithSeparator(" ")
}
static private func containsOperator(stack: Stack<String>, _ operators: [String: NSDictionary]) -> Bool {
guard stack.isEmpty == false else { return false }
// Is there a matching operator in the operators set?
return operators[stack.top()!] != nil ? true : false
}
static private func hasLowerPrecedence(x: String, _ y: String, _ operators: Set<Operator>) -> Bool {
guard let first = operators[x], let second = operators[y] else { return false }
return first < second
}
}
let input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
let operators: Set<Operator> = [
Operator("^", 4, .Right),
Operator("*", 3, .Left),
Operator("/", 3, .Left),
Operator("+", 2, .Left),
Operator("-", 2, .Left)
]
let output = try! ShuntingYard.parse(input, operators: operators)
print("input: \(input)")
print("output: \(output)")
|
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
| #Factor | Factor | : pangram? ( str -- ? )
[ "abcdefghijklmnopqrstuvwxyz" ] dip >lower diff length 0 = ;
"How razorback-jumping frogs can level six piqued gymnasts!" 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
| #Forth | Forth | : pangram? ( addr len -- ? )
0 -rot bounds do
i c@ 32 or [char] a -
dup 0 26 within if
1 swap lshift or
else drop then
loop
1 26 lshift 1- = ;
s" The five boxing wizards jump quickly." pangram? . \ -1 |
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.
| #PicoLisp | PicoLisp | (setq
Low '(A B)
Upp '(B A)
Sym '((+ A B) A) )
(de binomial (N K)
(let f
'((N)
(if (=0 N) 1 (apply * (range 1 N))) )
(if (> K N)
0
(/
(f N)
(* (f (- N K)) (f K)) ) ) ) )
(de pascal (N Z)
(for Lst
(mapcar
'((A)
(mapcar
'((B) (apply binomial (mapcar eval Z)))
(range 0 N) ) )
(range 0 N) )
(for L Lst
(prin (align 2 L) " ") )
(prinl) )
(prinl) )
(pascal 4 Low)
(pascal 4 Upp)
(pascal 4 Sym) |
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.
| #PL.2FI | PL/I | PASCAL_MATRIX: PROCEDURE OPTIONS (MAIN); /* derived from Fortran version 18 Decenber 2021 */
pascal_lower: procedure(a);
declare a(*,*) fixed binary;
declare (n, i, j) fixed binary;
n = hbound(a,1);
a = 0;
a(*, 1) = 1;
do i = 2 to n;
do j = 2 to i;
a(i, j) = a(i - 1, j) + a(i - 1, j - 1);
end;
end;
end pascal_lower;
pascal_upper: procedure(a);
declare a(*,*) fixed binary;
declare (n, i, j) fixed binary;
n = hbound(a,1);
a = 0;
a(1, *) = 1;
do i = 2 to n;
do j = 2 to i;
a(j, i) = a(j, i - 1) + a(j - 1, i - 1);
end;
end;
end pascal_upper;
pascal_symmetric: procedure(a);
declare a(*,*) fixed binary;
declare (n, i, j) fixed binary;
n = hbound(a,1);
a = 0;
a(*, 1) = 1;
a(1, *) = 1;
do i = 2 to n;
do j = 2 to n;
a(i, j) = a(i - 1, j) + a(i, j - 1);
end;
end;
end pascal_symmetric;
declare n fixed binary;
put ('Size of matrix?');
get (n);
begin;
declare a(n, n) fixed binary;
put skip list ('Lower Pascal Matrix');
call pascal_lower(a);
put edit (a) (skip, (n) f(3) );
put skip list ('Upper Pascal Matrix');
call pascal_upper(a);
put edit (a) (skip, (n) f(3) );
put skip list ('Symmetric Pascal Matrix');
call pascal_symmetric(a);
put edit (a) (skip, (n) f(3) );
end;
end PASCAL_MATRIX;
|
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
| #Excel | Excel | PASCAL
=LAMBDA(n,
BINCOEFF(n - 1)(
SEQUENCE(1, n, 0, 1)
)
)
BINCOEFF
=LAMBDA(n,
LAMBDA(k,
QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
)
) |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #VBA | VBA |
Option Explicit
Sub Main()
Dim s() As String, i As Long
Debug.Print "list of 10 passwords : "
'do a list of 10 passwords with password's lenght = 21 and visually similar = False
s = Gp(10, 21, False)
'return
Debug.Print "1- with password's lenght = 21 and visually similar = False :"
For i = 1 To UBound(s): Debug.Print s(i): Next
'do a list of 10 passwords with pattern = "A/9-a/1-9/4-!/5" and visually similar = True
s = Gp(10, "A/9-a/1-9/4-!/5", True)
'return
Debug.Print "2- with pattern = ""A/9-a/1-9/4-!/5"" and visually similar = True :"
For i = 1 To UBound(s): Debug.Print s(i): Next
End Sub
Sub HelpMe()
Dim s As String
s = "Help :" & vbCrLf
s = s & "----------------------------------" & vbCrLf
s = s & "The function (named : Gp) needs 3 required parameters :" & vbCrLf & vbCrLf
s = s & "1- Nb_Passwords (Long) : the number of passwords to generate." & vbCrLf & vbCrLf
s = s & "2- NbChar_Or_Pattern (Variant) : either a number or a pattern" & vbCrLf
s = s & " If number : NbChar_Or_Pattern specify the password length. All the digits are random ASCII characters" & vbCrLf
s = s & " If pattern : NbChar_Or_Pattern specify the password length and the layout of passwords." & vbCrLf
s = s & " The pattern is built like this :" & vbCrLf
s = s & " ""A"" means Upper case, ""a"" means lower case, 9 means numerics and ! means others characters." & vbCrLf
s = s & " ""-"" is the separator between these values." & vbCrLf
s = s & " the number of characters is specified after the sign (required): ""/""" & vbCrLf
s = s & " example of pattern available : ""A/3-a/2-9/1-!/1""" & vbCrLf & vbCrLf
s = s & "3- Excl_Similar_Chars (Boolean) : True if you want the option of excluding visually similar characters."
Debug.Print s
End Sub
Private Function Gp(Nb_Passwords As Long, NbChar_Or_Pattern As Variant, Excl_Similar_Chars As Boolean) As String()
'generate a list of passwords
Dim l As Long, s() As String
ReDim s(1 To Nb_Passwords)
If IsNumeric(NbChar_Or_Pattern) Then
For l = 1 To Nb_Passwords
s(l) = p(CLng(NbChar_Or_Pattern), Excl_Similar_Chars)
Next l
Else
For l = 1 To Nb_Passwords
s(l) = ttt(CStr(NbChar_Or_Pattern), Excl_Similar_Chars)
Next l
End If
Gp = s
End Function
Public Function p(n As Long, e As Boolean) As String
'create 1 password without pattern (just with the password's lenght)
Dim t As String, i As Long, a As Boolean, b As Boolean, c As Boolean, d As Boolean
Randomize Timer
If n < 4 Then
p = "Error. Numbers of characters is too small. Min : 4"
ElseIf n >= 4 And n < 7 Then
T = u(122, 97) & u(90, 65) & u(57, 48) & v
For j = 5 To n
i = Int((4 * Rnd) + 1)
Select Case i
Case 1: T = T & u(122, 97)
Case 2: T = T & u(90, 65)
Case 3: T = T & u(57, 48)
Case 4: T = T & v
End Select
Next j
'Debug.Print T
p = y(T)
Else
Do
i = Int((4 * Rnd) + 1)
Select Case i
Case 1: t = t & u(122, 97): a = True
Case 2: t = t & u(90, 65): b = True
Case 3: t = t & u(57, 48): c = True
Case 4: t = t & v: d = True
End Select
If Len(t) >= 2 And e Then
If x(t) Then t = Left(t, Len(t) - 1)
End If
If Len(t) = n Then
If a And b And c And d Then
Exit Do
Else
w t, a, b, c, d
p = p(n, e)
End If
ElseIf Len(t) > n Then
w t, a, b, c, d
p = p(n, e)
End If
Loop
p = t
End If
End Function
Public Function ttt(s As String, e As Boolean) As String
'create 1 password with pattern
Dim a, i As Long, j As Long, st As String, Nb As Long
a = Split(s, "-")
For i = 0 To UBound(a)
Select Case Left(a(i), 1)
Case "A"
Nb = CLng(Split(a(i), "/")(1)): j = 0
Do
j = j + 1
st = st & u(90, 65)
If Len(st) >= 2 And e Then
If x(st) Then st = Left(st, Len(st) - 1): j = j - 1
End If
Loop While j < Nb
Case "a"
Nb = CLng(Split(a(i), "/")(1)): j = 0
Do
j = j + 1
st = st & u(122, 97)
If Len(st) >= 2 And e Then
If x(st) Then st = Left(st, Len(st) - 1): j = j - 1
End If
Loop While j < Nb
Case "9"
Nb = CLng(Split(a(i), "/")(1)): j = 0
Do
j = j + 1
st = st & u(57, 48)
If Len(st) >= 2 And e Then
If x(st) Then st = Left(st, Len(st) - 1): j = j - 1
End If
Loop While j < Nb
Case "!"
Nb = CLng(Split(a(i), "/")(1)): j = 0
Do
j = j + 1
st = st & v
If Len(st) >= 2 And e Then
If x(st) Then st = Left(st, Len(st) - 1): j = j - 1
End If
Loop While j < Nb
End Select
Next i
ttt = y(st)
End Function
Private Function u(m As Long, l As Long) As String
'random 1 character in lower/upper case or numeric
Randomize Timer
u = Chr(Int(((m - l + 1) * Rnd) + l))
End Function
Private Function v() As String
'random 1 character "special"
Randomize Timer
v = Mid("!""#$%&'()*+,-./:;<=>?@[]^_{|}~", Int((30 * Rnd) + 1), 1)
End Function
Private Sub w(t As String, a As Boolean, b As Boolean, c As Boolean, d As Boolean)
t = vbNullString: a = False: b = False: c = False: d = False
End Sub
Private Function x(s As String) As Boolean
'option of excluding visually similar characters
Dim t, i As Long
Const d As String = "Il I1 l1 lI 1l 1I 0O O0 5S S5 2Z 2? Z? Z2 ?2 ?Z DO OD"
t = Split(d, " ")
For i = 0 To UBound(t)
If Right(s, 2) = t(i) Then
x = True: Exit Function
End If
Next
End Function
Private Function y(s As String) As String
'shuffle the password's letters only if pattern
Dim i&, t, r As String, d() As Long
t = Split(StrConv(s, vbUnicode), Chr(0))
d = z(UBound(t))
For i = 0 To UBound(t)
r = r & t(d(i))
Next i
y = Left(r, Len(r) - 1)
End Function
Private Function z(l As Long) As Long()
'http://rosettacode.org/wiki/Best_shuffle#VBA
Dim i As Long, ou As Long, temp() As Long
Dim c As New Collection
ReDim temp(l)
If l = 1 Then
temp(0) = 0
ElseIf l = 2 Then
temp(0) = 1: temp(1) = 0
Else
Randomize
Do
ou = Int(Rnd * l)
On Error Resume Next
c.Add CStr(ou), CStr(ou)
If Err <> 0 Then
On Error GoTo 0
Else
temp(ou) = i
i = i + 1
End If
Loop While c.Count <> l
End If
z = temp
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.
| #Maxima | Maxima | rmod(i, j) := mod(j, i)$
rpow(x, y) := y^x$
rpn(sexpr) := (
operands: [],
expr: charlist(sexpr),
for token in expr do (
if token = "+" then (
push(pop(operands) + pop(operands), operands)
)
elseif token = "-" then (
push(-1 * (pop(operands) - pop(operands)), operands)
)
elseif token = "*" then (
push(pop(operands) * pop(operands), operands)
)
elseif token = "/" then (
push(1 / (pop(operands) / pop(operands)), operands)
)
elseif token = "%" then (
push(rmod(pop(operands), pop(operands)), operands)
)
elseif token = "^" then (
push(rpow(pop(operands), pop(operands)), operands)
)
elseif token # " " then (
push(parse_string(token), operands)
),
if token # " " then (
print(token, " : ", operands)
)
),
pop(operands)
)$
rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"), numer; |
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.
| #MiniScript | MiniScript | RPN = function(inputText)
tokens = inputText.split
stack = []
while tokens
tok = tokens.pull
if "+-*/^".indexOf(tok) != null then
b = stack.pop
a = stack.pop
if tok == "+" then stack.push a + b
if tok == "-" then stack.push a - b
if tok == "*" then stack.push a * b
if tok == "/" then stack.push a / b
if tok == "^" then stack.push a ^ b
else
stack.push val(tok)
end if
print tok + " --> " + stack
end while
return stack[0]
end function
print 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
| #Batch_File | Batch File | @echo off
setlocal enabledelayedexpansion
set /p string=Your string :
set count=0
:loop
if "!%string%:~%count%,1!" neq "" (
set reverse=!%string%:~%count%,1!!reverse!
set /a count+=1
goto loop
)
set palindrome=isn't
if "%string%"=="%reverse%" set palindrome=is
echo %string% %palindrome% a palindrome.
pause
exit |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Ruby | Ruby | def palindromesgapful(digit, pow)
r1 = digit * (10**pow + 1)
r2 = 10**pow * (digit + 1)
nn = digit * 11
(r1...r2).select { |i| n = i.to_s; n == n.reverse && i % nn == 0 }
end
def digitscount(digit, count)
pow = 2
nums = []
while nums.size < count
nums += palindromesgapful(digit, pow)
pow += 1
end
nums[0...count]
end
count = 20
puts "First 20 palindromic gapful numbers ending with:"
(1..9).each { |digit| print "#{digit} : #{digitscount(digit, count)}\n" }
count = 100
puts "\nLast 15 of first 100 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "#{digit} : #{digitscount(digit, count).last(15)}\n" }
count = 1000
puts "\nLast 10 of first 1000 palindromic gapful numbers ending in:"
(1..9).each { |digit| print "#{digit} : #{digitscount(digit, count).last(10)}\n" } |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Tcl | Tcl | package require Tcl 8.5
# Helpers
proc tokenize {str} {
regexp -all -inline {[\d.]+|[-*^+/()]} $str
}
proc precedence op {
dict get {^ 4 * 3 / 3 + 2 - 2} $op
}
proc associativity op {
if {$op eq "^"} {return "right"} else {return "left"}
}
proc shunting {expression} {
set stack {}
foreach token [tokenize $expression] {
if {[string is double $token]} {
puts "add to output: $token"
lappend output $token
} elseif {$token eq "("} {
puts "push parenthesis"
lappend stack $token
} elseif {$token eq ")"} {
puts "popping to parenthesis"
while {[lindex $stack end] ne "("} {
lappend output [lindex $stack end]
set stack [lreplace $stack end end]
puts "...popped [lindex $output end] to output"
}
set stack [lreplace $stack end end]
puts "...found parenthesis"
} else {
puts "adding operator: $token"
set p [precedence $token]
set a [associativity $token]
while {[llength $stack]} {
set o2 [lindex $stack end]
if {
$o2 ne "(" &&
(($a eq "left" && $p <= [precedence $o2]) ||
($a eq "right" && $p < [precedence $o2]))
} then {
puts "...popped operator $o2 to output"
lappend output $o2
set stack [lreplace $stack end end]
} else {
break
}
}
lappend stack $token
}
puts "\t\tOutput:\t$output\n\t\tStack:\t$stack"
}
puts "transferring tokens from stack to output"
lappend output {*}[lreverse $stack]
}
puts [shunting "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"] |
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
| #Fortran | Fortran | module pangram
implicit none
private
public :: is_pangram
character (*), parameter :: lower_case = 'abcdefghijklmnopqrstuvwxyz'
character (*), parameter :: upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
contains
function to_lower_case (input) result (output)
implicit none
character (*), intent (in) :: input
character (len (input)) :: output
integer :: i
integer :: j
output = input
do i = 1, len (output)
j = index (upper_case, output (i : i))
if (j /= 0) then
output (i : i) = lower_case (j : j)
end if
end do
end function to_lower_case
function is_pangram (input) result (output)
implicit none
character (*), intent (in) :: input
character (len (input)) :: lower_case_input
logical :: output
integer :: i
lower_case_input = to_lower_case (input)
output = .true.
do i = 1, len (lower_case)
if (index (lower_case_input, lower_case (i : i)) == 0) then
output = .false.
exit
end if
end do
end function is_pangram
end module pangram |
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.
| #PureBasic | PureBasic | EnableExplicit
Define.i x=5, I, J
Macro Print_Pascal_matrix(typ)
PrintN(typ)
For I=1 To x
For J=1 To x : Print(RSet(Str(p(I,J)),3," ")+Space(3)) : Next
PrintN("")
Next
Print(~"\n\n")
EndMacro
Procedure Pascal_sym(n.i,Array p.i(2))
Define.i I,J
p(1,0)=1
For I=1 To n
For J=1 To n : p(I,J)=p(I-1,J)+p(I,J-1) : Next
Next
EndProcedure
Procedure Pascal_upp(n.i,Array p.i(2))
Define.i I,J
p(0,0)=1
For I=1 To n
For J=1 To n : p(I,J)=p(I-1,J-1)+p(I,J-1) : Next
Next
EndProcedure
Procedure Pascal_low(n.i,Array p.i(2))
Define.i I,J
Pascal_upp(n,p())
Dim p2.i(n,n)
CopyArray(p(),p2())
For I=1 To n
For J=1 To n : Swap p(J,I),p2(I,J) : Next
Next
EndProcedure
OpenConsole()
Dim p.i(x,x)
Pascal_upp(x,p())
Print_Pascal_matrix("Upper:")
Dim p.i(x,x)
Pascal_low(x,p())
Print_Pascal_matrix("Lower:")
Dim p.i(x,x)
Pascal_sym(x,p())
Print_Pascal_matrix("Symmetric:")
Input()
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
| #F.23 | F# | let rec nextrow l =
match l with
| [] -> []
| h :: [] -> [1]
| h :: t -> h + t.Head :: nextrow t
let pascalTri n = List.scan(fun l i -> 1 :: nextrow l) [1] [1 .. n]
for row in pascalTri(10) do
for i in row do
printf "%s" (i.ToString() + ", ")
printfn "%s" "\n"
|
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #Wren | Wren | import "random" for Random
import "/ioutil" for FileUtil, File, Input
import "/fmt" for Fmt
import "os" for Process
var r = Random.new()
var rr = Random.new() // use a separate generator for shuffles
var lb = FileUtil.lineBreak
var lower = "abcdefghijklmnopqrstuvwxyz"
var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var digit = "0123456789"
var other = """!"#$%&'()*+,-./:;<=>?@[]^_{|}~"""
var exclChars = [
"'I', 'l' and '1'",
"'O' and '0' ",
"'5' and 'S' ",
"'2' and 'Z' "
]
var shuffle = Fn.new { |s|
var sl = s.toList
rr.shuffle(sl)
return sl.join()
}
var generatePasswords = Fn.new { |pwdLen, pwdNum, toConsole, toFile|
var ll = lower.count
var ul = upper.count
var dl = digit.count
var ol = other.count
var tl = ll + ul + dl + ol
var fw = toFile ? File.create("pwds.txt") : null
if (toConsole) System.print("\nThe generated passwords are:")
for (i in 0...pwdNum) {
var pwd = lower[r.int(ll)] + upper[r.int(ul)] + digit[r.int(dl)] + other[r.int(ol)]
for (j in 0...pwdLen - 4) {
var k = r.int(tl)
pwd = pwd + ((k < ll) ? lower[k] :
(k < ll + ul) ? upper[k - ll] :
(k < tl - ol) ? digit[k - ll - ul] : other[tl - 1 - k])
}
for (i in 1..5) pwd = shuffle.call(pwd) // shuffle 5 times say
if (toConsole) Fmt.print(" $2d: $s", i + 1, pwd)
if (toFile) {
fw.writeBytes(pwd)
if (i < pwdNum - 1) fw.writeBytes(lb)
}
}
if (toFile) {
System.print("\nThe generated passwords have been written to the file pwds.txt")
fw.close()
}
}
var printHelp = Fn.new {
System.print("""
This program generates up to 99 passwords of between 5 and 20 characters in
length.
You will be prompted for the values of all parameters when the program is run
- there are no command line options to memorize.
The passwords can either be written to the console or to a file (pwds.txt),
or both.
The passwords must contain at least one each of the following character types:
lower-case letters : a -> z
upper-case letters : A -> Z
digits : 0 -> 9
other characters : !"#$%&'()*+,-./:;<=>?@[]^_{|}~
Optionally, a seed can be set for the random generator
(any non-zero number) otherwise the default seed will be used.
Even if the same seed is set, the passwords won't necessarily be exactly
the same on each run as additional random shuffles are always performed.
You can also specify that various sets of visually similar characters
will be excluded (or not) from the passwords, namely: Il1 O0 5S 2Z
Finally, the only command line options permitted are -h and -help which
will display this page and then exit.
Any other command line parameters will simply be ignored and the program
will be run normally.
""")
}
var args = Process.arguments
if (args.count == 1 && (args[0] == "-h" || args[0] == "-help")) {
printHelp.call()
return
}
System.print("Please enter the following and press return after each one")
var pwdLen = Input.integer(" Password length (5 to 20) : ", 5, 20)
var pwdNum = Input.integer(" Number to generate (1 to 99) : ", 1, 99)
var seed = Input.number (" Seed value (0 to use default) : ")
if (seed != 0) r = Random.new(seed)
System.print(" Exclude the following visually similar characters")
for (i in 0..3) {
var yn = Input.option(" %(exclChars[i]) y/n : ", "ynYN")
if (yn == "y" || yn == "Y") {
if (i == 0) {
upper = upper.replace("I", "")
lower = lower.replace("l", "")
digit = digit.replace("1", "")
} else if (i == 1) {
upper = upper.replace("O", "")
digit = digit.replace("0", "")
} else if (i == 2) {
upper = upper.replace("S", "")
digit = digit.replace("5", "")
} else if (i == 3) {
upper = upper.replace("Z", "")
digit = digit.replace("2", "")
}
}
}
var toConsole = Input.option(" Write to console y/n : ", "ynYN")
toConsole = toConsole == "y" || toConsole == "Y"
var toFile = true
if (toConsole) {
toFile = Input.option(" Write to file y/n : ", "ynYN")
toFile = toFile == "y" || toFile == "Y"
}
generatePasswords.call(pwdLen, pwdNum, toConsole, toFile) |
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.
| #N.2Ft.2Froff | N/t/roff | .ig
RPN parser implementation in TROFF
..
.\" \(*A stack implementation
.nr Ac 0
.af Ac 1
.de APUSH
.if (\\n(Ac>=0)&(\\n(Ac<27) \{ \
. nr Ac +1
. af Ac A
. nr A\\n(Ac \\$1
. af Ac 1
\}
..
.de APOP
.if (\\n(Ac>0)&(\\n(Ac<27) \{ \
. af Ac A
. rr A\\n(Ac \\$1
. af Ac 1
. nr Ac -1
..
.\" Facility to print entire stack
.de L2
.af Ac 1
.if \\n(Li<=\\n(Ac \{ \
. af Li A
\\n(A\\n(Li
. af Li 1
. nr Li +1
. L2
\}
..
.de APRINT
.nr Li 1
.L2
.br
..
.\" Integer exponentiation algorithm
.de L1
.if \\n(Li<\\$2 \{ \
. nr Rs \\n(Rs*\\$1
. nr Li +1
. L1 \\$1 \\$2
\}
..
.de EXP
.nr Li 0
.nr Rs 1
.L1 \\$1 \\$2
..
.\" RPN Parser
.de REAP
.af Ac A
.nr O2 \\n(A\\n(Ac
.af Ac 1
.nr Ai \\n(Ac-1
.af Ai A
.nr O1 \\n(A\\n(Ai
.APOP
.APOP
..
.de RPNPUSH
.ie '\\$1'+' \{ \
. REAP
. nr Rs \\n(O1+\\n(O2
\}
.el \{ \
. ie '\\$1'-' \{ \
. REAP
. nr Rs \\n(O1-\\n(O2
\}
. el \{ \
. ie '\\$1'*' \{ \
. REAP
. nr Rs \\n(O1*\\n(O2
\}
. el \{ \
. ie '\\$1'/' \{ \
. REAP
. nr Rs \\n(O1/\\n(O2
\}
. el \{ \
. ie '\\$1'%' \{ \
. REAP
. nr Rs \\n(O1%\\n(O2
\}
. el \{ \
. ie '\\$1'^' \{ \
. REAP
. EXP \\n(O1 \\n(O2
\}
. el .nr Rs \\$1
\}
\}
\}
\}
\}
.APUSH \\n(Rs
.APRINT
..
.de RPNPRINT
.if \\n(Ac>1 .tm ERROR (rpn.roff): Malformed input expression. Evaluation stack size: \\n(Ac > 1 .
\\n(AA
..
.de RPNPARSE
.RPNPUSH \\$1
.ie \\n(.$>1 \{ \
. shift
. RPNPARSE \\$@
\}
.el .RPNPRINT
..
.RPNPARSE 3 4 2 * 1 5 - 2 3 ^ ^ / + \" Our input expression |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20
rpnDefaultExpression = '3 4 2 * 1 5 - 2 3 ^ ^ / +'
EODAD = '.*'
parse arg rpnString
if rpnString = '.' then rpnString = rpnDefaultExpression
if rpnString = '' then do
say 'Enter numbers or operators [to stop enter' EODAD']:'
loop label rpnloop forever
rpnval = ask
if rpnval == EODAD then leave rpnloop
rpnString = rpnString rpnval
end rpnloop
end
rpnString = rpnString.space(1)
say rpnString':' evaluateRPN(rpnString)
return
-- -----------------------------------------------------------------------------
method evaluateRPN(rpnString) public static returns Rexx
stack = LinkedList()
op = 0
L = 'L'
R = 'R'
rpnString = rpnString.strip('b')
say 'Input\tOperation\tStack after'
loop label rpn while rpnString.length > 0
parse rpnString token rest
rpnString = rest.strip('b')
say token || '\t\-'
select label tox case token
when '*' then do
say 'Operate\t\t\-'
op[R] = Rexx stack.pop()
op[L] = Rexx stack.pop()
stack.push(op[L] * op[R])
end
when '/' then do
say 'Operate\t\t\-'
op[R] = Rexx stack.pop()
op[L] = Rexx stack.pop()
stack.push(op[L] / op[R])
end
when '+' then do
say 'Operate\t\t\-'
op[R] = Rexx stack.pop()
op[L] = Rexx stack.pop()
stack.push(op[L] + op[R])
end
when '-' then do
say 'Operate\t\t\-'
op[R] = Rexx stack.pop()
op[L] = Rexx stack.pop()
stack.push(op[L] - op[R])
end
when '^' then do
say 'Operate\t\t\-'
op[R] = Rexx stack.pop()
op[L] = Rexx stack.pop()
-- If exponent is a whole number use Rexx built-in exponentiation operation, otherwise use Math.pow()
op[R] = op[R] + 0
if op[R].datatype('w') then stack.push(op[L] ** op[R])
else stack.push(Rexx Math.pow(op[L], op[R]))
end
otherwise do
if token.datatype('n') then do
say 'Push\t\t\-'
stack.push(token)
end
else do
say 'Error\t\t\-'
end
end
end tox
calc = Rexx
say stack.toString
end rpn
say
calc = stack.toString
return calc
|
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
| #BCPL | BCPL | get "libhdr"
let palindrome(s) = valof
$( let l = s%0
for i = 1 to l/2
unless s%i = s%(l+1-i)
resultis false
resultis true
$)
let inexact(s) = valof
$( let temp = vec 1+256/BYTESPERWORD
temp%0 := 0
for i = 1 to s%0 do
$( let ch = s%i | 32
if '0'<=ch & ch<='9' | 'a'<=ch & ch<='z' then
$( temp%0 := temp%0 + 1
temp%(temp%0) := ch
$)
$)
resultis palindrome(temp)
$)
let check(s) =
palindrome(s) -> "exact palindrome",
inexact(s) -> "inexact palindrome",
"not a palindrome"
let start() be
$( let tests = vec 8
tests!0 := "rotor"
tests!1 := "racecar"
tests!2 := "RACEcar"
tests!3 := "level"
tests!4 := "redder"
tests!5 := "rosetta"
tests!6 := "A man, a plan, a canal: Panama"
tests!7 := "Egad, a base tone denotes a bad age"
tests!8 := "This is not a palindrome"
for i = 0 to 8 do
writef("'%S': %S*N", tests!i, check(tests!i))
$) |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Rust | Rust | This version uses number->string then string->number conversions to create palindromes.
|
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
getopprec() {
case "$1" in
'+') echo 2;;
'-') echo 2;;
'*') echo 3;;
'/') echo 4;;
'%') echo 4;;
'^') echo 4;;
'(') echo 5;;
esac
}
getopassoc() {
case "$1" in
'^') echo r;;
*) echo l;;
esac
}
showstacks() {
[ -n "$1" ] && echo "Token: $1" || echo "End parsing"
echo -e "\tOutput: `tr $'\n' ' ' <<< "$out"`"
echo -e "\tOperators: `tr $'\n' ' ' <<< "$ops"`"
}
infix() {
local out="" ops=""
while [ "$#" -gt 0 ]; do
grep -qE '^[0-9]+$' <<< "$1"
if [ "$?" -eq 0 ]; then
out="`sed -e '$a'"$1" -e '/^$/d' <<< "$out"`"
showstacks "$1"
shift && continue
fi
grep -q '^[-+*/^%]$' <<< "$1"
if [ "$?" -eq 0 ]; then
if [ -n "$ops" ]; then
thispred=`getopprec "$1"`
thisassoc=`getopassoc "$1"`
topop="`sed -n '$p' <<< "$ops"`"
thatpred=`getopprec "$topop"`
thatassoc=`getopassoc "$topop"`
while [ $thatpred -gt $thispred ] 2> /dev/null || ( [ \
$thatpred -eq $thispred ] 2> /dev/null && [ $thisassoc = \
'l' ] 2> /dev/null ); do # To /dev/null 'cus u r fake news
[ "$topop" = '(' ] && break
op="`sed -n '$p' <<< "$ops"`"
out="`sed -e '$a'"$op" -e '/^$/d' <<< "$out"`"
ops="`sed '$d' <<< "$ops"`"
topop="`sed -n '$p' <<< "$ops"`"
thatpred=`getopprec "$topop"`
thatassoc=`getopassoc "$topop"`
done
fi
ops="`sed -e '$a'"$1" -e '/^$/d' <<< "$ops"`"
showstacks "$1"
shift && continue
fi
if [ "$1" = '(' ]; then
ops="`sed -e '$a'"$1" -e '/^$/d' <<< "$ops"`"
showstacks "$1"
shift && continue
fi
if [ "$1" = ')' ]; then
grep -q '^($' <<< "`sed -n '$p' <<< "$ops"`"
while [ "$?" -ne 0 ]; do
op="`sed -n '$p' <<< "$ops"`"
out="`sed -e '$a'"$op" -e '/^$/d' <<< "$out"`"
ops="`sed '$d' <<< "$ops"`"
grep -q '^($' <<< "`sed '$p' <<< "$ops"`"
done
ops="`sed '$d' <<< "$ops"`"
showstacks "$1"
shift && continue
fi
shift
done
while [ -n "$ops" ]; do
op="`sed -n '$p' <<< "$ops"`"
out="`sed -e '$a'"$op" -e '/^$/d' <<< "$out"`"
ops="`sed '$d' <<< "$ops"`"
done
showstacks "$1"
}
infix 3 + 4 \* 2 / \( 1 - 5 \) ^ 2 ^ 3 |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isPangram(s As Const String) As Boolean
Dim As Integer length = Len(s)
If length < 26 Then Return False
Dim p As String = LCase(s)
For i As Integer = 97 To 122
If Instr(p, Chr(i)) = 0 Then Return False
Next
Return True
End Function
Dim s(1 To 3) As String = _
{ _
"The quick brown fox jumps over the lazy dog", _
"abbdefghijklmnopqrstuVwxYz", _ '' no c!
"How vexingly quick daft zebras jump!" _
}
For i As Integer = 1 To 3:
Print "'"; s(i); "' is "; IIf(isPangram(s(i)), "a", "not a"); " pangram"
Print
Next
Print
Print "Press nay key to quit"
Sleep |
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.
| #Python | Python | from pprint import pprint as pp
def pascal_upp(n):
s = [[0] * n for _ in range(n)]
s[0] = [1] * n
for i in range(1, n):
for j in range(i, n):
s[i][j] = s[i-1][j-1] + s[i][j-1]
return s
def pascal_low(n):
# transpose of pascal_upp(n)
return [list(x) for x in zip(*pascal_upp(n))]
def pascal_sym(n):
s = [[1] * n for _ in range(n)]
for i in range(1, n):
for j in range(1, n):
s[i][j] = s[i-1][j] + s[i][j-1]
return s
if __name__ == "__main__":
n = 5
print("\nUpper:")
pp(pascal_upp(n))
print("\nLower:")
pp(pascal_low(n))
print("\nSymmetric:")
pp(pascal_sym(n)) |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Factor | Factor | USING: grouping kernel math sequences ;
: (pascal) ( seq -- newseq )
dup last 0 prefix 0 suffix 2 <clumps> [ sum ] map suffix ;
: pascal ( n -- seq )
1 - { { 1 } } swap [ (pascal) ] times ; |
http://rosettacode.org/wiki/Password_generator | Password generator | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a ──► z
upper-case letters: A ──► Z
digits: 0 ──► 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include at least one (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
capital eye, lowercase ell, the digit one
capital oh, the digit zero
the digit five, capital ess
the digit two, capital zee
| #zkl | zkl | var pwdLen=10, pwds=1, xclude="";
argh:=Utils.Argh(
L("+xclude","","Don't use these characters",fcn(arg){ xclude=arg }),
L("+len","","Number of characters in password", fcn(arg){ pwdLen=arg.toInt() } ),
L("+num","","Number of passwords to generate", fcn(arg){ pwds=arg.toInt() } ),
);
try{ argh.parse(vm.arglist) }catch{ System.exit(1) }
isd:='wrap(w){ w.pump(String) - xclude }; // iterator to String
g1,g2,g3 := isd(["a".."z"]), isd(["A".."Z"]), isd(["0".."9"]);
g4:="!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" - xclude;
all:=String(g1,g2,g3,g4);
fcn rnd(s){ s[(0).random(s.len())] } // pick a random character from s
// generate random characters of filler needed to complete password
fill:=(pwdLen-4).pump.fp(String,rnd.fp(all)); // a deferred/pending calculation
do(numPwds){
// Data is byte bucket (and editor). I can shuffle a Data but not a String.
pwd:=T(g1,g2,g3,g4).pump(Data,rnd); // 1 from each of these into a Data
pwd.extend(fill()).shuffle().text.println();
} |
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.
| #Nim | Nim | import math, rdstdin, strutils, tables
type Stack = seq[float]
proc opPow(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a.pow b
proc opMul(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a * b
proc opDiv(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a / b
proc opAdd(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a + b
proc opSub(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a - b
proc opNum(s: var Stack; num: float) =
s.add num
let ops = toTable({"^": opPow,
"*": opMul,
"/": opDiv,
"+": opAdd,
"-": opSub})
proc getInput(inp = ""): seq[string] =
var inp = inp
if inp.len == 0:
inp = readLineFromStdin "Expression: "
result = inp.strip.split
proc rpnCalc(tokens: seq[string]): seq[seq[string]] =
var s: Stack
result = @[@["TOKEN","ACTION","STACK"]]
for token in tokens:
var action = ""
if ops.hasKey token:
action = "Apply op to top of stack"
ops[token](s)
else:
action = "Push num onto top of stack"
s.opNum token.parseFloat
result.add(@[token, action, s.join(" ")])
let rpn = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
echo "For RPN expression: ", rpn
let rp = rpnCalc rpn.getInput
var maxColWidths = newSeq[int](rp[0].len)
for i in 0 .. rp[0].high:
for x in rp:
maxColWidths[i] = max(maxColWidths[i], x[i].len + 3)
for x in rp:
for i, y in x:
stdout.write y.alignLeft(maxColWidths[i])
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.
| #Objeck | Objeck |
use IO;
use Struct;
bundle Default {
class RpnCalc {
function : Main(args : String[]) ~ Nil {
Caculate("3 4 2 * 1 5 - 2 3 ^ ^ / +");
}
function : native : Caculate(rpn : String) ~ Nil {
rpn->PrintLine();
tokens := rpn->Split(" ");
stack := FloatVector->New();
each(i : tokens) {
token := tokens[i]->Trim();
if(token->Size() > 0) {
if(token->Get(0)->IsDigit()) {
stack->AddBack(token->ToFloat());
}
else {
right := stack->Get(stack->Size() - 1); stack->RemoveBack();
left := stack->Get(stack->Size() - 1); stack->RemoveBack();
select(token->Get(0)) {
label '+': {
stack->AddBack(left + right);
}
label '-': {
stack->AddBack(left - right);
}
label '*': {
stack->AddBack(left * right);
}
label '/': {
stack->AddBack(left / right);
}
label '^': {
stack->AddBack(right->Power(left));
}
};
};
PrintStack(stack);
};
};
Console->Print("result: ")->PrintLine(stack->Get(0));
}
function : PrintStack(stack : FloatVector) ~ Nil {
" ["->Print();
each(i : stack) {
stack->Get(i)->Print();
if(i + 1< stack->Size()) {
", "->Print();
};
};
']'->PrintLine();
}
}
}
|
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
| #Befunge | Befunge | v_$0:8p>:#v_:18p08g1-08p >:08g`!v
~->p5p ^ 0v1p80-1g80vj!-g5g80g5_0'ev
:a^80+1:g8<>8g1+:18pv>0"eslaF">:#,_@
[[relet]]-2010------>003-x -^"Tru"< |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Sidef | Sidef | class PalindromeGenerator (digit, base=10) {
has power = base
has after = (digit*power - 1)
has even = false
method next {
if (++after == power*(digit+1)) {
power *= base if even
after = digit*power
even.not!
}
even ? (after*power*base + reverse(after, base))
: (after*power + reverse(after/base, base))
}
}
var task = [
"(Required) First 20 gapful palindromes:", { .first(20) }, 7,
,"\n(Required) 86th through 100th:", { .first(1e2).last(15) }, 8,
,"\n(Optional) 991st through 1,000th:", { .first(1e3).last(10) }, 10,
,"\n(Extra stretchy) 9,995th through 10,000th:", { .first(1e4).last(6) }, 12,
]
task.each_slice(3, {|title, f, w|
say title
for d in (1..9) {
var k = 11*d
var iter = PalindromeGenerator(d)
var arr = f(^Inf->lazy.map { iter.next }.grep {|n| k `divides` n })
say ("#{d}: ", arr.map{ "%*s" % (w, _) }.join(' '))
}
}) |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #VBA | VBA | Option Explicit
Option Base 1
Function ShuntingYard(strInfix As String) As String
Dim i As Long, j As Long, token As String, tokenArray() As String
Dim stack() As Variant, queue() As Variant, discard As String
Dim op1 As String, op2 As String
Debug.Print strInfix
' Get tokens
tokenArray = Split(strInfix)
' Initialize array (removed later)
ReDim stack(1)
ReDim queue(1)
' Loop over tokens
Do While 1
i = i + 1
If i - 1 > UBound(tokenArray) Then
Exit Do
Else
token = tokenArray(i - 1) 'i-1 due to Split returning a Base 0
End If
If token = "" Then: Exit Do
' Print
Debug.Print i, token, Join(stack, ","), Join(queue, ",")
' If-loop over tokens (either brackets, operators, or numbers)
If token = "(" Then
stack = push(token, stack)
ElseIf token = ")" Then
While Peek(stack) <> "("
queue = push(pop(stack), queue)
Wend
discard = pop(stack) 'discard "("
ElseIf isOperator(token) Then
op1 = token
Do While (isOperator(Peek(stack)))
' Debug.Print Peek(stack)
op2 = Peek(stack)
If op2 <> "^" And precedence(op1) = precedence(op2) Then
'"^" is the only right-associative operator
queue = push(pop(stack), queue)
ElseIf precedence(op1$) < precedence(op2$) Then
queue = push(pop(stack), queue)
Else
Exit Do
End If
Loop
stack = push(op1, stack)
Else 'number
'actually, wrong operator could end up here, like say %
'If the token is a number, then add it to the output queue.
queue = push(CStr(token), queue)
End If
Loop
While stack(1) <> ""
If Peek(stack) = "(" Then Debug.Print "no matching ')'": End
queue = push(pop(stack), queue)
Wend
' Print final output
ShuntingYard = Join(queue, " ")
Debug.Print "Output:"
Debug.Print ShuntingYard
End Function
'------------------------------------------
Function isOperator(op As String) As Boolean
isOperator = InStr("+-*/^", op) <> 0 And Len(op$) = 1
End Function
Function precedence(op As String) As Integer
If isOperator(op$) Then
precedence = 1 _
- (InStr("+-*/^", op$) <> 0) _
- (InStr("*/^", op$) <> 0) _
- (InStr("^", op$) <> 0)
End If
End Function
'------------------------------------------
Function push(str, stack) As Variant
Dim out() As Variant, i As Long
If Not IsEmpty(stack(1)) Then
out = stack
ReDim Preserve out(1 To UBound(stack) + 1)
out(UBound(out)) = str
Else
ReDim out(1 To 1)
out(1) = str
End If
push = out
End Function
Function pop(stack)
pop = stack(UBound(stack))
If UBound(stack) > 1 Then
ReDim Preserve stack(1 To UBound(stack) - 1)
Else
stack(1) = ""
End If
End Function
Function Peek(stack)
Peek = stack(UBound(stack))
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
| #Frink | Frink | s = "The quick brown fox jumps over the lazy dog."
println["\"$s\" is" + (isPangram[s] ? "" : " not") + " a pangram."]
isPangram[s] :=
{
charSet = toSet[charList[lc[s]]]
for c = "a" to "z"
if ! charSet.contains[c]
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func main() {
for _, s := range []string{
"The quick brown fox jumps over the lazy dog.",
`Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`,
"Not a pangram.",
} {
if pangram(s) {
fmt.Println("Yes:", s)
} else {
fmt.Println("No: ", s)
}
}
}
func pangram(s string) bool {
var missing uint32 = (1 << 26) - 1
for _, c := range s {
var index uint32
if 'a' <= c && c <= 'z' {
index = uint32(c - 'a')
} else if 'A' <= c && c <= 'Z' {
index = uint32(c - 'A')
} else {
continue
}
missing &^= 1 << index
if missing == 0 {
return true
}
}
return false
} |
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.
| #R | R | lower.pascal <- function(n) {
a <- matrix(0, n, n)
a[, 1] <- 1
if (n > 1) {
for (i in 2:n) {
j <- 2:i
a[i, j] <- a[i - 1, j - 1] + a[i - 1, j]
}
}
a
}
# Alternate version
lower.pascal.alt <- function(n) {
a <- matrix(0, n, n)
a[, 1] <- 1
if (n > 1) {
for (j in 2:n) {
i <- j:n
a[i, j] <- cumsum(a[i - 1, j - 1])
}
}
a
}
# While it's possible to modify lower.pascal to get the upper matrix,
# here we simply transpose the lower one.
upper.pascal <- function(n) t(lower.pascal(n))
symm.pascal <- function(n) {
a <- matrix(0, n, n)
a[, 1] <- 1
for (i in 2:n) {
a[, i] <- cumsum(a[, i - 1])
}
a
} |
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.
| #Racket | Racket | #lang racket
(require math/number-theory)
(define (pascal-upper-matrix n)
(for/list ((i n)) (for/list ((j n)) (j . binomial . i))))
(define (pascal-lower-matrix n)
(for/list ((i n)) (for/list ((j n)) (i . binomial . j))))
(define (pascal-symmetric-matrix n)
(for/list ((i n)) (for/list ((j n)) ((+ i j) . binomial . j))))
(define (matrix->string m)
(define col-width
(for*/fold ((rv 1)) ((r m) (c r))
(if (zero? c) rv (max rv (+ 1 (order-of-magnitude c))))))
(string-append
(string-join
(for/list ((r m))
(string-join (map (λ (c) (~a #:width col-width #:align 'right c)) r) " ")) "\n")
"\n"))
(printf "Upper:~%~a~%" (matrix->string (pascal-upper-matrix 5)))
(printf "Lower:~%~a~%" (matrix->string (pascal-lower-matrix 5)))
(printf "Symmetric:~%~a~%" (matrix->string (pascal-symmetric-matrix 5))) |
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
| #Fantom | Fantom |
class Main
{
Int[] next_row (Int[] row)
{
new_row := [1]
(row.size-1).times |i|
{
new_row.add (row[i] + row[i+1])
}
new_row.add (1)
return new_row
}
Void print_pascal (Int n) // no output for n <= 0
{
current_row := [1]
n.times
{
echo (current_row.join(" "))
current_row = next_row (current_row)
}
}
Void main ()
{
print_pascal (10)
}
}
|
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.
| #OCaml | OCaml | (* binop : ('a -> 'a -> 'a) -> 'a list -> 'a list *)
let binop op = function
| b::a::r -> (op a b)::r
| _ -> failwith "invalid expression"
(* interp : float list -> string -> string * float list *)
let interp s = function
| "+" -> "add", binop ( +. ) s
| "-" -> "subtr", binop ( -. ) s
| "*" -> "mult", binop ( *. ) s
| "/" -> "divide", binop ( /. ) s
| "^" -> "exp", binop ( ** ) s
| str -> "push", (float_of_string str) :: s
(* interp_and_show : float list -> string -> float list *)
let interp_and_show s inp =
let op,s' = interp s inp in
Printf.printf "%s\t%s\t" inp op;
List.(iter (Printf.printf "%F ") (rev s'));
print_newline ();
s'
(* rpn_eval : string -> float list *)
let rpn_eval str =
Printf.printf "Token\tAction\tStack\n";
let ss = Str.(split (regexp_string " ") str) in
List.fold_left interp_and_show [] ss |
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
| #BQN | BQN | Pal ← ≡⊸⌽
Pal1 ← ⊢≡⌽
Pal2 ← {𝕩≡⌽𝕩} |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #Wren | Wren | import "/fmt" for Conv, Fmt
var reverse = Fn.new { |s|
var e = 0
while (s > 0) {
e = e * 10 + (s % 10)
s = (s/10).floor
}
return e
}
var MAX = 100000
var data = [ [1, 20, 7], [86, 100, 8], [991, 1000, 10], [9995, 10000, 12], [99996, 100000, 14] ]
var results = {}
for (d in data) {
for (i in d[0]..d[1]) results[i] = List.filled(9, 0)
}
var p
for (d in 1..9) {
var next_d = false
var count = 0
var pow = 1
var fl = d * 11
for (nd in 3..19) {
var slim = (d + 1) * pow
for (s in d*pow...slim) {
var e = reverse.call(s)
var mlim = (nd%2 != 1) ? 1 : 10
for (m in 0...mlim) {
if (nd%2 == 0) {
p = s*pow*10 + e
} else {
p = s*pow*100 + m*pow*10 + e
}
if (p%fl == 0) {
count = count + 1
var rc = results[count]
if (rc != null) rc[d-1] = p
if (count == MAX) next_d = true
}
if (next_d) break
}
if (next_d) break
}
if (next_d) break
if (nd%2 == 1) pow = pow * 10
}
}
for (d in data) {
var s1 = Fmt.ordinalize(d[0])
var s2 = Fmt.ordinalize(d[1])
System.print("%(s1) to %(s2) palindromic gapful numbers (> 100) ending with:")
for (i in 1..9) {
System.write("%(i): ")
for (j in d[0]..d[1]) System.write("%(Fmt.d(d[2], results[j][i-1])) ")
System.print()
}
System.print()
} |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Class SymbolType
Public ReadOnly symbol As String
Public ReadOnly precedence As Integer
Public ReadOnly rightAssociative As Boolean
Public Sub New(symbol As String, precedence As Integer, rightAssociative As Boolean)
Me.symbol = symbol
Me.precedence = precedence
Me.rightAssociative = rightAssociative
End Sub
End Class
ReadOnly Operators As Dictionary(Of String, SymbolType) = New Dictionary(Of String, SymbolType) From
{
{"^", New SymbolType("^", 4, True)},
{"*", New SymbolType("*", 3, False)},
{"/", New SymbolType("/", 3, False)},
{"+", New SymbolType("+", 2, False)},
{"-", New SymbolType("-", 2, False)}
}
Function ToPostfix(infix As String) As String
Dim tokens = infix.Split(" ")
Dim stack As New Stack(Of String)
Dim output As New List(Of String)
Dim Print = Sub(action As String) Console.WriteLine("{0,-4} {1,-18} {2}", action + ":", $"stack[ {String.Join(" ", stack.Reverse())} ]", $"out[ {String.Join(" ", output)} ]")
For Each token In tokens
Dim iv As Integer
Dim op1 As SymbolType
Dim op2 As SymbolType
If Integer.TryParse(token, iv) Then
output.Add(token)
Print(token)
ElseIf Operators.TryGetValue(token, op1) Then
While stack.Count > 0 AndAlso Operators.TryGetValue(stack.Peek(), op2)
Dim c = op1.precedence.CompareTo(op2.precedence)
If c < 0 OrElse Not op1.rightAssociative AndAlso c <= 0 Then
output.Add(stack.Pop())
Else
Exit While
End If
End While
stack.Push(token)
Print(token)
ElseIf token = "(" Then
stack.Push(token)
Print(token)
ElseIf token = ")" Then
Dim top = ""
While stack.Count > 0
top = stack.Pop()
If top <> "(" Then
output.Add(top)
Else
Exit While
End If
End While
If top <> "(" Then
Throw New ArgumentException("No matching left parenthesis.")
End If
Print(token)
End If
Next
While stack.Count > 0
Dim top = stack.Pop()
If Not Operators.ContainsKey(top) Then
Throw New ArgumentException("No matching right parenthesis.")
End If
output.Add(top)
End While
Print("pop")
Return String.Join(" ", output)
End Function
Sub Main()
Dim infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
Console.WriteLine(ToPostfix(infix))
End Sub
End Module |
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
| #Go | Go | package main
import "fmt"
func main() {
for _, s := range []string{
"The quick brown fox jumps over the lazy dog.",
`Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`,
"Not a pangram.",
} {
if pangram(s) {
fmt.Println("Yes:", s)
} else {
fmt.Println("No: ", s)
}
}
}
func pangram(s string) bool {
var missing uint32 = (1 << 26) - 1
for _, c := range s {
var index uint32
if 'a' <= c && c <= 'z' {
index = uint32(c - 'a')
} else if 'A' <= c && c <= 'Z' {
index = uint32(c - 'A')
} else {
continue
}
missing &^= 1 << index
if missing == 0 {
return true
}
}
return false
} |
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.
| #Raku | Raku | # Extend a matrix in 2 dimensions based on 3 neighbors.
sub grow-matrix(@matrix, &func) {
my $n = @matrix.shape eq '*' ?? 1 !! @matrix.shape[0];
my @m[$n+1;$n+1];
for ^$n X ^$n -> ($i, $j) {
@m[$i;$j] = @matrix[$i;$j];
}
# West North NorthWest
@m[$n; 0] = func( 0, @m[$n-1;0], 0 );
@m[ 0;$n] = func( @m[0;$n-1], 0, 0 );
@m[$_;$n] = func( @m[$_;$n-1], @m[$_-1;$n], @m[$_-1;$n-1]) for 1 ..^ $n;
@m[$n;$_] = func( @m[$n;$_-1], @m[$n-1;$_], @m[$n-1;$_-1]) for 1 .. $n;
@m;
}
# I am but mad north-northwest...
sub madd-n-nw(@m) { grow-matrix @m, -> $w, $n, $nw { $n + $nw } }
sub madd-w-nw(@m) { grow-matrix @m, -> $w, $n, $nw { $w + $nw } }
sub madd-w-n (@m) { grow-matrix @m, -> $w, $n, $nw { $w + $n } }
# Define 3 infinite sequences of Pascal matrices.
constant upper-tri = [1], &madd-w-nw ... *;
constant lower-tri = [1], &madd-n-nw ... *;
constant symmetric = [1], &madd-w-n ... *;
show_m upper-tri[4];
show_m lower-tri[4];
show_m symmetric[4];
sub show_m (@m) {
my \n = @m.shape[0];
for ^n X ^n -> (\i, \j) {
print @m[i;j].fmt("%{1+max(@m).chars}d");
print "\n" if j+1 eq n;
}
say '';
} |
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
| #FOCAL | FOCAL | 1.1 S OLD(1)=1; T %4.0, 1, !
1.2 F N=1,10; D 2
1.3 Q
2.1 S NEW(1)=1
2.2 F X=1,N; S NEW(X+1)=OLD(X)+OLD(X+1)
2.3 F X=1,N+1; D 3
2.4 T !
3.1 S OLD(X)=NEW(X)
3.2 T %4.0, OLD(X) |
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.
| #Oforth | Oforth | "3 4 2 * 1 5 - 2 3 ^ ^ / +" eval println |
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.
| #ooRexx | ooRexx | /* ooRexx *************************************************************
* 10.11.2012 Walter Pachl translated from PL/I via REXX
**********************************************************************/
fid='rpl.txt'
ex=linein(fid)
Say 'Input:' ex
/* ex=' 3 4 2 * 1 5 - 2 3 ^ ^ / +' */
Numeric Digits 15
expr=''
st=.circularqueue~new(100)
Say 'Stack contents:'
do While ex<>''
Parse Var ex ch +1 ex
expr=expr||ch;
if ch<>' ' then do
If pos(ch,'0123456789')>0 Then /* a digit goes onto stack */
st~push(ch)
Else Do /* an operator */
op=st~pull /* get top element */
select /* and modify the (now) top el*/
when ch='+' Then st~push(st~pull + op)
when ch='-' Then st~push(st~pull - op)
when ch='*' Then st~push(st~pull * op)
when ch='/' Then st~push(st~pull / op)
when ch='^' Then st~push(st~pull ** op)
end;
Say st~string(' ','L') /* show stack in LIFO order */
end
end
end
Say 'The reverse polish expression = 'expr
Say 'The evaluated expression = 'st~pull |
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
| #Bracmat | Bracmat | ( ( palindrome
= a
. @(!arg:(%?a&utf$!a) ?arg !a)
& palindrome$!arg
| utf$!arg
)
& ( desep
= x
. @(!arg:?x (" "|"-"|",") ?arg)
& !x desep$!arg
| !arg
)
& "In girum imus nocte et consumimur igni"
"Я иду с мечем, судия"
"The quick brown fox"
"tregða, gón, reiði - er nóg að gert"
"人人為我,我為人人"
"가련하시다 사장집 아들딸들아 집장사 다시 하련가"
: ?candidates
& whl
' ( !candidates:%?candidate ?candidates
& out
$ ( !candidate
is
( palindrome$(low$(str$(desep$!candidate)))
& indeed
| not
)
a
palindrome
)
)
&
); |
http://rosettacode.org/wiki/Palindromic_gapful_numbers | Palindromic gapful numbers | Palindromic gapful numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the
first and last digit are known as gapful numbers.
Evenly divisible means divisible with no remainder.
All one─ and two─digit numbers have this property and are trivially excluded. Only
numbers ≥ 100 will be considered for this Rosetta Code task.
Example
1037 is a gapful number because it is evenly divisible by the
number 17 which is formed by the first and last decimal digits
of 1037.
A palindromic number is (for this task, a positive integer expressed in base ten), when the number is
reversed, is the same as the original number.
Task
Show (nine sets) the first 20 palindromic gapful numbers that end with:
the digit 1
the digit 2
the digit 3
the digit 4
the digit 5
the digit 6
the digit 7
the digit 8
the digit 9
Show (nine sets, like above) of palindromic gapful numbers:
the last 15 palindromic gapful numbers (out of 100)
the last 10 palindromic gapful numbers (out of 1,000) {optional}
For other ways of expressing the (above) requirements, see the discussion page.
Note
All palindromic gapful numbers are divisible by eleven.
Related tasks
palindrome detection.
gapful numbers.
Also see
The OEIS entry: A108343 gapful numbers.
| #zkl | zkl | // 10,True --> 101,111,121,131,141,151,161,171,181,191,202, ..
// 10,False --> 1001,1111,1221,1331,1441,1551,1661,1771,1881,..
fcn createPalindromeW(start,oddLength){ //--> iterator
[start..].tweak('wrap(z){
p,n := z,z;
if(oddLength) n/=10;
while(n>0){ p,n = p*10 + (n%10), n/10; }
p
})
}
fcn palindromicGapfulW(endsWith){ //--> iterator
po,pe := createPalindromeW(10,True), createPalindromeW(10,False);
div:=endsWith*10 + endsWith;
Walker.zero().tweak('wrap{
p:=( if(pe.peek()<po.peek()) pe.next() else po.next() );
if(p%10==endsWith and (p%div)==0) p else Void.Skip
})
} |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Wren | Wren | import "/seq" for Stack
import "/pattern" for Pattern
/* To find out the precedence, we take the index of the
token in the OPS string and divide by 2 (rounding down).
This will give us: 0, 0, 1, 1, 2 */
var ops = "-+/*^"
var infixToPostfix = Fn.new { |infix|
var sb = ""
var s = Stack.new()
var p = Pattern.new("+1/s")
for (token in p.splitAll(infix)) {
var c = token[0]
var idx = ops.indexOf(c)
// check for operator
if (idx != - 1) {
if (s.isEmpty) {
s.push(idx)
} else {
while (!s.isEmpty) {
var prec2 = (s.peek()/2).floor
var prec1 = (idx/2).floor
if (prec2 > prec1 || (prec2 == prec1 && c != "^")) {
sb = sb + ops[s.pop()] + " "
} else break
}
s.push(idx)
}
} else if (c == "(") {
s.push(-2) // -2 stands for "("
} else if (c == ")") {
// until "(" on stack, pop operators.
while (s.peek() != -2) sb = sb + ops[s.pop()] + " "
s.pop()
} else {
sb = sb + token + " "
}
}
while (!s.isEmpty) sb = sb + ops[s.pop()] + " "
return sb
}
var es = [
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )"
]
for (e in es) {
System.print("Infix : %(e)")
System.print("Postfix : %(infixToPostfix.call(e))\n")
} |
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
| #Haskell | Haskell | import Data.Char (toLower)
import Data.List ((\\))
pangram :: String -> Bool
pangram = null . (['a' .. 'z'] \\) . map toLower
main = print $ pangram "How razorback-jumping frogs can level six piqued gymnasts!" |
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
| #HicEst | HicEst | PangramBrokenAt("This is a Pangram.") ! => 2 (b is missing)
PangramBrokenAt("The quick Brown Fox jumps over the Lazy Dog") ! => 0 (OK)
FUNCTION PangramBrokenAt(string)
CHARACTER string, Alfabet="abcdefghijklmnopqrstuvwxyz"
PangramBrokenAt = INDEX(Alfabet, string, 64)
! option 64: verify = 1st letter of string not in Alfabet
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.
| #REXX | REXX | /*REXX program generates and displays three forms of an NxN Pascal matrix. */
numeric digits 50 /*be able to calculate huge factorials.*/
parse arg N . /*obtain the optional matrix size (N).*/
if N=='' | N=="," then N= 5 /*Not specified? Then use the default.*/
call show N, upp(N), 'Pascal upper triangular matrix'
call show N, low(N), 'Pascal lower triangular matrix'
call show N, sym(N), 'Pascal symmetric matrix'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
upp: procedure; parse arg N; $= /*gen Pascal upper triangular matrix. */
do i=0 for N; do j=0 for N; $=$ comb(j, i); end; end; return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
low: procedure; parse arg N; $= /*gen Pascal lower triangular matrix. */
do i=0 for N; do j=0 for N; $=$ comb(i, j); end; end; return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
sym: procedure; parse arg N; $= /*generate Pascal symmetric matrix. */
do i=0 for N; do j=0 for N; $=$ comb(i+j, i); end; end; return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; parse arg x; !=1; do j=2 to x; != !*j; end; return !
/*──────────────────────────────────────────────────────────────────────────────────────*/
comb: procedure; parse arg x,y; if x=y then return 1 /* {=} case.*/
if y>x then return 0 /* {>} case.*/
if x-y<y then y= x-y; _= 1; do j=x-y+1 to x; _= _*j; end; return _ / !(y)
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: procedure; parse arg s,@; w=0; #=0 /*get args. */
do x=1 for s**2; w= max(w, 1 + length( word(@,x) ) ); end
say; say center( arg(3), 50, '─') /*show title*/
do r=1 for s; if r==1 then $= '[[' /*row 1 */
else $= ' [' /*rows 2 N*/
do c=1 for s; #= #+1; e= (c==s) /*e ≡ "end".*/
$=$ || right( word(@, #), w) || left(',', \e) || left("]", e)
end /*c*/ /* [↑] row.*/
say $ || left(',', r\==s)left("]", r==s) /*show row. */
end /*r*/
return |
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
| #Forth | Forth | : init ( n -- )
here swap cells erase 1 here ! ;
: .line ( n -- )
cr here swap 0 do dup @ . cell+ loop drop ;
: next ( n -- )
here swap 1- cells here + do
i @ i cell+ +!
-1 cells +loop ;
: pascal ( n -- )
dup init 1 .line
1 ?do i next i 1+ .line loop ; |
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.
| #PARI.2FGP | PARI/GP | estack = [];
epush(x) = {
estack = vector(#estack + 1, i, if(i <= #estack, estack[i], x));
return(#estack);
};
epop() = {
local(val = estack[#estack]);
estack = vector(#estack - 1, i, estack[i]);
return(val);
};
registerRPNToken(t) = {
local(o1, o2);
if(type(t) == "t_STR",
if(t == "+", o2 = epop(); o1 = epop(); epush(o1 + o2),
if(t == "-", o2 = epop(); o1 = epop(); epush(o1 - o2),
if(t == "*", o2 = epop(); o1 = epop(); epush(o1 * o2),
if(t == "/", o2 = epop(); o1 = epop(); epush(o1 / o2),
if(t == "%", o2 = epop(); o1 = epop(); epush(o1 % o2),
if(t == "^", o2 = epop(); o1 = epop(); epush(o1 ^ o2)
)))))),
if(type(t) == "t_INT" || type(t) == "t_REAL" || type(t) == "t_FRAC",
epush(t))
);
print(estack);
};
parseRPN(s) = {
estack = [];
for(i = 1, #s, registerRPNToken(s[i]));
if(#estack > 1, error("Malformed postfix expression."));
return(estack[1]);
};
parseRPN([3, 4, 2, "*", 1, 5, "-", 2, 3, "^", "^", "/", "+"]); \\ Our input expression |
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
| #Burlesque | Burlesque |
zz{ri}f[^^<-==
|
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #Xojo | Xojo |
Function ShuntingYard(strInfix As String) As String
Dim i as Integer
Dim token, tokenArray() As String
Dim stack(), queue() As Variant
Dim discard As String
Dim op1, op2 As String
Dim Left_Brackets, Right_Brackets As Integer
Dim output As String
Dim dbl_output As Double
Left_Brackets = CountFields(strInfix, "(")
Right_Brackets = CountFields(strInfix, ")")
If Left_Brackets = Right_Brackets Then
'Get tokens
tokenArray = Split(strInfix," ")
'Initialize array (removed later)
ReDim stack(1)
ReDim queue(1)
'Loop over tokens
For i = 0 to tokenArray.Ubound
'i = i + 1
If i > UBound(tokenArray) Then
Exit For
Else
token = tokenArray(i ) 'i-1 due to Split returning a Base 0
End If
If token = "" Then
Exit For
End If
Dim stackString As String
Dim queuString As String
for m as Integer = 0 to stack.Ubound
stackString = stackString + " " + stack(m)
Next
for m as Integer = 0 to queue.Ubound
queuString = queuString + " " + queue(m)
Next
MsgBox(Str(i) + " " + token + " " + stackString + " " + queuString)
'Window1.txtQueu.Text = Window1.txtQueu.Text + Str(i) + " " + token + " " + stackString + " " + queuString + EndOfLIne
' If-loop over tokens (either brackets, operators, or numbers)
If token = "(" Then
stack.Append(token)
ElseIf token = ")" Then
While stack(stack.Ubound) <> "("
queue.Append(stack.pop)
Wend
discard = stack.Pop 'discard "("
ElseIf isOperator(token) Then
op1 = token
//Do While (isOperator(Peek(stack)))
While isOperator( stack(stack.Ubound) ) = True
op2 = stack(stack.Ubound)
If op2 <> "^" And precedence(op1) = precedence(op2) Then
'"^" is the only right-associative operator
queue.Append(stack.pop)
ElseIf precedence(op1) < precedence(op2) Then
queue.Append(stack.Pop)
Else
Exit While
End If
Wend
//Loop
stack.Append(op1)
Else 'number
'actually, wrong operator could end up here, like say %
'If the token is a number, then add it to the output queue.
queue.Append(CStr(token))
End If
Next
for i = 0 to queue.Ubound
output = output +queue(i) + " "
next
for i = stack.Ubound DownTo 0
output = output + stack(i)+" "
next
While InStr(output, " ") <> 0
output = ReplaceAll(output," "," ")
Wend
output = Trim(output)
Return output
Else
MsgBox("Syntax Error!" + EndOfLine + "Count left brackets: " + Str(Left_Brackets) + EndOfLine +"Count right brackets: " + Str(Right_Brackets))
End If
End Function
Function isOperator(op As String) As Boolean
If InStr("+-*/^", op) <> 0 and Len(op) = 1 Then
Return True
End If
End Function
Function precedence(op As String) As Integer
If isOperator(op) = True Then
If op = "+" or op = "-" Then
Return 2
ElseIf op = "/" or op = "*" Then
Return 3
ElseIf op = "^" Then
Return 4
End If
End If
End Function |
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm | Parsing/Shunting-yard algorithm | Task
Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.
Assume an input of a correct, space separated, string of tokens representing an infix expression
Generate a space separated output string representing the RPN
Test with the input string:
3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
print and display the output here.
Operator precedence is given in this table:
operator
precedence
associativity
operation
^
4
right
exponentiation
*
3
left
multiplication
/
3
left
division
+
2
left
addition
-
2
left
subtraction
Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
Note
The handling of functions and arguments is not required.
See also
Parsing/RPN calculator algorithm for a method of calculating a final value from this output RPN expression.
Parsing/RPN to infix conversion.
| #zkl | zkl | var input="3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
var opa=Dictionary("^",T(4,True), "*",T(3,False), // op:(prec,rAssoc)
"/",T(3,False), "+",T(2,False), "-",T(2,False),
);
"infix: ".println(input);
"postfix:".println(parseInfix(input));
fcn parseInfix(e){
stack:=List(); // holds operators and left parenthesis
rpn:="";
foreach tok in (e.split(" ")){
switch(tok){
case("("){ stack.append(tok) } // push "(" to stack
case(")"){
while(True){ // pop item ("(" or operator) from stack
op:=stack.pop();
if(op=="(") break; // discard "("
rpn+=" " + op; // add operator to result
}
}
else{ // default
o1:=opa.find(tok); // op or Void
if(o1){ // token is an operator
while(stack){
// consider top item on stack
op:=stack[-1]; o2:=opa.find(op);
if(not o2 or o1[0]>o2[0] or
(o1[0]==o2[0] and o1[1])) break;
// top item is an operator that needs to come off
stack.pop();
rpn+=" " + op; // add it to result
}
// push operator (the new one) to stack
stack.append(tok);
}else // token is an operand
rpn+=(rpn and " " or "") + tok; // add operand to result
}
} // switch
display(tok,rpn,stack);
} // foreach
// drain stack to result
rpn + stack.reverse().concat(" ");
}
fcn display(tok,rpn,stack){
"Token|".println(tok);
"Stack|".println(stack.concat());
"Queue|".println(rpn);
println();
} |
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
| #Icon_and_Unicon | Icon and Unicon | procedure panagram(s) #: return s if s is a panagram and fail otherwise
if (map(s) ** &lcase) === &lcase then return s
end |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Io | Io | Sequence isPangram := method(
letters := " " repeated(26)
ia := "a" at(0)
foreach(ichar,
if(ichar isLetter,
letters atPut((ichar asLowercase) - ia, ichar)
)
)
letters contains(" " at(0)) not // true only if no " " in letters
)
"The quick brown fox jumps over the lazy dog." isPangram println // --> true
"The quick brown fox jumped over the lazy dog." isPangram println // --> false
"ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ" isPangram println // --> true |
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.
| #Ring | Ring |
# Project : Pascal matrix generation
load "stdlib.ring"
res = newlist(5,5)
see "=== Pascal upper matrix ===" + nl
result = pascalupper(5)
showarray(result)
see nl + "=== Pascal lower matrix ===" + nl
result = pascallower(5)
showarray(result)
see nl + "=== Pascal symmetrical matrix ===" + nl
result = pascalsymmetric(5)
showarray(result)
func pascalupper(n)
for m=1 to n
for p=1 to n
res[m][p] = 0
next
next
for p=1 to n
res[1][p] = 1
next
for i=2 to n
for j=2 to i
res[j][i] = res[j][i-1]+res[j-1][i-1]
end
end
return res
func pascallower(n)
for m=1 to n
for p=1 to n
res[m][p] = 0
next
next
for p=1 to n
res[p][1] = 1
next
for i=2 to n
for j=2 to i
res[i][j] = res[i-1][j]+res[i-1][j-1]
next
next
return res
func pascalsymmetric(n)
for m=1 to n
for p=1 to n
res[m][p] = 0
next
next
for p=1 to n
res[p][1] = 1
res[1][p] = 1
next
for i=2 to n
for j = 2 to n
res[i][j] = res[i-1][j]+res[i][j-1]
next
next
return res
func showarray(result)
for n=1 to 5
for m=1 to 5
see "" + result[n][m] + " "
next
see nl
next
|
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.
| #Ruby | Ruby | #Upper, lower, and symetric Pascal Matrix - Nigel Galloway: May 3rd., 21015
require 'pp'
ng = (g = 0..4).collect{[]}
g.each{|i| g.each{|j| ng[i][j] = i==0 ? 1 : j<i ? 0 : ng[i-1][j-1]+ng[i][j-1]}}
pp ng; puts
g.each{|i| g.each{|j| ng[i][j] = j==0 ? 1 : i<j ? 0 : ng[i-1][j-1]+ng[i-1][j]}}
pp ng; puts
g.each{|i| g.each{|j| ng[i][j] = (i==0 or j==0) ? 1 : ng[i-1][j ]+ng[i][j-1]}}
pp ng |
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
| #Fortran | Fortran | PROGRAM Pascals_Triangle
CALL Print_Triangle(8)
END PROGRAM Pascals_Triangle
SUBROUTINE Print_Triangle(n)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: c, i, j, k, spaces
DO i = 0, n-1
c = 1
spaces = 3 * (n - 1 - i)
DO j = 1, spaces
WRITE(*,"(A)", ADVANCE="NO") " "
END DO
DO k = 0, i
WRITE(*,"(I6)", ADVANCE="NO") c
c = c * (i - k) / (k + 1)
END DO
WRITE(*,*)
END DO
END SUBROUTINE Print_Triangle |
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.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
my $number = '[+-]?(?:\.\d+|\d+(?:\.\d*)?)';
my $operator = '[-+*/^]';
my @tests = ('3 4 2 * 1 5 - 2 3 ^ ^ / +');
for (@tests) {
while (
s/ \s* ((?<left>$number)) # 1st operand
\s+ ((?<right>$number)) # 2nd operand
\s+ ((?<op>$operator)) # operator
(?:\s+|$) # more to parse, or done?
/
' '.evaluate().' ' # substitute results of evaluation
/ex
) {}
say;
}
sub evaluate {
(my $a = "($+{left})$+{op}($+{right})") =~ s/\^/**/;
say $a;
eval $a;
} |
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
| #C | C | #include <string.h>
int palindrome(const char *s)
{
int i,l;
l = strlen(s);
for(i=0; i<l/2; i++)
{
if ( s[i] != s[l-i-1] ) return 0;
}
return 1;
} |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Ioke | Ioke | Text isPangram? = method(
letters = "abcdefghijklmnopqrstuvwxyz" chars
text = self lower chars
letters map(x, text include?(x)) reduce(&&)
) |
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
| #J | J | require 'strings'
isPangram=: (a. {~ 97+i.26) */@e. tolower |
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.
| #Scala | Scala | //Pascal Matrix Generator
object pascal{
def main( args:Array[String] ){
println("Enter the order of matrix")
val n = scala.io.StdIn.readInt()
var F = new Factorial()
var mx = Array.ofDim[Int](n,n)
for( i <- 0 to (n-1); j <- 0 to (n-1) ){
if( i>=j ){ //iCj
mx(i)(j) = F.fact(i) / ( ( F.fact(j) )*( F.fact(i-j) ) )
}
}
println("iCj:")
for( i <- 0 to (n-1) ){ //iCj print
for( j <- 0 to (n-1) ){
print( mx(i)(j)+" " )
}
println("")
}
println("jCi:")
for( i <- 0 to (n-1) ){ //jCi print
for( j <- 0 to (n-1) ){
print( mx(j)(i)+" " )
}
println("")
}
//(i+j)C j
for( i <- 0 to (n-1); j <- 0 to (n-1) ){
mx(i)(j) = F.fact(i+j) / ( ( F.fact(j) )*( F.fact(i) ) )
}
//print (i+j)Cj
println("(i+j)Cj:")
for( i <- 0 to (n-1) ){
for( j <- 0 to (n-1) ){
print( mx(i)(j)+" " )
}
println("")
}
}
}
class Factorial(){
def fact( a:Int ): Int = {
var b:Int = 1
for( i <- 2 to a ){
b = b*i
}
return b
}
}
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub pascalTriangle(n As UInteger)
If n = 0 Then Return
Dim prevRow(1 To n) As UInteger
Dim currRow(1 To n) As UInteger
Dim start(1 To n) As UInteger ''stores starting column for each row
start(n) = 1
For i As Integer = n - 1 To 1 Step -1
start(i) = start(i + 1) + 3
Next
prevRow(1) = 1
Print Tab(start(1));
Print 1U
For i As UInteger = 2 To n
For j As UInteger = 1 To i
If j = 1 Then
Print Tab(start(i)); "1";
currRow(1) = 1
ElseIf j = i Then
Print " 1"
currRow(i) = 1
Else
currRow(j) = prevRow(j - 1) + prevRow(j)
Print Using "######"; currRow(j); " ";
End If
Next j
For j As UInteger = 1 To i
prevRow(j) = currRow(j)
Next j
Next i
End Sub
pascalTriangle(14)
Print
Print "Press any key to quit"
Sleep |
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.
| #Phix | Phix | with javascript_semantics
procedure evalRPN(string s)
sequence stack = {},
ops = split(s)
for i=1 to length(ops) do
string op = ops[i]
switch op
case "+": stack[-2] = stack[-2]+stack[-1]; stack = stack[1..-2]
case "-": stack[-2] = stack[-2]-stack[-1]; stack = stack[1..-2]
case "*": stack[-2] = stack[-2]*stack[-1]; stack = stack[1..-2]
case "/": stack[-2] = stack[-2]/stack[-1]; stack = stack[1..-2]
case "^": stack[-2] = power(stack[-2],stack[-1]); stack = stack[1..-2]
default : stack = append(stack,scanf(op,"%d")[1][1])
end switch
?{op,stack}
end for
end procedure
evalRPN("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
| #C.23 | C# | using System;
class Program
{
static string Reverse(string value)
{
char[] chars = value.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
static bool IsPalindrome(string value)
{
return value == Reverse(value);
}
static void Main(string[] args)
{
Console.WriteLine(IsPalindrome("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
| #Java | Java | public class Pangram {
public static boolean isPangram(String test){
for (char a = 'A'; a <= 'Z'; a++)
if ((test.indexOf(a) < 0) && (test.indexOf((char)(a + 32)) < 0))
return false;
return true;
}
public static void main(String[] args){
System.out.println(isPangram("the quick brown fox jumps over the lazy dog"));//true
System.out.println(isPangram("the quick brown fox jumped over the lazy dog"));//false, no s
System.out.println(isPangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));//true
System.out.println(isPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ"));//false, no r
System.out.println(isPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ"));//false, no m
System.out.println(isPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ"));//true
System.out.println(isPangram(""));//false
}
} |
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.
| #Scheme | Scheme | (import (srfi 25))
(define-syntax dotimes
(syntax-rules ()
((_ (i n) body ...)
(do ((i 0 (+ i 1)))
((>= i n))
body ...))))
(define (pascal-upper n)
(let ((p (make-array (shape 0 n 0 n) 0)))
(dotimes (i n)
(array-set! p 0 i 1))
(dotimes (i (- n 1))
(dotimes (j (- n 1))
(array-set! p (+ 1 i) (+ 1 j)
(+ (array-ref p i j)
(array-ref p (+ 1 i) j)))))
p))
(define (pascal-lower n)
(let ((p (make-array (shape 0 n 0 n) 0)))
(dotimes (i n)
(array-set! p i 0 1))
(dotimes (i (- n 1))
(dotimes (j (- n 1))
(array-set! p (+ 1 i) (+ 1 j)
(+ (array-ref p i j)
(array-ref p i (+ 1 j))))))
p))
(define (pascal-symmetric n)
(let ((p (make-array (shape 0 n 0 n) 0)))
(dotimes (i n)
(array-set! p i 0 1)
(array-set! p 0 i 1))
(dotimes (i (- n 1))
(dotimes (j (- n 1))
(array-set! p (+ 1 i) (+ 1 j)
(+ (array-ref p (+ 1 i) j)
(array-ref p i (+ 1 j))))))
p))
(define (print-array a)
(let ((r (array-end a 0))
(c (array-end a 1)))
(dotimes (row (- r 1))
(dotimes (col (- c 1))
(display (array-ref a row col))
(display #\space))
(newline)))) |
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
| #Frink | Frink |
pascal[rows] :=
{
widest = length[toString[binomial[rows-1, (rows-1) div 2]]]
for row = 0 to rows-1
{
line = repeat[" ", round[(rows-row)* (widest+1)/2]]
for col = 0 to row
line = line + padRight[binomial[row, col], widest+1, " "]
println[line]
}
}
pascal[10]
|
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.
| #PHP | PHP |
<?php
function rpn($postFix){
$stack = Array();
echo "Input\tOperation\tStack\tafter\n" ;
$token = explode(" ", trim($postFix));
$count = count($token);
for($i = 0 ; $i<$count;$i++)
{
echo $token[$i] ." \t";
$tokenNum = "";
if (is_numeric($token[$i])) {
echo "Push";
array_push($stack,$token[$i]);
}
else
{
echo "Operate";
$secondOperand = end($stack);
array_pop($stack);
$firstOperand = end($stack);
array_pop($stack);
if ($token[$i] == "*")
array_push($stack,$firstOperand * $secondOperand);
else if ($token[$i] == "/")
array_push($stack,$firstOperand / $secondOperand);
else if ($token[$i] == "-")
array_push($stack,$firstOperand - $secondOperand);
else if ($token[$i] == "+")
array_push($stack,$firstOperand + $secondOperand);
else if ($token[$i] == "^")
array_push($stack,pow($firstOperand,$secondOperand));
else {
die("Error");
}
}
echo "\t\t" . implode(" ", $stack) . "\n";
}
return end($stack);
}
echo "Compute Value: " . 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
| #C.2B.2B | C++ | #include <string>
#include <algorithm>
bool is_palindrome(std::string const& s)
{
return std::equal(s.begin(), s.end(), s.rbegin());
} |
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
| #JavaScript | JavaScript | function isPangram(s) {
var letters = "zqxjkvbpygfwmucldrhsnioate"
// sorted by frequency ascending (http://en.wikipedia.org/wiki/Letter_frequency)
s = s.toLowerCase().replace(/[^a-z]/g,'')
for (var i = 0; i < 26; i++)
if (s.indexOf(letters[i]) < 0) return false
return true
}
console.log(isPangram("is this a pangram")) // false
console.log(isPangram("The quick brown fox jumps over the lazy dog")) // true |
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #jq | jq | def is_pangram:
explode
| map( if 65 <= . and . <= 90 then . + 32 # uppercase
elif 97 <= . and . <= 122 then . # lowercase
else empty
end )
| unique
| length == 26;
# Example:
"The quick brown fox jumps over the lazy dog" | is_pangram |
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.
| #Sidef | Sidef | func grow_matrix(matrix, callback) {
var m = matrix
var s = m.len
m[s][0] = callback(0, m[s-1][0], 0)
m[0][s] = callback(m[0][s-1], 0, 0)
{|i| m[i+1][s] = callback(m[i+1][s-1], m[i][s], m[i][s-1])} * (s-1)
{|i| m[s][i+1] = callback(m[s][i], m[s-1][i+1], m[s-1][i])} * (s)
return m
}
func transpose(matrix) {
matrix[0].range.map{|i| matrix.map{_[i]} }
}
func madd_n_nw(m) { grow_matrix(m, ->(_, n, nw) { n + nw }) }
func madd_w_nw(m) { grow_matrix(m, ->(w, _, nw) { w + nw }) }
func madd_w_n(m) { grow_matrix(m, ->(w, n, _) { w + n }) }
var functions = [madd_n_nw, madd_w_nw, madd_w_n].map { |f|
func(n) {
var r = [[1]]
{ f(r) } * n
transpose(r)
}
}
functions.map { |f|
f(4).map { .map{ '%2s' % _ }.join(' ') }.join("\n")
}.join("\n\n").say |
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
| #FunL | FunL | import lists.zip
def
pascal( 1 ) = [1]
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [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.
| #PicoLisp | PicoLisp | (de rpnCalculator (Str)
(let (^ ** Stack) # Define '^' from the built-in '**'
(prinl "Token Stack")
(for Token (str Str "*+-/\^")
(if (num? Token)
(push 'Stack @)
(set (cdr Stack)
((intern Token) (cadr Stack) (pop 'Stack)) ) )
(prin Token)
(space 6)
(println Stack) )
(println (car Stack)) ) ) |
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.
| #PL.2FI | PL/I | Calculator: procedure options (main); /* 14 Sept. 2012 */
declare expression character (100) varying initial ('');
declare ch character (1);
declare (stack controlled, operand) float (18);
declare in file input;
open file (in) title ('/CALCULAT.DAT,type(text),recsize(100)');
on endfile (in) go to done;
put ('Stack contents:');
main_loop:
do forever;
get file (in) edit (ch) (a(1));
expression = expression || ch;
if ch = ' ' then iterate;
select (ch);
when ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
do; allocate stack; stack = ch; iterate main_loop; end;
when ('+') do; operand = stack; free stack; stack = stack + operand; end;
when ('-') do; operand = stack; free stack; stack = stack - operand; end;
when ('*') do; operand = stack; free stack; stack = stack * operand; end;
when ('/') do; operand = stack; free stack; stack = stack / operand; end;
when ('^') do; operand = stack; free stack; stack = stack ** operand; end;
end;
call show_stack;
end;
done:
put skip list ('The reverse polish expression = ' || expression);
put skip list ('The evaluated expression = ' || stack);
end Calculator; |
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
| #Clojure | Clojure | (defn palindrome? [s]
(= s (clojure.string/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
| #Julia | Julia | function makepangramchecker(alphabet)
alphabet = Set(uppercase.(alphabet))
function ispangram(s)
lengthcheck = length(s) ≥ length(alphabet)
return lengthcheck && all(c in uppercase(s) for c in alphabet)
end
return ispangram
end
const tests = ["Pack my box with five dozen liquor jugs.",
"The quick brown fox jumps over a lazy dog.",
"The quick brown fox jumps\u2323over the lazy dog.",
"The five boxing wizards jump quickly.",
"This sentence contains A-Z but not the whole alphabet."]
is_english_pangram = makepangramchecker('a':'z')
for s in tests
println("The sentence \"", s, "\" is ", is_english_pangram(s) ? "" : "not ", "a pangram.")
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
| #K | K | lcase : _ci 97+!26
ucase : _ci 65+!26
tolower : {@[x;p;:;lcase@n@p:&26>n:ucase?/:x]}
panagram: {&/lcase _lin tolower x} |
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.
| #Stata | Stata | mata
function pascal1(n) {
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
}
function pascal2(n) {
a = I(n)
a[.,1] = J(n,1,1)
for (i=3; i<=n; i++) {
a[i,2..i-1] = a[i-1,2..i-1]+a[i-1,1..i-2]
}
return(a)
}
function pascal3(n) {
a = J(n,n,0)
for (i=1; i<n; i++) {
a[i+1,i] = i
}
s = p = I(n)
k = 1
for (i=0; i<n; i++) {
p = p*a/k++
s = s+p
}
return(s)
}
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Pascal := function(n)
local i, v;
v := [1];
for i in [1 .. n] do
Display(v);
v := Concatenation([0], v) + Concatenation(v, [0]);
od;
end;
Pascal(9);
# [ 1 ]
# [ 1, 1 ]
# [ 1, 2, 1 ]
# [ 1, 3, 3, 1 ]
# [ 1, 4, 6, 4, 1 ]
# [ 1, 5, 10, 10, 5, 1 ]
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 8, 28, 56, 70, 56, 28, 8, 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.
| #PL.2FSQL | PL/SQL | CREATE OR REPLACE FUNCTION rpn_calc(str VARCHAR2) RETURN NUMBER AS
TYPE num_aa IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
TYPE num_stack IS RECORD (a num_aa, top PLS_INTEGER DEFAULT 0);
ns num_stack;
pos1 INTEGER := 1;
pos2 INTEGER;
token VARCHAR2(100);
op2 NUMBER;
PROCEDURE push(s IN OUT NOCOPY num_stack, x NUMBER) IS
BEGIN
s.top := s.top + 1;
s.a(s.top) := x;
END;
FUNCTION pop(s IN OUT NOCOPY num_stack) RETURN NUMBER IS
x NUMBER;
BEGIN
x := s.a(s.top);
s.top := s.top - 1;
RETURN x;
END;
PROCEDURE print_stack(s num_stack) IS -- for debugging only; remove from final version
ps VARCHAR2(4000);
BEGIN
FOR i IN 1 .. s.top LOOP
ps := ps || s.a(i) || ' ';
END LOOP;
DBMS_OUTPUT.put_line('Stack: ' || RTRIM(ps));
END;
BEGIN
WHILE pos1 <= LENGTH(str) LOOP
pos2 := INSTR(str || ' ', ' ', pos1);
token := SUBSTR(str, pos1, pos2 - pos1);
pos1 := pos2 + 1;
CASE token
WHEN '+' THEN push(ns, pop(ns) + pop(ns));
WHEN '-' THEN op2 := pop(ns); push(ns, pop(ns) - op2);
WHEN '*' THEN push(ns, pop(ns) * pop(ns));
WHEN '/' THEN op2 := pop(ns); push(ns, pop(ns) / op2);
WHEN '^' THEN op2 := pop(ns); push(ns, POWER(pop(ns), op2));
ELSE push(ns, TO_NUMBER(token));
END CASE;
print_stack(ns); -- for debugging purposes only
END LOOP;
RETURN pop(ns);
END rpn_calc;
/ |
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
| #CLU | CLU | % Reverse a string
str_reverse = proc (s: string) returns (string)
chs: array[char] := array[char]$predict(0, string$size(s))
for c: char in string$chars(s) do
array[char]$addl(chs, c)
end
return (string$ac2s(chs))
end str_reverse
% 'Normalize' a string (remove everything but letters and make uppercase)
normalize = proc (s: string) returns (string)
chs: array[char] := array[char]$predict(0, string$size(s))
for c: char in string$chars(s) do
if c>='a' cand c<='z' then
c := char$i2c(char$c2i(c) - 32)
end
if c>='A' cand c<='Z' then
array[char]$addh(chs, c)
end
end
return (string$ac2s(chs))
end normalize
% Check if a string is an exact palindrome
palindrome = proc (s: string) returns (bool)
return (s = str_reverse(s))
end palindrome
% Check if a string is an inexact palindrome
inexact_palindrome = proc (s: string) returns (bool)
return (palindrome(normalize(s)))
end inexact_palindrome
% Test cases
start_up = proc ()
po: stream := stream$primary_output()
tests: array[string] := array[string]$[
"rotor", "racecar", "RACEcar", "level", "rosetta",
"A man, a plan, a canal: Panama",
"Egad, a base tone denotes a bad age",
"This is not a palindrome"
]
for test: string in array[string]$elements(tests) do
stream$puts(po, "\"" || test || "\": ")
if palindrome(test) then
stream$putl(po, "exact palindrome")
elseif inexact_palindrome(test) then
stream$putl(po, "inexact palindrome")
else
stream$putl(po, "not a palindrome")
end
end
end start_up |
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
| #Kotlin | Kotlin | // version 1.0.6
fun isPangram(s: String): Boolean {
if (s.length < 26) return false
val t = s.toLowerCase()
for (c in 'a' .. 'z')
if (c !in t) return false
return true
}
fun main(args: Array<String>) {
val candidates = arrayOf(
"The quick brown fox jumps over the lazy dog",
"New job: fix Mr. Gluck's hazy TV, PDQ!",
"A very bad quack might jinx zippy fowls",
"A very mad quack might jinx zippy fowls" // no 'b' now!
)
for (candidate in candidates)
println("'$candidate' is ${if (isPangram(candidate)) "a" else "not a"} pangram")
} |
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.
| #Tcl | Tcl |
package require math
namespace eval pascal {
proc upper {n} {
for {set i 0} {$i < $n} {incr i} {
for {set j 0} {$j < $n} {incr j} {
puts -nonewline \t[::math::choose $j $i]
}
puts ""
}
}
proc lower {n} {
for {set i 0} {$i < $n} {incr i} {
for {set j 0} {$j < $n} {incr j} {
puts -nonewline \t[::math::choose $i $j]
}
puts ""
}
}
proc symmetric {n} {
for {set i 0} {$i < $n} {incr i} {
for {set j 0} {$j < $n} {incr j} {
puts -nonewline \t[::math::choose [expr {$i+$j}] $i]
}
puts ""
}
}
}
foreach type {upper lower symmetric} {
puts "\n* $type"
pascal::$type 5
}
|
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
| #GAP | GAP | Pascal := function(n)
local i, v;
v := [1];
for i in [1 .. n] do
Display(v);
v := Concatenation([0], v) + Concatenation(v, [0]);
od;
end;
Pascal(9);
# [ 1 ]
# [ 1, 1 ]
# [ 1, 2, 1 ]
# [ 1, 3, 3, 1 ]
# [ 1, 4, 6, 4, 1 ]
# [ 1, 5, 10, 10, 5, 1 ]
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 8, 28, 56, 70, 56, 28, 8, 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.
| #PowerShell | PowerShell |
function Invoke-Rpn
{
<#
.SYNOPSIS
A stack-based evaluator for an expression in reverse Polish notation.
.DESCRIPTION
A stack-based evaluator for an expression in reverse Polish notation.
All methods in the Math and Decimal classes are available.
.PARAMETER Expression
A space separated, string of tokens.
.PARAMETER DisplayState
This switch shows the changes in the stack as each individual token is processed as a table.
.EXAMPLE
Invoke-Rpn -Expression "3 4 Max"
.EXAMPLE
Invoke-Rpn -Expression "3 4 Log2"
.EXAMPLE
Invoke-Rpn -Expression "3 4 2 * 1 5 - 2 3 ^ ^ / +"
.EXAMPLE
Invoke-Rpn -Expression "3 4 2 * 1 5 - 2 3 ^ ^ / +" -DisplayState
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)]
[AllowEmptyString()]
[string]
$Expression,
[Parameter(Mandatory=$false)]
[switch]
$DisplayState
)
Begin
{
function Out-State ([System.Collections.Stack]$Stack)
{
$array = $Stack.ToArray()
[Array]::Reverse($array)
$array | ForEach-Object -Process { Write-Host ("{0,-8:F3}" -f $_) -NoNewline } -End { Write-Host }
}
function New-RpnEvaluation
{
$stack = New-Object -Type System.Collections.Stack
$shortcuts = @{
"+" = "Add"; "-" = "Subtract"; "/" = "Divide"; "*" = "Multiply"; "%" = "Remainder"; "^" = "Pow"
}
:ARGUMENT_LOOP foreach ($argument in $args)
{
if ($DisplayState -and $stack.Count)
{
Out-State $stack
}
if ($shortcuts[$argument])
{
$argument = $shortcuts[$argument]
}
try
{
$stack.Push([decimal]$argument)
continue
}
catch
{
}
$argCountList = $argument -replace "(\D+)(\d*)",‘$2’
$operation = $argument.Substring(0, $argument.Length – $argCountList.Length)
foreach($type in [Decimal],[Math])
{
if ($definition = $type::$operation)
{
if (-not $argCountList)
{
$argCountList = $definition.OverloadDefinitions |
Foreach-Object { ($_ -split ", ").Count } |
Sort-Object -Unique
}
foreach ($argCount in $argCountList)
{
try
{
$methodArguments = $stack.ToArray()[($argCount–1)..0]
$result = $type::$operation.Invoke($methodArguments)
$null = 1..$argCount | Foreach-Object { $stack.Pop() }
$stack.Push($result)
continue ARGUMENT_LOOP
}
catch
{
## If error, try with the next number of arguments
}
}
}
}
}
if ($DisplayState -and $stack.Count)
{
Out-State $stack
if ($stack.Count)
{
Write-Host "`nResult = $($stack.Peek())"
}
}
else
{
$stack
}
}
}
Process
{
Invoke-Expression -Command "New-RpnEvaluation $Expression"
}
End
{
}
}
Invoke-Rpn -Expression "3 4 2 * 1 5 - 2 3 ^ ^ / +" -DisplayState
|
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
| #COBOL | COBOL | identification division.
function-id. palindromic-test.
data division.
linkage section.
01 test-text pic x any length.
01 result pic x.
88 palindromic value high-value
when set to false low-value.
procedure division using test-text returning result.
set palindromic to false
if test-text equal function reverse(test-text) then
set palindromic to true
end-if
goback.
end function palindromic-test.
|
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
| #Ksh | Ksh |
#!/bin/ksh
# Pangram checker
# # Variables:
#
alphabet='abcdefghijklmnopqrstuvwxyz'
typeset -a strs
strs+=( 'Mr. Jock, TV quiz PhD., bags few lynx.' )
strs+=( 'A very mad quack might jinx zippy fowls.' )
# # Functions:
#
# # Function _ispangram(str) - return 0 if str is a pangram
#
function _ispangram {
typeset _str ; typeset -l _str="$1"
typeset _buff ; _buff="${alphabet}"
typeset _i ; typeset -si _i
for ((_i=0; _i<${#_str} && ${#_buff}>0; _i++)); do
_buff=${_buff/${_str:${_i}:1}/}
done
return ${#_buff}
}
######
# main #
######
typeset -si i
for ((i=0; i<${#strs[*]}; i++)); do
_ispangram "${strs[i]}"
if (( ! $? )); then
print "${strs[i]} <<< IS A PANGRAM."
else
print "${strs[i]} <<< Is not a pangram."
fi
done
|
http://rosettacode.org/wiki/Pangram_checker | Pangram checker | Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.
A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: The quick brown fox jumps over the lazy dog.
Task
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
Related tasks
determine if a string has all the same characters
determine if a string has all unique characters
| #Liberty_BASIC | Liberty BASIC | 'Returns 0 if the string is NOT a pangram or >0 if it IS a pangram
string$ = "The quick brown fox jumps over the lazy dog."
Print isPangram(string$)
Function isPangram(string$)
string$ = Lower$(string$)
For i = Asc("a") To Asc("z")
isPangram = Instr(string$, chr$(i))
If isPangram = 0 Then Exit Function
Next i
End Function |
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.
| #VBA | VBA | Option Base 1
Private Function pascal_upper(n As Integer)
Dim res As Variant: ReDim res(n, n)
For j = 1 To n
res(1, j) = 1
Next j
For i = 2 To n
res(i, 1) = 0
For j = 2 To i
res(j, i) = res(j, i - 1) + res(j - 1, i - 1)
Next j
For j = i + 1 To n
res(j, i) = 0
Next j
Next i
pascal_upper = res
End Function
Private Function pascal_symmetric(n As Integer)
Dim res As Variant: ReDim res(n, n)
For i = 1 To n
res(i, 1) = 1
res(1, i) = 1
Next i
For i = 2 To n
For j = 2 To n
res(i, j) = res(i - 1, j) + res(i, j - 1)
Next j
Next i
pascal_symmetric = res
End Function
Private Sub pp(m As Variant)
For i = 1 To UBound(m)
For j = 1 To UBound(m, 2)
Debug.Print Format(m(i, j), "@@@");
Next j
Debug.Print
Next i
End Sub
Public Sub main()
Debug.Print "=== Pascal upper matrix ==="
pp pascal_upper(5)
Debug.Print "=== Pascal lower matrix ==="
pp WorksheetFunction.Transpose(pascal_upper(5))
Debug.Print "=== Pascal symmetrical matrix ==="
pp pascal_symmetric(5)
End Sub |
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.