-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanSum.cs
98 lines (78 loc) · 2.45 KB
/
canSum.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter your targetSum");
double targetSum;
string input;
try
{
input = Console.ReadLine();
if (!double.TryParse(input, out targetSum))
{
Console.WriteLine("Invalid input. Please enter a valid double value.");
return;
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
return;
}
Console.WriteLine("enter your array separated by spaces");
string arr;
string[] numberStrings;
double[] numbers;
try
{
arr = Console.ReadLine();
numberStrings = (arr ?? "").Split(' ');
numbers = new double[numberStrings.Length];
for (int i = 0; i < numberStrings.Length; i++)
{
if (!double.TryParse(numberStrings[i], out numbers[i]))
{
Console.WriteLine($"Invalid input '{numberStrings[i]}'. Please enter a valid double value.");
return;
}
}
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
Dictionary<double, bool> memo = new Dictionary<double, bool>();
CanSum problem = new CanSum(targetSum, numbers, memo);
Console.WriteLine(problem.seeCanSum());
}
}
public class CanSum
{
public double targetSum;
public double[] numbers = { };
public Dictionary<double,bool> memo = new Dictionary<double,bool>();
public CanSum(double targetSum, double[] numbers, Dictionary<double,bool> memo)
{
this.targetSum = targetSum;
this.numbers = numbers;
this.memo= memo;
}
public bool seeCanSum()
{
if (memo.ContainsKey(this.targetSum)) { return memo[targetSum]; }
if( targetSum == 0 ) { return true; }
if (targetSum < 0 ) { return false; }
foreach ( double x in numbers )
{
double remainder = targetSum - x;
CanSum remainderSum = new CanSum(remainder, numbers, memo);
if( remainderSum.seeCanSum() == true ) {
memo[targetSum] = true;
return true;
};
}
memo[targetSum] = false;
return false;
}
}