Skip to content

Commit 308be73

Browse files
committed
Много рефакторинга
Вынес все строки в отдельный файл, убрал немного неиспользуемого
1 parent e799ac5 commit 308be73

18 files changed

Lines changed: 196 additions & 229 deletions

app/src/main/java/com/apochromat/codeblockmobile/logic/Arithmetics.kt

Lines changed: 71 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import kotlin.math.*
66
fun arithmetics(heap: Heap, expression: String): Pair<String, Int> {
77
val exp = expression.replace("\\s".toRegex(), "")
88
if (exp.isEmpty()) {
9-
return Pair("Empty input", 0)
9+
return Pair(emptyInput(), 0)
1010
}
1111
val (prepared, expStatus) = preparingExpression(heap, exp)
1212
val (correctLine, lineStatus) = lineCheck(exp)
@@ -78,7 +78,7 @@ fun rpnToAnswer(rpn: String): Pair<String, Int> {
7878
try {
7979
stack.push(operand.toInt())
8080
} catch (e: NumberFormatException) {
81-
return Pair("Unexpected symbol $operand", 0)
81+
return Pair(unexpectedSymbol(operand), 0)
8282
}
8383
operand = String()
8484
}
@@ -91,7 +91,7 @@ fun rpnToAnswer(rpn: String): Pair<String, Int> {
9191
'^' ->{
9292
val result = b.toDouble().pow(a).toLong()
9393
if(result>=2147483647){
94-
return Pair("Memory limit", 0)
94+
return Pair(memoryLimit(), 0)
9595
}
9696
stack.push(result.toInt())
9797
}
@@ -100,10 +100,10 @@ fun rpnToAnswer(rpn: String): Pair<String, Int> {
100100
val result = b.toDouble().pow(step).toLong()
101101

102102
if (b<0){
103-
return Pair("Root of a negative number",0)
103+
return Pair(negativeRoot(), 0)
104104
}
105105
if(result>=2147483647){
106-
return Pair("Memory limit", 0)
106+
return Pair(memoryLimit(), 0)
107107
}
108108
stack.push(result.toInt())
109109
}
@@ -114,145 +114,140 @@ fun rpnToAnswer(rpn: String): Pair<String, Int> {
114114
try {
115115
stack.push(b / a)
116116
} catch (e: Exception) {
117-
return Pair("Division by zero", 0)
117+
return Pair(zeroDivision(), 0)
118118
}
119119
}
120120
'%' ->{
121121
try {
122122
stack.push(b % a)
123123
} catch (e: Exception){
124-
return Pair("Division by zero", 0)
124+
return Pair(zeroDivision(), 0)
125125
}
126126
}
127127
else -> {
128-
return Pair("Unexpected symbol ${rpn[i]}", 0)
128+
return Pair(unexpectedSymbol(rpn[i].toString()), 0)
129129
}
130130
}
131131
} catch (e: EmptyStackException) {
132-
return Pair("Incorrect expression", 0)
132+
return Pair(incorrectExpression(), 0)
133133
}
134134
}
135135
i++
136136
}
137-
return Pair("OK", stack.pop())
137+
return Pair(ok(), stack.pop())
138138
}
139139

140140
fun lineCheck(string: String): Pair<String, Int> {
141141
var str = string.replace("[A-Za-z-+*/0-9()%_^#\\[\\]]".toRegex(), "")
142142
if (str.isNotEmpty()) {
143-
return Pair("Unexpected Symbol", 0)
143+
return Pair(unexpectedSymbol(str), 0)
144144
}
145-
val reg = "([-+%#^ ]+[0-9_]+[A_Za-z_]+[0-9]*[-+%*#^ ]*)|(\\b[0-9_]+[A-Za-z_]+[0-9]*)|(\\b[_][0-9]+)".toRegex()
146-
if(reg.find(string)!=null){
147-
return Pair("Incorrect Expression",0)
145+
val reg = "([-+%#^ ]+[0-9_]+[A-Za-z_]+[0-9]*[-+%*#^ ]*)|(\\b[0-9_]+[A-Za-z_]+[0-9]*)|(\\b[_][0-9]+)".toRegex()
146+
if(reg.find(string)!=null) {
147+
return Pair(incorrectExpression(), 0)
148148
}
149-
str=string.replace("[A-Za-z-+*/0-9%^#_\\[\\]]".toRegex(), "")
150-
val scob1=str.replace("\\(".toRegex(), "")
151-
val scob2 =str.replace("\\)".toRegex(), "")
152-
if (scob1.length!=scob2.length) {
153-
return Pair("Incorrect Expression", 0)
149+
str = string.replace("[A-Za-z-+*/0-9%^#_\\[\\]]".toRegex(), "")
150+
val bracket1 = str.replace("\\(".toRegex(), "")
151+
val bracket2 = str.replace("\\)".toRegex(), "")
152+
if (bracket1.length != bracket2.length) {
153+
return Pair(incorrectExpression(), 0)
154154
}
155-
return Pair("OK", 1)
155+
return Pair(ok(), 1)
156156
}
157157

158158
fun preparingExpression(heap: Heap, expression: String): Pair<String, Int> {
159159
var exp = expression
160160
var preparedExpression = String()
161-
val regArr="([A-Za-z]+[A-Za-z0-9_]*)\\[[A-Za-z0-9 +%*/_#^-]*]".toRegex();
162-
var array = regArr.find(exp);
161+
val regArr="([A-Za-z]+[A-Za-z0-9_]*)\\[[A-Za-z0-9 +%*/_#^-]*]".toRegex()
162+
var array = regArr.find(exp)
163163
while (array!=null) {
164164
val (arrName, arrIndex) = indexCount(heap, array.value)
165165
if(arrIndex==-1){
166166
return Pair(arrName, 0)
167167
}
168168
if (!heap.isArrayExist(arrName)) {
169-
return Pair("Undefined array $arrName", 0)
169+
return Pair(undefinedArray(arrName), 0)
170170
}
171-
val arrValue = heap.getArrayValue(arrName, arrIndex);
172-
var fromArrToNum =arrValue.toString()
173-
if(arrValue!!.toInt()<0){
174-
fromArrToNum="("+fromArrToNum+")"
171+
val arrValue = heap.getArrayValue(arrName, arrIndex)
172+
var fromArrToNum = arrValue.toString()
173+
if(arrValue!!.toInt() < 0) {
174+
fromArrToNum = "($fromArrToNum)"
175175
}
176176
exp = exp.replace(array.value, fromArrToNum)
177177
array = regArr.find(exp)
178178
}
179-
val reg="[A-Za-z]+[A-Za-z0-9_]*".toRegex();
180-
var varieble = reg.find(exp);
181-
while (varieble!=null) {
182-
val VV=varieble.value;
183-
if (!heap.isVariableExist(varieble.value)) {
184-
return Pair("Undefined varieble $VV ", 0)
179+
val reg="[A-Za-z]+[A-Za-z0-9_]*".toRegex()
180+
var variable = reg.find(exp)
181+
while (variable!=null) {
182+
if (!heap.isVariableExist(variable.value)) {
183+
return Pair(undefinedVariable(variable.value), 0)
185184
}
186-
val varValue=heap.getVariableValue(varieble.value)
187-
var fromVarToNum =varValue.toString()
188-
if(varValue!!.toInt()<0){
189-
fromVarToNum="("+fromVarToNum+")"
185+
val varValue = heap.getVariableValue(variable.value)
186+
var fromVarToNum = varValue.toString()
187+
if(varValue!!.toInt() < 0) {
188+
fromVarToNum= "($fromVarToNum)"
190189
}
191-
exp = exp.replaceRange(varieble.range, fromVarToNum)
192-
varieble = reg.find(exp)
190+
exp = exp.replaceRange(variable.range, fromVarToNum)
191+
variable = reg.find(exp)
193192
}
194193

195194
for (j in exp.indices) {
196195
if (exp[j] == '-') {
197-
if (j == 0) {
198-
preparedExpression += "0"
199-
} else if (exp[j - 1] == '(') {
196+
if ((j == 0) || (exp[j - 1] == '(')) {
200197
preparedExpression += "0"
201198
}
202199
}
203200
preparedExpression += exp[j]
204201
}
205202
return Pair(preparedExpression, 1)
206203
}
204+
207205
fun defineInput(heap:Heap, expression: String):Triple<String,String, Int>{
208-
val arr="[A-Za-z]+[\\[(\\d+_*^#)\\]]".toRegex();
209-
val varieble = "[A-Za-z]+[A-Za-z0-9_]*".toRegex();
206+
val arr="[A-Za-z]+[\\[(\\d+_*^#)\\]]".toRegex()
207+
val variable = "[A-Za-z]+[A-Za-z0-9_]*".toRegex()
210208

211-
if(arr.find(expression)!=null){
212-
val(name, index)= indexCount(heap,expression);
213-
if (index==-1){
214-
return Triple(name, "NaN", 0);
209+
if (arr.find(expression)!=null){
210+
val(name, index) = indexCount(heap,expression)
211+
if (index == -1) {
212+
return Triple(name, tagNaN(), 0)
215213
}
216214
if(heap.isArrayExist(name) && index>=0 && index<heap.getArraySize(name)!!.toInt()) {
217-
return Triple("Array", name, index);
215+
return Triple(tagArray(), name, index)
218216
}
219217
}
220-
if(varieble.find(expression)!=null){
218+
if (variable.find(expression)!=null){
221219
if(heap.isVariableExist(expression)) {
222-
return Triple("Variable", expression, 0);
220+
return Triple(tagVariable(), expression, 0)
223221
}
224222
}
225-
return Triple("InputError","NaN",0);
223+
return Triple(inputError(), tagNaN(),0)
226224
}
225+
227226
fun indexCount(heap:Heap, arr:String):Pair<String,Int>{
228-
var array:String=arr;
229-
var index=-1;
230-
var arrname="";
231-
val reg="([A-Za-z]+[A-Za-z0-9_]*)\\[[A-Za-z0-9 +*/%_^#-]*]".toRegex();
232-
while (reg.find(array)!=null){
233-
val arg="\\[[A-Za-z0-9 +*/_%^#-]*]".toRegex().find(array);
234-
arrname="[A-Za-z]+[A-Za-z0-9_]*".toRegex().find(reg.find(array)!!.value)!!.value;
227+
var array = arr
228+
var index = -1
229+
var arrayName = ""
230+
val reg = "([A-Za-z]+[A-Za-z0-9_]*)\\[[A-Za-z0-9 +*/%_^#-]*]".toRegex()
231+
while (reg.find(array) != null) {
232+
val arg = "\\[[A-Za-z0-9 +*/_%^#-]*]".toRegex().find(array)
233+
arrayName = "[A-Za-z]+[A-Za-z0-9_]*".toRegex().find(reg.find(array)!!.value)!!.value
235234
if(arg!=null) {
236-
var arm=arg.value.replace("[","");
237-
arm=arm.replace("]","");
238-
var (status, rez) = arithmetics(heap, arm);
239-
array=array.replace(arm,rez.toString());
240-
index= rez;
241-
println(index)
242-
println(status)
243-
if(!heap.isArrayExist(arrname)){
244-
return Pair("Unidentified array", -1)
235+
val arm = arg.value.replace("[","").replace("]","")
236+
val (status, rez) = arithmetics(heap, arm)
237+
array = array.replace(arm,rez.toString())
238+
index = rez
239+
if (!heap.isArrayExist(arrayName)){
240+
return Pair(undefinedArray(arrayName), -1)
245241
}
246-
if (index>=heap.getArraySize(arrname)!!.toInt() || index<0){
247-
return Pair("Index out of range", -1)
242+
if (index >= heap.getArraySize(arrayName)!!.toInt() || index<0){
243+
return Pair(indexOutOfRange(), -1)
248244
}
249-
if(status!="OK"){
250-
return Pair(status,-1)
245+
if(status != ok()){
246+
return Pair(status, -1)
251247
}
252-
val arrayValue=heap.getArrayValue(arrname,rez);
253-
array=array.replace(reg.find(array)!!.value, arrayValue.toString());
254-
248+
val arrayValue = heap.getArrayValue(arrayName, rez)
249+
array = array.replace(reg.find(array)!!.value, arrayValue.toString())
255250
}
256251
}
257-
return Pair(arrname,index);
252+
return Pair(arrayName, index)
258253
}

app/src/main/java/com/apochromat/codeblockmobile/logic/Assignment.kt

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,23 @@ class Assignment : Block() {
2525
}
2626

2727
override fun executeBlock() {
28+
super.executeBlock()
2829
initVar()
2930
val obj = defineInput(heap, inputName)
3031
name = obj.second
31-
if (obj.first !in listOf("Array", "Variable")) {
32+
if (obj.first !in listOf(tagArray(), tagVariable())) {
3233
setBlockStatus(obj.first)
3334
return
3435
}
3536
val calculated = arithmetics(heap, inputValue)
3637
setBlockStatus(calculated.first)
37-
if (calculated.first != "OK") return
38+
if (calculated.first != ok()) return
3839
value = calculated.second
3940
when (obj.first) {
40-
"Array" -> {
41+
tagArray() -> {
4142
heap.setArrayValue(name, obj.third, value)
4243
}
43-
"Variable" -> {
44+
tagVariable() -> {
4445
heap.setVariableValue(name, value)
4546
}
4647
}

app/src/main/java/com/apochromat/codeblockmobile/logic/Block.kt

Lines changed: 9 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,11 @@ open class Block {
1515
// Хранилище переменных
1616
var heap: Heap = Heap()
1717

18-
// Счетчик блоков
19-
var counter: Int = 0
20-
21-
// Словарь со всеми блоками
22-
var allBlocks: MutableMap<Int, Block> = mutableMapOf()
23-
24-
// Список устойчивых связей между блоками
25-
var strongConnections: MutableList<Pair<Block, Block>> = mutableListOf()
26-
2718
// Флаг работы программы
2819
var isProgramRunning = false
2920
}
30-
// Переменные с данными
3121

22+
// Переменные с данными
3223
var inputLeftEdit: String = ""
3324
var inputMediumEdit: String = ""
3425
var inputRightEdit: String = ""
@@ -49,18 +40,14 @@ open class Block {
4940
lateinit var activity: ProjectActivity
5041

5142
var crutch = true
43+
5244
// Ссылки на следующий и предыдущий блоки
5345
private var nextBlock: Block? = null
5446
private var prevBlock: Block? = null
5547

5648
// Тип, статус и идентификатор блока
57-
private var type: String = "Undefined"
58-
var status: String = "OK"
59-
private var id: Int = counter++
60-
61-
init {
62-
allBlocks[this.getBlockId()] = this
63-
}
49+
private var type: String = ""
50+
var status: String = ok()
6451

6552
// Операции с типом, статусом и идентификатором блока
6653
fun setBlockType(input: String) {
@@ -79,19 +66,6 @@ open class Block {
7966
return status
8067
}
8168

82-
fun getBlockId(): Int {
83-
return id
84-
}
85-
86-
fun getBlockById(_id: Int): Block? {
87-
return allBlocks[_id]
88-
}
89-
90-
// Получить словарь всех блоков
91-
fun getAllBlocks(): MutableMap<Int, Block> {
92-
return allBlocks
93-
}
94-
9569
// Получить доступ к хранилищу переменных
9670
fun accessHeap(): Heap {
9771
return heap
@@ -114,27 +88,12 @@ open class Block {
11488
return prevBlock
11589
}
11690

117-
// Операции со списком устойчивых связей между блоками
118-
fun addStrongConnection(pair: Pair<Block, Block>) {
119-
strongConnections.add(pair)
120-
}
121-
122-
fun removeStrongConnection(pair: Pair<Block, Block>) {
123-
strongConnections.remove(pair)
124-
}
125-
126-
fun getAllStrongConnections(): MutableList<Pair<Block, Block>> {
127-
return strongConnections
91+
open fun executeBlock() {
92+
status = ok()
12893
}
129-
130-
open fun executeBlock() {}
13194
open fun kickRunning() {}
132-
fun clearBlockData() {
133-
status = "OK"
134-
}
13595

13696
open fun run() {
137-
// adapterConsole.addMessage( getPrevBlock()?.indexListBlocks.toString() + " " + type + " " + getNextBlock()?.indexListBlocks.toString())
13897
if (getBlockType() == "ConsoleInput"){
13998
executeBlock()
14099
}
@@ -143,17 +102,15 @@ open class Block {
143102
when {
144103
getNextBlock() == null -> {
145104
isProgramRunning = false
146-
println("Program finished with status: ${getBlockStatus()}")
147-
adapterConsole.addMessage("Program finished with status: ${getBlockStatus()}")
105+
adapterConsole.addMessage(programFinish(status))
148106
adapterBlocks.notifyItemChanged(indexListBlocks)
149107
}
150-
getBlockStatus() == "OK" -> {
108+
getBlockStatus() == ok() -> {
151109
callStack.push(getNextBlock())
152110
}
153111
else -> {
154112
isProgramRunning = false
155-
println("Program finished with status: ${getBlockStatus()}")
156-
adapterConsole.addMessage("Program finished with status: ${getBlockStatus()}")
113+
adapterConsole.addMessage(programFinish(status))
157114
adapterBlocks.notifyItemChanged(indexListBlocks)
158115
}
159116
}

0 commit comments

Comments
 (0)