Advertisement
Ms_Nenova

c# Arrays Subsets Sum of Length K

Jan 18th, 2013
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.41 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class CheckSubset
  5. {
  6.     static void findSubsets(int[] arr, List<int> newArray, int index, int S, int K)
  7.     {
  8.  
  9.         for (int i = index; i < arr.Length; i++)
  10.         {
  11.             int count = 0;
  12.             foreach (var item in newArray)
  13.             count += item;
  14.  
  15.             if ((arr[i] + count) == S)
  16.             {
  17.                 foreach (var item in newArray)
  18.                 if ((newArray.Count + 1) == K)
  19.                 {
  20.                     Console.Write("{0}, ", item);
  21.                     Console.Write("{0}, ", arr[i]);
  22.                     Console.WriteLine();
  23.                 }
  24.             }
  25.             newArray.Add(arr[i]);
  26.             findSubsets(arr, newArray, i + 1, S, K);
  27.             newArray.Remove(arr[i]);
  28.         }
  29.     }
  30.     static void Main()
  31.     {
  32.         Console.Write("Enter the number of elements in the array:");
  33.         int N = int.Parse(Console.ReadLine());
  34.         int[] arr = new int[N];
  35.         for (int i = 0; i < N; i++)
  36.         {
  37.             Console.Write("Enter an element:");
  38.             arr[i] = int.Parse(Console.ReadLine());
  39.         }
  40.         Console.Write("Enter the sum of subsets S:");
  41.         int S = int.Parse(Console.ReadLine());
  42.         Console.Write("Enter the length of the subset K:");
  43.         int K = int.Parse(Console.ReadLine());
  44.         findSubsets(arr, new List<int>(), 0 , S, K);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement