Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Linux
  • outsystems guide
  • Toggle search form
HackerRank Organizing Containers of Balls Problem Solution

HackerRank Organizing Containers of Balls

Posted on April 17, 2023April 19, 2023 By Yashwant Parihar No Comments on HackerRank Organizing Containers of Balls

In this post, we will solve HackerRank Organizing Containers of Balls Problem Solution.

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. The distribution of ball types per container are shown in the
following diagram.

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

The diagram below depicts a single swap operation.

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].

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
HackerRank Organizing Containers of Balls Problem Solution
HackerRank Organizing Containers of Balls Problem Solution

Table of Contents

  • Organizing Containers of Balls C Solution
  • Organizing Containers of Balls C++ Solution
  • Organizing Containers of Balls C Sharp Solution
  • Organizing Containers of Balls Java Solution
  • Organizing Containers of Balls JavaScript Solutions
  • Organizing Containers of Balls Python Solutions

Organizing Containers of Balls C Solution

#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 sum_rows[n];
    int sum_column[n];
    
    int i,j;
    
    i=0;
    
    while (i<n)
    {
       sum_rows[i]=0;
       j=0;
       while (j<n)
       {
           sum_rows[i]+=M[i][j];
           j++;
       }    
        
       i++; 
    }
    
        i=0;
    
    while (i<n)
    {
        sum_column[i]=0;
       j=0;
       while (j<n)
       {
           sum_column[i]+=M[j][i];
           j++;
       }    
        
       i++; 
    }  
    
     int key;
        
    i=1;
    
    while(i<n)
    {
        j=i-1;
        key=sum_column[i];
        
        while ((j>=0)&&(key>sum_column[j]))
        {
            sum_column[j+1]=sum_column[j];
            j--;
        }
        
        sum_column[j+1]=key;
        
        i++;
    }    
    
        
    i=1;
    
    while(i<n)
    {
        j=i-1;
        key=sum_rows[i];
        
        while ((j>=0)&&(key>sum_rows[j]))
        {
            sum_rows[j+1]=sum_rows[j];
            j--;
        }
        
        sum_rows[j+1]=key;
        
        i++;
    }        
        
     int possible=1;
        
     i=0;   
        
     while (i<n)
     {
         if (sum_rows[i]!=sum_column[i]) {possible=0;break;}
         
         i++;
     }    
        
        
     if (possible)  printf("Possible\n"); 
        else printf("Impossible\n"); 
        
    }
    

    return 0;
}

Organizing Containers of Balls C++ Solution

#include <cmath>
#include <cstdio>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;

void solve(int n){
    int **mat= new int*[n];
    for(int i=0;i<n;i++){
        mat[i]=new int[n];
    }
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            cin>>mat[i][j];
    set<int> c, b;
    for(int i=0;i<n;i++){
        int csum=0, bsum=0;
        for(int j=0;j<n;j++){
            csum+=mat[i][j];
            bsum+=mat[j][i];
        }
        c.insert(csum);
        b.insert(bsum);
    }
    if(c==b)cout<<"Possible"<<endl;
    else cout<<"Impossible"<<endl;
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int q, n;
    cin>>q;
    for(int i=0;i<q;i++){
        cin>>n;
        solve(n);
    }
    return 0;
}

Organizing Containers of Balls C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution 
{

    static void Main(String[] args) 
    {
        int q = Convert.ToInt32(Console.ReadLine());
        for(int a0 = 0; a0 < q; a0++)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int[][] M = new int[n][];
            for(int M_i = 0; M_i < n; M_i++)
            {
               string[] M_temp = Console.ReadLine().Split(' ');
               M[M_i] = Array.ConvertAll(M_temp,Int32.Parse);
            }
            int[] lengths = new int[n];
            int[] colorsCount = new int[n];
            for(int i = 0; i < n; i++)
            {
                int count = 0;
                for(int j = 0; j < M[i].Length; j++)
                {
                    colorsCount[j] += M[i][j];
                    count += M[i][j];
                }
                lengths[i] = count;
            }
            Array.Sort(lengths);
            Array.Sort(colorsCount);
            //for(int i = 0; i < lengths.Length; i++)
               // Console.WriteLine("{0}    {1}",lengths[i],colorsCount[i]);
            bool pos = true;
            for(int i = 0; i < n; i++)
                if(lengths[i] != colorsCount[i])
                {
                    Console.WriteLine("Impossible");
                    pos = false;
                    break;
                }
            if(pos)
                Console.WriteLine("Possible");
        }
    }
}

Organizing Containers of Balls Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'organizingContainers' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts 2D_INTEGER_ARRAY container as parameter.
     */

    public static String organizingContainers(List<List<Integer>> container) {
        // Write your code here
        int[] rowArr = new int[container.size()];
        for(int i = 0; i < container.size(); i++){
            List<Integer> row = container.get(i);
            for(int j = 0; j< row.size(); j++){
                rowArr[i] += row.get(j); 
            }
        }
        
        // for(int n: rowArr){
        //     System.out.println(n);
        // }
        
        
        int[] colArr = new int[container.size()];
        for(int j = 0; j< container.size(); j++){
            for(int i = 0; i<container.size(); i++){
                colArr[i] += container.get(j).get(i);
            }
        }
        
        
        // for(int n: colArr){
        //     System.out.println(n);
        // }
        
        Arrays.sort(rowArr);
        Arrays.sort(colArr);
        return Arrays.equals(rowArr, colArr)? "Possible":"Impossible";
        

    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int q = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, q).forEach(qItr -> {
            try {
                int n = Integer.parseInt(bufferedReader.readLine().trim());

                List<List<Integer>> container = new ArrayList<>();

                IntStream.range(0, n).forEach(i -> {
                    try {
                        container.add(
                            Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                                .map(Integer::parseInt)
                                .collect(toList())
                        );
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                });

                String result = Result.organizingContainers(container);

                bufferedWriter.write(result);
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Organizing Containers of Balls JavaScript Solutions

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 = [];
        for(M_i = 0; M_i < n; M_i++){
           M[M_i] = readLine().split(' ');
           M[M_i] = M[M_i].map(Number);
        }
        const ballTypesQty = new Array(n).fill(0);
        const ballTypesQtyInBascket = new Array(n).fill(0);
        
        for (let i = 0; i < M.length; i++) {
            for (let j = 0; j < M[i].length; j++) {
                ballTypesQty[j] = ballTypesQty[j] + M[i][j]
                ballTypesQtyInBascket[i] = ballTypesQtyInBascket[i] + M[i][j];
            }
        }
        ballTypesQty.sort();
        ballTypesQtyInBascket.sort();
        const string = ballTypesQty.every((item,index) => item === ballTypesQtyInBascket[index]) ? 'Possible' : 'Impossible';
        console.log(string)
    }

}

Organizing Containers of Balls Python Solutions

#!/bin/python3

import sys


q = int(input().strip())
for a0 in range(q):
    n = int(input().strip())
    M = []
    sums = dict()
    for M_i in range(n):
        M_t = [int(M_temp) for M_temp in input().strip().split(' ')]
        M.append(M_t)
    # your code goes here
    rowsum = [sum(x) for x in M]
    colsum = [sum(x[i] for x in M) for i in range(n)]

    for x in rowsum:
        if sums.get(x,-1) == -1:
            sums[x] = 1
        else:
            sums[x] += 1
    for y in colsum:
        if sums.get(y,-1) == -1 or sums[y] == 0:
            print('Impossible')
            break
        else:
            sums[y] -= 1
    else:
        print('Possible')
    
        
    

Other Solutions

  • HackerRank Encryption Problem Solution
  • HackerRank Bigger is Greater Problem Solution
c, C#, C++, HackerRank Solutions, java, javascript, python Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank Taum and B’day Problem Solution
Next Post: HackerRank Encryption Problem Solution

Related Posts

Javascript project for practice | Github User Information javascript
HackerRank Build a Palindrome Problem Solution HackerRank Build a Palindrome Problem Solution c
HackerRank Jumping on the Clouds: Revisited Problem Solution HackerRank Jumping on the Clouds: Revisited c
HackerRank CamelCase Problem Solution HackerRank CamelCase Problem Solution c
HackerRank Two Strings Problem Solution HackerRank Two Strings Problem Solution c
HackerRank Grading Students Problem Solution HackerRank Grading Students Problem Solution c

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme