0
\$\begingroup\$

I wrote a code and the code counts the number of identical elements between the arrays s and d at the same index. I need to optimize the code for speed and readability. I tried HashSet but it didn't work at all. Do you have any Suggestions?

public static void main (String[] args) throws java.lang.Exception
    { Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();

        while (t-- > 0) {

            int a = sc.nextInt(); //

            int count = 0;
            int s[] = new int[a];
            int d[] = new int[a];

            for (int i = 0; i < a; i++) {
                s[i] = sc.nextInt();

            }
            for (int j = 0; j < a; j++) {


                d[j] = sc.nextInt();
            }

            for (int i = 0; i < a; i++) {

                    if (s[i] == d[i]) {

                        count++;
                       
                    }


                }


            System.out.println(count);
        }
    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ You get better answers if you ask better questions. My answer and Justin's answer improve on the code as provided, greybeard's discusses a more general approach. The question is whether the code you provided, which reads input as 1) number of sets 2) size of this set 3) first list of numbers 4) second list of numbers 5) continue from 2 is the model you want/have to work with or just a way of producing the lists, but you want a general answer - the best answer is very much dependent on this. \$\endgroup\$ Commented Aug 3, 2023 at 10:31
  • 1
    \$\begingroup\$ (@MarkBluemel 1) number of lengths & pairs of sequences, actually, or #test cases.) \$\endgroup\$
    – greybeard
    Commented Aug 3, 2023 at 12:47

4 Answers 4

3
\$\begingroup\$

You don't need the third "for" loop do you? Nor do you really need the second array. Think about it...

\$\endgroup\$
1
\$\begingroup\$

You are getting suggestions to not compare two arrays due to the way you coded count the number of identical elements between the arrays 's' and 'd' at the same index.

Generally, put business logic in its own procedure:
You get to name and document procedure and parameters.

    /** @return the count of identical elements at the same index 
     * in <code>int</code> arrays <code>a</code> and <code>b</code>. */
    int countOfIdenticalElementsAtSameIndex(int[] a, int[] b) {
        return countOfIdenticalElementsAtSameIndex(a, b, Integer.MAX_VALUE);
    }
    /** @return the count of identical elements at the same index 
     * in <code>int</code> arrays <code>a</code> and <code>b</code>, 
     * for 0 <= index < <code>limit</code>.
     */
    int countOfIdenticalElementsAtSameIndex(int[] a, int[] b, int limit) {
        if (null == a || null == b)
            return 0;
        int count = 0;
        limit = Math.min(Math.min(a.length, b.length), limit)
        for (int i = 0 ; i < limit ; i++)
            if (a[i] == b[i])
                count += 1;
        return count;
    }
\$\endgroup\$
3
  • \$\begingroup\$ I read both ++i and i++ on their own as next i, and i++ was there in K&R. I use += 1 where I think increase by 1 - code the way you think. \$\endgroup\$
    – greybeard
    Commented Aug 3, 2023 at 7:36
  • \$\begingroup\$ I (and probably most people) would find if (a == null || b == null) more readable. The only time Yoda expressions might have a purpose in Java is when testing Boolean variables. That's the only time you might inadvertently use = instead of == and still be able to compile the line. \$\endgroup\$
    – k314159
    Commented Aug 3, 2023 at 13:58
  • 1
    \$\begingroup\$ (@k314159 I did mention habits from C days.) \$\endgroup\$
    – greybeard
    Commented Aug 3, 2023 at 14:03
1
\$\begingroup\$
  • (Said already) here you need only the first array.
  • You do not separate the tasks of first reading and then comparing. It would be nice if you could already create functions, "methods."
  • Testing the speed of the application can only sensibly be done redirecting a file to System.in as in java MyClass <data.txt. As keyboard input cannot be measured. Then one would see that Scanner has a bit overhead.
  • The main thing here is the style, readability. count can be introduced after reading the data here.

Then a tip: you are using an array style introduced to let Java look more like C and C++:

int a[] = ...

But more logical is keeping the type parts together:

int[] a = ...

The C compatibility syntax is a dead giveaway of a new inexperienced developer.

I would have liked to see:

int length = scanner.nextInt();
int[] first = readArray(scanner, length);
int[] second = readArray(scanner, length);
int same = identical(first, second);
System.out.println(...);

There is not much to optimize here.

You could have chosen to read two lines of text, each containing one array.

\$\endgroup\$
1
\$\begingroup\$

The structure of the input is not readily apparent from the example, so I wasn't able to rigorously test my changes.
Several ideas:

  • make the indentation / spacing consistent
  • use for instead of while when the number of iterations is known
  • use (++i) instead of (i++) if you only need the incremented value
  • use the same iterator name for the same depth of loop nesting (i, j)
  • reduce the number of loops by storing only the first half of each subarray
  • braces are optional for single statements
public static void main (String[] args) throws java.lang.Exception
{ 
    Scanner sc = new Scanner(System.in);
    int m = sc.nextInt();

    for (int i = 0; i < m; ++i) 
    {
        int n = sc.nextInt();
        int count = 0;
        int first_half[] = new int[n];

        for (int j = 0; j < n; ++j) 
            first_half[j] = sc.nextInt();

        for (int j = 0; j < n; ++j)
            if (first_half[j] == sc.nextInt()) 
                ++count;

        System.out.println(count);
    }
}

Hope that helps. It would be tough to optimize further; look at java.util.Arrays line 787 and you'll see that they aren't much fancier.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Thank you so much for the great explanation, Justin. \$\endgroup\$ Commented Aug 2, 2023 at 17:08
  • 1
    \$\begingroup\$ I get storing only half as much. I still don't understand storing only the first half of each subarray - the first array from each test-case? \$\endgroup\$
    – greybeard
    Commented Aug 4, 2023 at 4:36
  • \$\begingroup\$ Sorry, that is what I meant. You are correct. \$\endgroup\$ Commented Aug 10, 2023 at 0:51

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.