Я делаю приложение для iOS для структуры данных, и в преобразовании prefix-infix-postfix есть логическая ошибка, поэтому мне нужна помощь, чтобы выяснить это.
Я попытался отладить свой код с помощьюдобавить точку останова в моем коде, и я также пытаюсь сравнить с алгоритмом prefix-infix-postfix
AS Input Я вначале предоставляю строку от пользователя, которую он / она должен выбрать из двух видов выбора, например, из "Что *" в "Что *", что они для преобразования.
что * = Infix или префикс или постфикс
, затем в текстовом поле в соответствии с пользователем "from" введите выражение в виде строки, затем нажмите кнопку "CONVERT" и затем под кнопкойкак пользователь метки, получите ответ
хорошо, так что это код для преобразования префикса infix в префикс infix-to-postfix, postfix-to-infix, postfix-to-prefix, prefix-to-infix и prefix-to-postfix.Я получил правильный вывод для префикса infix к префиксу, от infix к postfix, но для других, когда я нажимаю кнопку «Преобразовать», поскольку ответ показывает мне это рядом с моим выражением ответа, но это не так, значит, в этой частикод
ссылка на код: DATASTRUCTURE
//
// countViewController.swift
// DataStructure
//
// Created by Mihir Joshi on 18/08/18.
// Copyright © 2018 Mihir Joshi. All rights reserved.
//
import UIKit
extension String {
func getCharAtIndex(_ index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
}
public struct Stack1<T> {
fileprivate var array = [T]()
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public mutating func push(_ element: T) {
array.append(element)
}
public mutating func pop() -> T? {
return array.popLast()
}
public var top: T? {
return array.last
}
}
class countViewController: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource , UITextFieldDelegate
{
@IBOutlet weak var from_lbl: UITextField!
@IBOutlet weak var to_lbl: UITextField!
// @IBOutlet weak var input_txt: UITextField!
@IBOutlet weak var btnconvert: UIButton!
@IBOutlet weak var input_Text: UITextField!
@IBOutlet weak var answer_lbl: UILabel!
@IBOutlet weak var btnSave: UIButton!
@IBOutlet weak var btnHistory: UIButton!
@IBOutlet weak var ansIs: UILabel!
@IBOutlet weak var toPickerView: UITextField!
@IBOutlet weak var fromPickerView: UITextField!
let selectpicker = ["Prefix","Infix","Postfix"]
var sp1 = Int()
var selected = String()
var btn = String()
var btn1 = String()
var sp2 = Int()
var msg = "Please enter valid the selection !"
var input = String()
var s = Stack<String>()
// var s1 = Stack1<Character>()
let select = UIPickerView()
let fromselect = UIPickerView()
override func viewDidLoad() {
super.viewDidLoad()
sp1 = 0;
from_lbl.inputView = fromselect
to_lbl.inputView = select
select.delegate = self as UIPickerViewDelegate
select.dataSource = self as UIPickerViewDataSource
fromselect.delegate = self as UIPickerViewDelegate
fromselect.dataSource = self as UIPickerViewDataSource
btnconvert.layer.cornerRadius = 5.0
btnSave.layer.cornerRadius = 5.0
// btnHistory.layer.cornerRadius = 5.0
let toolbar = UIToolbar();
toolbar.sizeToFit()
let doneCastButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donecastPicker(sender: )))
doneCastButton.tintColor = UIColor(displayP3Red: 28.0/255.0, green: 28.0/255.0, blue: 28.0/255.0, alpha: 1.0)
toolbar.setItems([doneCastButton], animated: false)
let toolbar2 = UIToolbar();
toolbar2.sizeToFit()
let doneCast2Button = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(countViewController.done2castPicker));
doneCast2Button.tintColor = UIColor(displayP3Red: 28.0/255.0, green: 28.0/255.0, blue: 28.0/255.0, alpha: 1.0)
toolbar2.setItems([doneCast2Button], animated: false)
to_lbl.inputAccessoryView = toolbar
from_lbl.inputAccessoryView = toolbar2
}
@objc func donecastPicker(sender : UIBarButtonItem)
{
to_lbl.text = selectpicker[sp1]
if(sp1==0)
{
btn = "Prefix";
}
if(btn == "" && btn1 == "")
{
btnconvert.setTitle("Convert", for: .normal)
}
else
{
btnconvert.setTitle("Convert \(btn) to \(btn1)", for: .normal)
}
self.view.endEditing(true)
}
@objc func done2castPicker()
{
from_lbl.text = selectpicker[sp2]
if(btn == "" && btn1 == "")
{
btnconvert.setTitle("Convert", for: .normal)
}
else if(btn != "" && btn1 != "")
{
btnconvert.setTitle("Convert \(btn) to \(btn1)", for: .normal)
}
self.view.endEditing(true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return selectpicker.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return selectpicker[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
selected = selectpicker[row]
if(pickerView == select)
{
sp1 = pickerView.selectedRow(inComponent: 0)
btn = selectpicker[pickerView.selectedRow(inComponent: 0)]
}
else if(pickerView == fromselect)
{
sp2 = pickerView.selectedRow(inComponent: 0)
btn1 = selectpicker[pickerView.selectedRow(inComponent: 0)]
}
}
@IBAction func errorcheck(_ sender: Any) {
if(from_lbl.text == to_lbl.text || from_lbl.text! == "" || to_lbl.text! == "")
{
var msg3 = String()
msg3 = "Please review the selection(s)"
let errormessageshow = UIAlertController(title: "Empty Field", message: msg, preferredStyle: UIAlertController.Style.alert)
let defaultaction = UIAlertAction(title: "Ok", style: .default, handler:nil)
errormessageshow.addAction(defaultaction)
self.present(errormessageshow,animated: true, completion: nil)
}
}
@IBAction func save(_ sender: Any) {
// let c = historyelement.object(at: fromPickerView.selectedRow(inComponent: 0)) as! historyelement
//self.txtCast.text = c.CasteName
let h : historyelement = historyelement()
let dh : DatabaseHelper = DatabaseHelper()
h.Answer = answer_lbl.text!
h.Question = input_Text.text!
h.From = to_lbl.text!
h.to = from_lbl.text!
if(dh.addhistory(historyelement: h))
{
let sucessaddmessage = UIAlertController(title: "Updated", message: "Added to History !", preferredStyle: UIAlertController.Style.alert)
let defaultaction = UIAlertAction(title: "ok", style: .default, handler : { (alert: UIAlertAction) in
self.navigationController?.popViewController(animated: true)
})
sucessaddmessage.addAction(defaultaction)
self.present(sucessaddmessage, animated: true, completion: nil)
}
// h.From = c.from
}
@IBAction func convert(_ sender: Any)
{
input = input_Text.text!
if(from_lbl.text == to_lbl.text || from_lbl.text == "" || to_lbl.text == "" || input_Text.text == "")
{
var msg2 = String()
msg2 = "There is empty field(s)"
let errormessageshow = UIAlertController(title: "Empty Fields", message: msg2, preferredStyle: UIAlertController.Style.alert)
let defaultaction = UIAlertAction(title: "Ok", style: .default, handler:nil)
errormessageshow.addAction(defaultaction)
self.present(errormessageshow,animated: true, completion: nil)
}
// //------------------------------- INFIX TO PREFIX-----------------------------------
if(to_lbl.text == "Infix" && from_lbl.text == "Prefix")
{
var temp = String()
// temp = infixToPostfix(exp: input)
input = String(input.characters.reversed())
for i in 0..<input.characters.count
{
if(input.getCharAtIndex(i) == "(")
{
// input = input.replacingOccurrences(of: "(", with: ")")
temp = temp + ")"
}
else if(input.getCharAtIndex(i) == ")")
{
//input = input.replacingOccurrences(of: ")", with: "(")
temp = temp + "("
}
else
{
temp = temp + String(input.getCharAtIndex(i))
}
}
temp = infixToPostfix(exp: temp);
answer_lbl.text = String(temp.characters.reversed())
if(answer_lbl.text != "")
{
btnSave.isHidden = false
}
}
// //------------------------------- INFIX TO POSTFIX -----------------------------------
//
if(to_lbl.text == "Infix" && from_lbl.text == "Postfix")
{
//
answer_lbl.text = infixToPostfix(exp: input);
}
if(answer_lbl.text != "")
{
btnSave.isHidden = false
}
//
//
//
// //------------------------------- PREFIX TO INFIX -----------------------------------
//
if(to_lbl.text == "Prefix" && from_lbl.text == "Infix")
{
var temp = String()
// temp = prefixToPostfix(exp: input)
// answer_lbl.text = postfixtoInfix(exp: temp)
input = String(input.characters.reversed())
temp = postfixtoInfix(exp: input);
temp = String(temp.characters.reversed())
var temp1 : String = String()
// temp = temp.replacingOccurrences(of: "(", with: ")")
// temp = temp.replacingOccurrences(of: ")", with: "(")
for i in 0..<temp.characters.count
{
let c = temp.getCharAtIndex(i)
if(c == "(")
{
temp1 = temp1 + ")"
// temp = temp + ")"
}
else if(c == ")")
{
temp1 = temp1 + "("
}
else
{
temp1 = temp1 + String(c)
}
}
answer_lbl.text = String(temp1)
if(answer_lbl.text != "")
{
btnSave.isHidden = false
}
}
//------------------------------- PREFIX TO POSTFIX -----------------------------------
//
if(to_lbl.text == "Prefix" && from_lbl.text == "Postfix")
{
answer_lbl.text = prefixToPostfix(exp: input)
if(answer_lbl.text != "")
{
btnSave.isHidden = false
}
}
// //------------------------------- POSTFIX TO INFIX -----------------------------------
//
if(to_lbl.text == "Postfix" && from_lbl.text == "Infix")
{
answer_lbl.text = postfixtoInfix(exp: input);
if(answer_lbl.text != "")
{
btnSave.isHidden = false
}
}
//------------------------------- POSTFIX TO PREFIX -----------------------------------
if(to_lbl.text == "Postfix" && from_lbl.text == "Prefix")
{
answer_lbl.text = PostfixToPrefix(exp: input);
if(answer_lbl.text != "")
{
btnSave.isHidden = false
}
}
//------------------------------------------------------------------------------------------------
}
func prefixToPostfix(exp : String) -> String
{
var result = String()
var op1 = String()
var op2 = String()
for i in stride(from: exp.count-1, to: 0, by: -1)
{
let c : String = String(exp.getCharAtIndex(i))
if(Prec1(c: exp.getCharAtIndex(i)))
{
op1 = s.pop()!
op2 = s.pop()!
result = op2 + op1 + c;
s.push(result);
}
else{
s.push(String(c));
}
}
while (!s.isEmpty())
{
result += String(s.pop()!);
}
return result
}
func Prec1 (c : Character) -> Bool
{
if(c == "+" || c == "-" || c == "*" || c == "/" || c == "^" || c == "%")
{
return true;
}
return false;
}
func PostfixToPrefix(exp : String) -> String
{
var result = String()
var op1 = String()
var op2 = String()
for i in stride(from: 0, to: exp.count-1, by: +1)
{
let c : String = String(exp.getCharAtIndex(i))
if(Prec1(c: exp.getCharAtIndex(i)))
{
op1 = s.pop()!
op2 = s.pop()!
result = op1 + op2 + c;
s.push(result);
}
else{
s.push(String(c));
//log vali line baki see in java code
}
}
while (!s.isEmpty())
{
result += String(s.pop()!);
}
return result
}
func postfixtoInfix(exp : String) -> String
{
var result = String()
for i in 0..<exp.count
{
// let ch = c[i]
let c = exp.getCharAtIndex(i)
let c1 = String(c)
if(isOperator(c: c)){
var b = String()
b = String(s.pop()!);
var a = String();
a = String(s.pop()!)
s.push("("+a+c1+b+")");
print(a+c1+b)
}
else
{
s.push(c1);
}
}
while (!s.isEmpty())
{
result += String(s.pop()!);
}
return result
}
func isOperator(c : Character) -> Bool
{
if(c == "+" || c == "-" || c == "*" || c == "/" || c == "^")
{
return true;
}
return false;
}
func Prec(ch : String ) -> Int {
switch(ch)
{
case "+":
return 1
case "-":
return 1;
case "*":
return 2
case "/":
return 2;
case "^":
return 3;
default:
return -1;
}
}
func infixToPostfix(exp : String ) -> String
{
var result = String()
result = "";
let charArray = [String]()
for i in 0..<exp.count {
let c : String = String(exp.getCharAtIndex(i))
if(c>="a" && c<="z" || c>="A" && c<="Z" || c>=String(0) && c<=String(9))
{
result = result + String(c)
}
else if (c=="(")
{
s.push(c);
}
else if (c==")")
{
while (!s.isEmpty() && s.peek() != "(")
{
result += String(s.pop()!)
}
if (!s.isEmpty() && s.peek() != "(")
{
return "Invalid Expression"; // invalid expression
}
else
{
s.pop();
}
}
else // an operator is encountered
{
while (!s.isEmpty() && Prec(ch: c) <= Prec(ch: s.peek()!))
{
result += String(s.pop()!);
}
s.push(String(c));
}
}
while (!s.isEmpty())
{
result += String(s.pop()!);
}
return result
}
// reversedString is reversed, or empty if myString was nil
@IBAction func checkLabelsValues(_ sender: Any) {
// print("Hello")
if(from_lbl.text == to_lbl.text || from_lbl.text == "" || to_lbl.text == "")
{
let errormessageshow = UIAlertController(title: "Invalid Selection", message: "Empty Field or Same Selection", preferredStyle: UIAlertController.Style.alert)
let defaultaction = UIAlertAction(title: "Ok", style: .default, handler:nil)
errormessageshow.addAction(defaultaction)
self.present(errormessageshow,animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}