-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindOperations.cs
66 lines (60 loc) · 2.12 KB
/
FindOperations.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Collections.Generic;
using System.Linq;
namespace Q
{
public class FindOperations
{
private string[] _operations = new string[] { "+", "-", "/", "*" };
private Stack<string> _store = new Stack<string>();
private int _count = 0;
public FindOperations()
{
Find("2,3,5,6", "/*-+", 24);
}
public bool Find(string numbers, string operations, int total)
{
_count++;
var arr = numbers.Split(',');
if(arr.Length == 1 && Convert.ToInt32(arr[0]) == total)
{
return true;
}
for (int i = 0; i < operations.Length; i++)
{
for (int j = 0; j < arr.Length - 1; j++)
{
var a = Convert.ToInt32(arr[j]);
var b = Convert.ToInt32(arr[j+1]);
int newNumber = 0;
switch (operations[i])
{
case '+': { newNumber = a + b; } break;
case '-': { newNumber = a - b; } break;
case '/':
{
//newNumber = a / b;
if((a%b) == 0)
{
newNumber = a / b;
}
else
{
continue;
}
} break;
case '*': { newNumber = a * b; } break;
}
var result = Find(numbers.Replace($"{arr[j]},{arr[j+1]}", newNumber.ToString()), operations.Remove(i, 1), total);
//var result = Find(numbers.Replace($"{arr[j]},{arr[j+1]}", newNumber.ToString()), operations, total);
if(result)
{
_store.Push($"{a}{operations[i]}{b}");
return true;
}
}
}
return false;
}
}
}