Advertisement
Klaxon

[C# Arrays] Subset and Sum in Array

Sep 30th, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. // 17. * Write a program that reads three integer numbers N, K and S and an array of N elements from the console. Find in the array a subset of K elements that have sum S or indicate about its absence.
  2.  
  3. using System;
  4.  
  5. class SubsetAndSumInArray
  6. {
  7.     static void Main()
  8.     {
  9.         // Get N, K, S numbers
  10.         Console.Write("Enter N: ");
  11.         int n = int.Parse(Console.ReadLine());
  12.         Console.Write("Enter K: ");
  13.         int k = int.Parse(Console.ReadLine());
  14.         Console.Write("Enter S: ");
  15.         int s = int.Parse(Console.ReadLine());
  16.  
  17.         int[] array = new int[n];
  18.  
  19.         // help variables
  20.         int counter = 0;
  21.         string subset = "";
  22.  
  23.         for (int i = 0; i < n; i++)
  24.         {
  25.             Console.Write("Index {0}: ", i);
  26.             array[i] = int.Parse(Console.ReadLine());
  27.         }
  28.  
  29.         int maxSubset = (int)Math.Pow(2, n);
  30.  
  31.         // main magic
  32.         for (int i = 0; i < n; i++)
  33.         {
  34.             subset = "";
  35.             long checkingSum = 0;
  36.             int lenCounter = 0;
  37.  
  38.             for (int j = 0; j <= n; j++)
  39.             {
  40.                 int mask = 1 << j;
  41.                 int nAndMask = i & mask;
  42.                 int bit = nAndMask >> j;
  43.  
  44.                 if (bit == 1)
  45.                 {
  46.                     checkingSum = checkingSum + array[j];
  47.                     subset = subset + " " + array[j];
  48.                     lenCounter++;
  49.                 }
  50.             }
  51.  
  52.             // printing
  53.             if (checkingSum == s && lenCounter == k)
  54.             {
  55.  
  56.                 Console.WriteLine("Number of subest that have the sum of: {0}", s);
  57.                 counter++;
  58.                 Console.WriteLine("This subset has a sum of {0} : {1} ", s, subset);
  59.             }
  60.         }
  61.         Console.WriteLine(counter);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement