Advertisement
stoianpp

arrays6

Dec 12th, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. //Write a program that reads two integer numbers N and K and an array of N elements from the console.
  2. //Find in the array those K elements that have maximal sum.
  3.  
  4. using System;
  5. class MaxSumKofN
  6. {
  7.     static void Main()
  8.     {
  9.         Console.Write("Enter the array length: ");
  10.         int length = int.Parse(Console.ReadLine());
  11.         int[] array = new int[length];
  12.         Console.Write("Enter the number of elements for finding the max sum: ");
  13.         int elements = int.Parse(Console.ReadLine());
  14.         int combinations = (int)Math.Pow(2,length);
  15.         long totalSum = 0;
  16.         int[] members = new int[length];
  17.         for (int i = 0; i < length; i++)
  18.         {
  19.             Console.Write("Enter elements[{0}] value: ", i + 1);
  20.             array[i] = int.Parse(Console.ReadLine());
  21.         }
  22.  
  23.         for (int i = 1; i <= combinations; i++)
  24.         {
  25.             int count1s = 0;
  26.             for (int g = 0; g < length; g++)
  27.             {
  28.                 if ((i & (1 << g)) != 0) count1s++;
  29.             }
  30.             if (count1s == elements)
  31.             {
  32.                 int sum = 0;
  33.                 for (int g = 0; g < length; g++)
  34.                 {
  35.                     if ((i & (1 << g)) != 0)
  36.                     {
  37.                         sum += array[g];
  38.                     }
  39.                 }
  40.                 if (sum > totalSum)
  41.                 {
  42.                     totalSum = sum;
  43.                     for (int k = 0; k < length; k++) members[k] = 0;
  44.                     for (int g = 0; g < length; g++)
  45.                     {
  46.                         if ((i & 1 << g) != 0)
  47.                         {
  48.                             members[g] = 1;
  49.                         }
  50.                     }
  51.                 }
  52.             }
  53.         }
  54.         Console.Write("The {0} elements in the array with MaxSum {1} are: ", elements,totalSum);
  55.         for (int i = 0; i < length; i++)
  56.         {
  57.             if(members[i] == 1) Console.Write("{0}  ",array[i]);
  58.         }
  59.         Console.WriteLine();
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement