FIND 4 NUMS IN ARRAY WHOSE SUM EQUALS GIVEN NUM
namespace Find4NumsInArraywhoseSumEqualsGivenNum
{
class pair
{
public int i;
public int j;
public pair(int i, int j)
{
this.i = i;
this.j = j;
}
}
class Program
{
static void Main(string[] args)
{
List<int> li =new List<int>();
li.Add(1);
li.Add(2);
li.Add(3);
li.Add(4);
li.Add(5);
li.Add(6);
li.Add(7);
li.Add(8);
Dictionary<int,pair> Sums = new Dictionary<int,pair>();
int sum = 18;
for (int i = 0; i < li.Count; i++)
{
for (int j = i + 1; j < li.Count; j++)
{
int tempsum = li[i] + li[j];
int remainingsum = sum - tempsum;
if (Sums.ContainsKey(remainingsum))
Console.WriteLine(li[i] + " " + li[j] + " " + li[Sums[remainingsum].i] + " " + li[Sums[remainingsum].j]);
}
for (int k = 0; k < i; k++)
Sums[li[i] + li[k]] = new pair(i, k);
}
}
}
}
No comments:
Post a Comment