1

I got a question today and tried but doesn't found an relevent solution. The question is:

Suppose we have a 2D array containing the name of city and total number of products. The name of city could repeat in the list.

Now what we have to do is

  1. Count the number of product sold in one city and save them in another 2d array having unique city name and total number of products sold.
  2. Print the second city having highest products sold.

A sample list could be for consideration is:

private static String[][] arr = new String[][]{
        {"New Delhi", "5000"},
        {"Chennai", "4300"},
        {"Goa", "2940"},
        {"New Delhi", "2003"},
        {"Kolkata", "8904"},
        {"Kerala", "8972"},
        {"New Delhi", "8922"},
        {"Chennai", "8217"},
        {"New Delhi", "2462"},
        {"Kolkata", "5564"},
        {"Kerala", "9934"},
        {"New Delhi", "100"},
        {"Kolkata", "892"},
        {"Kerala", "9406"},
        {"New Delhi", "2003"},
        {"Chennai", "1049"}
    };

Note: I already tried this question with Map Interface. Only looking for solution with Multidimensional Array

2
  • use a map with city as key and products as value, and you just add all the values foreach key together. At last convert that map to an array Commented Oct 27, 2017 at 13:29
  • Already given a try to map and was successful in implementing Map. Commented Oct 27, 2017 at 15:31

2 Answers 2

4

Use HashMap where key will be city and value will be the total count

  1. Iterate over the array
  2. If key exists, get the value of key and increment the count with new values
  3. If key doesn't exist, push the value.

Here is the basic idea:

if(dataMap.get(city)==null){
  dataMap.put(city,value);
 }
else{
 dataMap.put(city,value+dataMap.get(city));
}

You can do the same thing with array as well, but you will need to declare a new array where you will be adding count based on the similar city name. The appropriate data structure for this scenario is HashMap

Sign up to request clarification or add additional context in comments.

8 Comments

Java8 version could be a lot smaller: dataMap.compute(city, ( k, v ) -> v == null ? value : v + value);
@Lino use merge to make it even shorter: dataMap.merge(city, value, (oldV, newV) -> oldV + newV);
@MalteHartwig even better! I forgot about that
@Lino I was worried about how you make the hashmap keys (cities) occur only once, when you loop through a list where they occur multiple times. But I realized in the else block that city key overwrites the old city key. It is not a problem.
@Lealo no i think you understood me wrong, its just not possible to have 2 times the same key in a HashMap
|
0

Finally done that using 2d array and my code is

import java.util.Arrays;

/**
 *
 * @author Chirag
 */
public class Sampleh {

    private static final String[][] $DATA = new String[][]{
        {"New Delhi", "5000"},
        {"Chennai", "4300"},
        {"Goa", "2940"},
        {"New Delhi", "2003"},
        {"Kolkata", "8904"},
        {"Kerala", "8972"},
        {"New Delhi", "8922"},
        {"Chennai", "8217"},
        {"New Delhi", "2462"},
        {"Kolkata", "5564"},
        {"Kerala", "9934"},
        {"New Delhi", "100"},
        {"Kolkata", "892"},
        {"Kerala", "9406"},
        {"New Delhi", "2003"},
        {"Chennai", "1049"}
    };

    private static String[][] $result = new String[50][2];

    private static void action1() {
        outer:
        for (int i = 0; i < $DATA.length; i++) {
            String curCity = $DATA[i][0];
            Integer curProd = Integer.valueOf($DATA[i][1]);
            for (String[] city : $result) {
                if (city[0] == null) {
                    //for this loop
                    continue;
                }
                if (city[0].equals(curCity)) {
                    //for outer loop;
                    continue outer;
                }
            }
            for (int k = i; k < $DATA.length; k++) {
                if ($DATA[k][0].equals(curCity)) {
                    String n = $DATA[k][1];
                    if (n == null) {
                        n = "0";
                    }
                    curProd += Integer.valueOf(n);
                }
            }
            $result[i][0] = curCity;
            $result[i][1] = "" + curProd;
        }
        {
            //this code removes nulls from result array
            String[][] temp; //a temparory 2d array
            int counter = 0; //counts the num of values excluding nulls
            for (String[] res : $result) {
                if (res[0] == null) {
                    continue;
                }
                ++counter;
            }
            temp = new String[counter][2]; //redefine the temporary 2d array with size of values
            counter = 0;
            for (String[] res : $result) {
                if (res[0] == null) {
                    continue;
                }
                temp[counter][0] = res[0];
                temp[counter][1] = res[1];
                counter++;
            }
            $result = temp; //copy all values from temporary array to global result array
        }

        //prints the final array which is not sorted
        for (String[] r : $result) {
            System.out.println("City " + r[0] + " have " + r[1] + " products");
        }
    }

    private static void action2() {
        String[] cities = new String[$result.length];
        int[] products = new int[$result.length];
        int[] prodCopy = new int[$result.length];

        for (int i = 0; i < $result.length; i++) {
            cities[i] = $result[i][0];
            prodCopy[i] = Integer.valueOf($result[i][1]);
            products[i] = Integer.valueOf($result[i][1]);
        }

        Arrays.sort(products);

        for (int i = 0; i < products.length; i++) {
            int counter = -1;
            for (int p : prodCopy) {
                ++counter;
                if (p == products[i]) {
                    break; //breaks the loop to continue to other code without increasing counter
                }
            }
            $result[i][0] = cities[counter];
            $result[i][1] = "" + prodCopy[counter];
        }

        System.out.println("\nprinting full list sorted as counting of product");
        for (String[] k : $result) {
            System.out.println("City: " + k[0] + " have products " + k[1]);
        }

        int loc = $result.length - 2;
        System.out.println();
        System.out.println("Second highest City is '" + $result[loc][0] + "' having products '" + $result[loc][1] + "'");
        System.out.println();
    }

    public static void main(String... $results) {
        action1();
        action2();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.