C++ program to find order of loading golds on weight scale without exploding it


Suppose we have an array A with n distinct elements, and another number x. There are n pieces of gold. The ith gold weight is A[i]. We will put this n pieces on weight scale one piece at a time. But the scale has an unusual defect: if the total weight on it is exactly x, it will explode. We have to check whether we can put all n gold pieces onto the scale in some order, without exploding the scale during the process. If we can, find that order. If not possible, mark "IMPOSSIBLE".

So, if the input is like A = [1, 2, 3, 4, 8]; x = 6, then the output will be [8, 1, 2, 3, 4], other orders are also valid

Steps

To solve this, we will follow these steps −

s := 0
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   s := s + A[i]
if s is same as x, then:
   return "IMPOSSIBLE"
s := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   s := s + A[i]
   if s is same as x, then:
      print A[i + 1], A[i]
      (increase i by 1)
      Ignore following part, skip to the next iteration
   print A[i]

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

void solve(vector<int> A, int x) {
   int s = 0;
   int n = A.size();
   for (int i = 0; i < n; i++) {
      s += A[i];
   }
   if (s == x) {
      cout << "IMPOSSIBLE";
      return;
   }
   s = 0;
   for (int i = 0; i < n; i++) {
      s += A[i];
      if (s == x) {
         cout << A[i + 1] << ", " << A[i] << ", ";
         i++;
         continue;
      }
      cout << A[i] << ", ";
   }
}
int main() {
   vector<int> A = { 1, 2, 3, 4, 8 };
   int x = 6;
   solve(A, x);
}

Input

{ 1, 2, 3, 4, 8 }, 6

Output

1, 2, 4, 3, 8,

Updated on: 03-Mar-2022

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements