TodorMitev

SubsetSum

Dec 23rd, 2011
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace _16SumInArray
  7. {
  8.     class SumInArray
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             Console.Write("Array size? = ");
  13.             int size = int.Parse(Console.ReadLine());
  14.             double[] array = new double[size];
  15.             Console.Write("Searched sum? = ");
  16.             double sum = double.Parse(Console.ReadLine());
  17.             for (int i = 0; i < array.Length; i++)
  18.             {
  19.                 Console.Write("arr[{0}]=", i);
  20.                 array[i] = double.Parse(Console.ReadLine());
  21.             }
  22.             int bestLen = 1;
  23.             int index = 0;
  24.             Array.Sort(array);
  25.             for (int i = 0; i < array.Length - 1; i++)
  26.             {
  27.                 int len = 1;
  28.                 double tempSum = array[i];
  29.                 int j = i + 1;
  30.                 while (j < array.Length && tempSum <= sum)
  31.                 {
  32.                     tempSum += array[j];
  33.                     len++;
  34.                     if (tempSum == sum)
  35.                     {
  36.                         index = i;
  37.                         bestLen = len;
  38.                     }
  39.                     j++;
  40.                 }
  41.             }
  42.             int count = 0;
  43.             while (count < bestLen)
  44.             {
  45.                 Console.Write("{0} ", array[index]);
  46.                 index++;
  47.                 count++;
  48.             }
  49.             Console.WriteLine();
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment