HackerRank Organizing Containers of Balls Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Organizing Containers of Balls Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank Organizing Containers of Balls Solution
HackerRank Organizing Containers of Balls Solution

HackerRank Organizing Containers of Balls

Task

David has several containers, each with a number of balls in it. He has just enough containers to sort each type of ball he has into its own container. David wants to sort the balls using his sort method.

David wants to perform some number of swap operations such that:

  • Each container contains only balls of the same type.
  • No two balls of the same type are located in different containers.

Example

containers = [[1, 4], [2, 3]]

David has n = 2 containers and 2 different types of balls, both of which are numbered from 0 to n – 1 = 1.

In a single operation, David can swap two balls located in different containers.

In this case, there is no way to have all green balls in one container and all red in the other using only swap operations. Return Impossible.

You must perform q queries where each query is in the form of a matrix, M. For each query, print Possible on a new line if David can satisfy the conditions above for the given matrix. Otherwise, print Impossible.

Function Description

Complete the organizingContainers function in the editor below.

organizingContainers has the following parameter(s):

  • int containter[n][m]: a two dimensional array of integers that represent the number of balls of each color in each container

Returns

  • string: either Possible or Impossible

Input Format

The first line contains an integer q, the number of queries.

Each of the next q sets of lines is as follows:

  1. The first line contains an integer n, the number of containers (rows) and ball types (columns).
  2. Each of the next n lines contains n space-separated integers describing row containers[i].

Constraints

  • 1 <= q <= 10
  • 1 <= n <= 100
  • 0 <= containers[i][j] <= 109

Scoring

  • For 33% of score, 1 <= n <= 10.
  • For 100% of score, 1 <= n <= 100.

Output Format

For each query, print Possible on a new line if David can satisfy the conditions above for the given matrix. Otherwise, print Impossible.

Sample Input 0

2
2
1 1
1 1
2
0 2
1 1

Sample Output 0

Possible
Impossible

Explanation 0

We perform the following q=2 queries:

  1. The diagram below depicts one possible way to satisfy David’s requirements for the first query: image
    Thus, we print Possible on a new line.
  2. The diagram below depicts the matrix for the second query: image
    No matter how many times we swap balls of type t0 and t1 between the two containers, we’ll never end up with one container only containing type t0 and the other container only containing type t1. Thus, we print Impossible on a new line.

Sample Input 1

2
3
1 3 1
2 1 2
3 3 3
3
0 2 1
1 1 1
2 0 0

Sample Output 1

Impossible
Possible

HackerRank Organizing Containers of Balls Solution

HackerRank Organizing Containers of Balls Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int q; 
    scanf("%d",&q);
    for(int a0 = 0; a0 < q; a0++){
        int n; 
        scanf("%d",&n);
        int M[n][n];
        for(int M_i = 0; M_i < n; M_i++){
           for(int M_j = 0; M_j < n; M_j++){
              
              scanf("%d",&M[M_i][M_j]);
           }
        }
        
        int x[n], y[n], i, j, k;
     
        for(i=0; i<n; i++){
            x[i] = 0;
            y[i] = 0;
        }
        
        for(i=0; i<n; i++){
            for(j=0; j<n; j++){
                x[i] = x[i] + M[i][j];
            }
        }
        
        for(i=0; i<n; i++){
            for(j=0; j<n; j++){
                y[i] = y[i] + M[j][i];
            }
            
            for(k=0; k<n; k++){
                if(y[i] == x[k]){
                    x[k] = -1;
                    
                } 
            }}
        int flag = 0;
            
        for(i=0; i<n; i++){
            if(x[i] != -1) flag = 1;
        }
        
        if(flag == 1) printf("Impossible\n");
        else printf("Possible\n");
            
        
        // your code goes here
    }
    return 0;
}

HackerRank Organizing Containers of Balls Solution in Cpp

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main(){
    int q;
    cin >> q;
    for(int a0 = 0; a0 < q; a0++){
        int n;
        cin >> n;
        vector< vector<int> > M(n,vector<int>(n));
        long long totalIn[101]={0},totalOf[100]={0};
        for(int M_i = 0;M_i < n;M_i++){
           for(int M_j = 0;M_j < n;M_j++){
              cin >> M[M_i][M_j];
               totalIn[M_i]+=M[M_i][M_j];
               totalOf[M_j]+=M[M_i][M_j];
           }
        }
        sort(totalIn,totalIn+100);
        sort(totalOf,totalOf+100);
        int i;
        for(i=0;i<100;i++)
            {
            if(totalIn[i]!=totalOf[i])
                break;
        }
        if(i==100)
            cout<<"Possible"<<endl;
        else
            cout<<"Impossible"<<endl;
        // your code goes here
    }
    return 0;
}

HackerRank Organizing Containers of Balls Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            int n = in.nextInt();
            int[][] M = new int[n][n];
            for(int M_i=0; M_i < n; M_i++){
                for(int M_j=0; M_j < n; M_j++){
                    M[M_i][M_j] = in.nextInt();
                }
            }
            int[] rt = new int[n];
            int[] ct = new int[n];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    rt[i] += M[i][j];
                    ct[j] += M[i][j];
                }
            }
            Arrays.sort(rt);
            Arrays.sort(ct);
            String ans = "Possible";
            for (int i = 0; i < n; i++) {
                if (rt[i] != ct[i])
                    ans = "Impossible";
            }
            System.out.println(ans);
        }
    }
}

HackerRank Organizing Containers of Balls Solution in Python

#!/bin/python

import sys


q = int(raw_input().strip())
for a0 in xrange(q):
    n = int(raw_input().strip())
    M = []
    for M_i in xrange(n):
        M_temp = map(int,raw_input().strip().split(' '))
        M.append(M_temp)
    ballcounts = {}
    for j in xrange(n):
        s = 0
        for i in xrange(n):
            s += M[i][j]
        if s in ballcounts:
            ballcounts[s] += 1
        else:
            ballcounts[s] = 1
    
    conts = {}
    for i in xrange(n):
        s = 0
        for j in xrange(n):
            s += M[i][j]
        if s in conts:
            conts[s] += 1
        else:
            conts[s] = 1    
    poss = True
    #for x in ballcounts:
    #    if ballcounts[x] % 2 == 1:
    #        poss = False
    for x in ballcounts:
        if not (x in conts):
            poss = False
            break
        if conts[x] != ballcounts[x]:
            poss = False
            break
    for x in conts:
        if not (x in ballcounts):
            poss = False
            break
        if conts[x] != ballcounts[x]:
            poss = False
            break
    if (poss):
        print "Possible"
    else:
        print "Impossible"

HackerRank Organizing Containers of Balls Solution using JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var q = parseInt(readLine());
    for(var a0 = 0; a0 < q; a0++){
        var n = parseInt(readLine());
        var M = [];
        var contTotals = [];
        var typeTotals = [];
        for(M_i = 0; M_i < n; M_i++){
            contTotals[M_i] = 0;
            typeTotals[M_i] = 0;
           M[M_i] = readLine().split(' ');
           M[M_i] = M[M_i].map(Number);
        }
        
        for (var type_i = 0; type_i < n; type_i++) {
            for (var cont_i = 0; cont_i < n; cont_i++) {
                contTotals[cont_i] += M[cont_i][type_i];
                typeTotals[type_i] += M[cont_i][type_i];
            }
        }
        contTotals.sort();
        typeTotals.sort();
        var failed = false;
        for (var i = 0; i < n; i++) {
            if (contTotals[i] != typeTotals[i]) {
                failed = true;
                break;
            }
        }
        if (failed == false)
            console.log("Possible");
        else
            console.log("Impossible");
    }

}

HackerRank Organizing Containers of Balls Solution in Scala

object Solution {

    def main(args: Array[String]) {
        val sc = new java.util.Scanner (System.in);
        var q = sc.nextInt();
        var a0 = 0;
        while(a0 < q){
            var n = sc.nextInt();
            var M = Array.ofDim[Int](n,n);
            var N = Array.ofDim[Int](n,n);
            for(M_i <- 0 to n-1) {
               for(M_j <- 0 to n-1){
                  M(M_i)(M_j) = sc.nextInt();
                  N(M_j)(M_i) =  M(M_i)(M_j) 
               }
            }
            // your code goes here
            val conSizes = M.map(x=>x.sum).sorted
            //conSizes.map(x=>println(x))
            val typSizes = N.map(x=>x.sum).sorted
            //typSizes.map(x=>println(x))
            if(conSizes.deep==typSizes.deep){
                println("Possible")
            }else{
                println("Impossible")
            }
            
            
            a0+=1;
        }
    }
}

HackerRank Organizing Containers of Balls Solution in Pascal

type arr=array[1..100]of int64;
var q,n,i,j:longint; b:int64;
    c,t:arr;
    
procedure sort(var a:arr; l,r:longint);
var i,j:longint; x:int64;
begin
  if l>=r then exit;
  i:=l; j:=r; x:=a[(l+r) div 2];
  repeat
    while a[i]<x do inc(i);
    while a[j]>x do dec(j);
    if i<=j then
    begin
      if i<j then
      begin
        a[i]:=a[i]+a[j];
        a[j]:=a[i]-a[j];
        a[i]:=a[i]-a[j]
      end;
      inc(i); dec(j)
    end
  until i>j;
  sort(a,l,j); sort(a,i,r)
end;
    
begin
  read(q);
  for q:=q downto 1 do
  begin
    read(n);
    fillchar(c,sizeof(c),0);
    fillchar(t,sizeof(t),0);
    for i:=1 to n do
      for j:=1 to n do
      begin
        read(b);
        inc(c[i],b);
        inc(t[j],b)
      end;
    sort(c,1,n); sort(t,1,n);
    for i:=1 to n do
      if c[i]<>t[i] then
      begin
        writeln('Impossible');
        break
      end
      else if i=n then
        writeln('Possible')
  end
end.

Disclaimer: This problem (Organizing Containers of Balls) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

Sharing Is Caring