static string[] infixToPostfix(string[] exp)
{
Stack<string> result = new Stack<string>();
Stack<string> stack = new Stack<string>();
stack.Push("#");
// iterating through each token
foreach (string s in exp)
{
if (isNumber(s))
{
result.Push(s);
}
else if (s == "(")
{
stack.Push(s);
}
else if (s == ")")
{
while ((stack.Peek() != "(") && (stack.Count > 0))
{
result.Push(stack.Peek());
stack.Pop();
}
stack.Pop();
}
else
{
while ((stack.Peek() != "#") && (getPriority(s) <= getPriority(stack.Peek())))
{
result.Push(stack.Peek());
stack.Pop();
}
stack.Push(s);
}
}
while (stack.Peek() != "#")
{
result.Push(stack.Peek());
stack.Pop();
}
return result.ToArray();
}
That is my alghorithm, i've got an assignment to create an expression tree based calculator and i've been succeded to built tree based on a right postfix notation, the problem is that i still cant figure out how to convert an array of string into a right postfix notation, can somebody please help me figure it out
Related
I get this error and I don't know why. I basically just check the operator and make calculations based on that.
Thank you for your help.
Function:
void calculate() {
setState(() {
int num1int = int.tryParse(_num1);
int num2int = int.tryParse(_num2);
int result = 0;
if (_operator == "+") {
result = num1int + num2int;
}
else if (_operator == "-") {
result = num1int - num2int;
}
else if (_operator == "*") {
result = num1int * num2int;
}
else if (_operator == "/") {
result = num1int ~/ num2int;
}
});
}
if "int.tryParse" can not convert it into integer, it will be returning "null". So your code does: null + null. You can add a check for num1int and num2int if it is null before calcultion.
please change your code to
if (_operator == "+") {
result = num1int??0 + num2int??0;
}
else if (_operator == "-") {
result = num1int??0 - num2int??0;
}
else if (_operator == "*") {
result = num1int??1 * num2int??1;
}
else if (_operator == "/") {
result = num1int??1 ~/ num2int??1;
}
How do i convert below Java code to scala and use continue in for loop, this program remove minimum number of extra closed parenthesis in a given string
input : lee(t(c)o)de)
output : leet(t(c)o)de
public String minRemoveToMakeValid(String s){
StringBuilder sb =new StringBuilder();
in open =0;
for (char c : s.toCharArray()){
if(c == '('){
open++
}
else if(c == ')'){
if(open == 0) continue;
open --;
}
sb.append(c)
}
return sb
}
https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
import util.control.Breaks._
val searchMe = "peter piper picked a peck of pickled peppers"
var numPs = 0
for (i <- 0 until searchMe.length) {
breakable {
if (searchMe.charAt(i) != 'p') {
break // break out of the 'breakable', continue the outside loop
} else {
numPs += 1
}
}
}
println("Found " + numPs + " p's in the string.")
Try it: https://scastie.scala-lang.org/R9sr95WESLyiKamCHHUVdQ
Im able to get it worked using below code
def minRemoveToMakeValid(s: String): String = {
var open = 0
val sb = new StringBuilder
for (c <- s.toCharArray) {
breakable {
if (c == '(') open += 1
else if (c == ')') {
if (open == 0)break
open -= 1
}
sb.append(c)
}
}
var result = new StringBuilder()
for(i<-sb.length()-1 to 0 by -1)
{
breakable{
open-=1
if(sb.charAt(i) == '(' && open >0) break
result.append(sb.charAt(i))
}
}
result.reverse.toString()
}
I am builing a little method for parenthesis balancing using scala and recursion.
I came out this code which surprisingly doesn't work.
object Test{
def balance(chars: List[Char]): Boolean=
{
var opening_index: Int = -1
var closing_index: Int = -1
opening_index = chars.indexOf('(')
closing_index = chars.indexOf(')')
println(opening_index)
println(closing_index)
if ( chars.size == 0 ) true
if ((opening_index == -1) & (closing_index== -1))
{
true
}
if (closing_index> -1 & opening_index> -1)
{
if (closing_index< opening_index) return(false)
else
{
balance(chars.filter(_!=chars(closing_index)).filter(_!=chars(opening_index)))
}
}
else
return (false)
}
val lst:List[Char] = List('(',')' ,'3','4')
balance(lst)
}
I am aware that there are other similar posts but I am more interested in using this approach than the other ones.
You probably wanted to filter by index, not by character. As it is, your code erases all parentheses in the first round.
This here works with zipWithIndex, and compares the index with opening_index and closing_index:
def balance(chars: List[Char]): Boolean = {
val opening_index = chars.indexOf('(')
val closing_index = chars.indexOf(')')
if ( chars.size == 0 ) {
true
} else if ((opening_index == -1) && (closing_index== -1)) {
true
} else if (closing_index > -1 && opening_index > -1) {
if (closing_index < opening_index) {
false
} else {
balance(
chars.zipWithIndex.filterNot{
case (c, i) => i == opening_index || i == closing_index
}.map(_._1)
)
}
} else {
false
}
}
println(balance("()34".toList))
println(balance("()34)".toList))
println(balance("(x)(y(z))".toList))
println(balance("(x)(y(z)".toList))
Output:
true
false
true
false
You can use below solution to check balance parenthesis.
object Driver extends App{
def balance(chars: List[Char]): Boolean=
{
if (chars.mkString("").length() == 0) {
return true;
}
if (chars.mkString("").contains("()")) {
return balance(chars.mkString("").replaceFirst("\\(\\)", "").toCharArray.toList);
}
if (chars.mkString("").contains("[]")) {
return balance(chars.mkString("").replaceFirst("\\[\\]", "").toCharArray.toList);
}
if (chars.mkString("").contains("{}")) {
return balance(chars.mkString("").replaceFirst("\\{\\}", "").toCharArray.toList);
} else {
return false;
}
}
println(balance(List('(','{','}')))
println(balance(List('(','{','}',')')))
}
There are two main (functional) problems with this code.
Firstly, this test does nothing because the result is thrown away
if ((opening_index == -1) & (closing_index== -1))
{
true
}
You probably meant return true
Secondly, the recursive call is wrong
balance(chars.filter(_ != chars(closing_index)).filter(_ != chars(opening_index)))
These two calls to filter are removing all the parentheses from the list, so the call to balance will always succeed even if the rest of the list is unbalanced.
You probably want to use three slice calls to remove the specific parentheses at opening_index and closing_index.
I just finished creating a program (I am a beginner at this programming stuff) Now I might be doing this the total wrong way or my logic might not be the greatest at programming but any help would be amazing I will post my code so far below
This code is used when a button is clicked, the button will send a text then the textbox will get the text.
if (txt1.Text == "")
{
txt1.Text = "J";
btn1.Visible = false;
}
else if (txt1.Text != "")
{
if (txt2.Text == "")
{
txt2.Text = "J";
btn1.Visible = false;
}
else if (txt2.Text != "")
{
if (txt3.Text == "")
{
txt3.Text = "J";
btn1.Visible = false;
}
else if (txt3.Text != "")
{
if (txt4.Text == "")
{
txt4.Text = "J";
btn1.Visible = false;
}
else if (txt4.Text != "")
{
if (txt5.Text == "")
{
txt5.Text = "J";
btn1.Visible = false;
}
else if (txt5.Text != "")
{
if (txt6.Text == "")
{
txt6.Text = "J";
btn1.Visible = false;
}
else if (txt6.Text != "")
{
if (txt7.Text == "")
{
txt7.Text = "J";
btn1.Visible = false;
}
else if (txt7.Text != "")
{
if (txt8.Text == "")
{
txt8.Text = "J";
btn1.Visible = false;
}
else if (txt8.Text != "")
{
}
}
}
}
}
}
}
}
You need to get all of these text cases into an array for the following loop to work (I have called the array 'txt' here). Based on what you have written this loop should do the same thing as your code but I'm not sure if that's what you really want to do. Your code is setting a single text box to "J" and then hiding your button only if every preceding text field is not an empty string (This will include any of the fields set to null, for example). The conditional then exits.
`for (int i = 0; i < txt.Length; i++) {
if(txt[i] != "") {
continue;
}
else if(txt[i] == "") {
txt[i] = "J";
btn1.Visible = false;
break;
}
}
Note: I don't know whether this works for C# 3 or not (it should). Try it.
First, you should put all of your text fields into an array:
TextField[] textFields = { txt1, txt2, txt3, txt4, txt5, txt6, txt7, txt8, };
Then, loop through the text fields to find a text field that has no text in it:
foreach (TextField tf in textFields) {
if (tf.Text == "") {
}
}
After we find it, we want to set its text to "J" and make btn1 invisible. Since we already found the text field, we don't need to continue the loop anymore, so we break:
tf.Text = "J";
btn1.Visible = false;
break;
If this doesn't work in C# 3, just update to C# 5 or 6 alright?
I am using JavaCC to print an AST in a particular format.
I need it to be like this :
LetNode( Identier(X), ExprNode( PlusNode( IntegerLiteral(8), IntegerLiteral(2) )))
but I am getting:
Start(LetNode(Identifier(x)(ExprNode(IntegerLiteral(5)(PlusNode(IntegerLiteral(5)()))
I am using the dump method to print this:
public void dump(String prefix) {
System.out.print(toString(prefix));
System.out.print("(");
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode)children[i];
if (n != null) {
n.dump(prefix +"");
}
}
System.out.print(")");
}
}
}
The output without any modification is :
Start
Sxl
Statement
VariableDecl
Identifier
Type
Expression
SimpleExpression
Term
Factor
Literal
IntegerLiteral
AdditiveOp
Term
Factor
Literal
IntegerLiteral
My method:
void AdditiveOp():
{}
{
(Plus() /*#Add(2)*/ | Minus() | Or())
}
void Plus():
{
}
{
(< PLUS >)
#PlusNode
}
If I remove the /* */ it does not work as it says it expects something else not +
Any help would be greatly appreciated!
The usual way to make an AST with JJT for an expression grammar is to do something like this
void AdditiveExpression() #void :
{ Token t ; }
{
MultiplicativeExpression()
( "+" MultiplicativeExpression() #Add(2)
| "-" MultiplicativeExpression() #Subtract(2)
)*
}