Created
June 17, 2013 04:15
-
-
Save misodengaku/5794613 to your computer and use it in GitHub Desktop.
メモとして残しておく
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel; | |
using System.Data; | |
using System.Drawing; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Windows.Forms; | |
namespace reverse_polish | |
{ | |
public partial class Form1 : Form | |
{ | |
Dictionary<string, int> vals = new Dictionary<string, int>(); | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
label1.Text = "" + ExecutePolish(GetPolishString(textBox1.Text)); | |
return; | |
} | |
/// <summary> | |
/// 数式を逆ポーランド記法に変換します。 | |
/// </summary> | |
/// <param name="s"></param> | |
/// <returns></returns> | |
private string GetPolishString(string s) | |
{ | |
string ret = ""; | |
var stack = new Stack<char>(); | |
foreach (var i in s) | |
{ | |
if (i == '+' || i == '-' || i == '*' || i == '/' || i == '=') | |
{ | |
ret += ","; | |
stack.Push(i); | |
} | |
else | |
ret += i; | |
} | |
for (int i = stack.Count() - 1; i >= 0; i--) | |
{ | |
ret += ","; | |
ret += stack.Pop(); | |
} | |
return ret; | |
} | |
private int ExecutePolish(string s) | |
{ | |
var stack = new Stack<string>(); | |
string n1, n2; | |
foreach(var i in s.Split(new char[]{','})) | |
{ | |
if (i[0] >= '0' && i[0] <= '9') | |
{ | |
stack.Push("" + i); | |
} | |
else if (i == "+" || i == "-" || i == "*" || i == "/" || i == "=") | |
{ | |
int r = 0; | |
n2 = stack.Pop(); | |
n1 = stack.Pop(); | |
switch (i) | |
{ | |
case "+": | |
r = int.Parse(n1) + int.Parse(n2); | |
break; | |
case "-": | |
r = int.Parse(n1) - int.Parse(n2); | |
break; | |
case "*": | |
r = int.Parse(n1) * int.Parse(n2); | |
break; | |
case "/": | |
r = int.Parse(n1) / int.Parse(n2); | |
break; | |
} | |
stack.Push("" + r); | |
} | |
else{ | |
stack.Push("" + vals[i]); | |
} | |
} | |
return int.Parse(stack.Pop()); | |
} | |
private void button2_Click(object sender, EventArgs e) | |
{ | |
vals[textBox2.Text] = int.Parse(textBox3.Text); | |
listBox1.Items.Add("変数セット:" + textBox2.Text + "=" + textBox3.Text); | |
} | |
private void button3_Click(object sender, EventArgs e) | |
{ | |
listBox1.Items.Add("変数内容:" + textBox2.Text + "=" + vals[textBox2.Text]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment