[Java Code Snippet] The least amount of differences between two integer arrays of same size.

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
Code:
package main;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
 
public class Test {
   
    public static void main(String[] arg) {
        Random random = new Random();
        ArrayList<Integer> list1 = new ArrayList<Integer>();
       
        int temp;
        int listSize = random.nextInt(100);
        if (listSize % 2 != 0)
            listSize++;
       
        System.out.print("串列: ");
        for (int i = 0; i < listSize; i++) {
            temp = random.nextInt(10);
            if (temp < 0)
                temp *= -1;
            list1.add(temp);
            System.out.print(temp + " ");
        }
        System.out.println();
       
        Collections.sort(list1, new Comparator<Integer>() {
           
            @Override
            public int compare(Integer a, Integer b) {
                if (a > b)
                    return 1;
                if (a < b)
                    return -1;
                return 0;
            }
           
        });
       
        System.out.print("串列小到大: ");
        for (int i : list1) {
            System.out.print(i + " ");
        }
        System.out.println();
       
        int size = list1.size() / 2;
        ArrayList<Integer> sub1 = new ArrayList<Integer>();
        ArrayList<Integer> sub2 = new ArrayList<Integer>();
       
        int head = 0;
        int tail = list1.size() - 1;
        boolean flag = true;
       
        for (int i = 0; i < size; i++) {
            if (flag) {
                sub1.add(list1.get(head));
                sub1.add(list1.get(tail));
            }
            else {
                sub2.add(list1.get(head));
                sub2.add(list1.get(tail));
            }
            head++;
            tail--;
            flag = !flag;
        }
       
        int sum1 = 0;
        int sum2 = 0;
       
        System.out.print("A 串列: ");
        for (int i : sub1) {
            sum1 += i;
            System.out.print(i + " ");
        }
        System.out.println();
       
        System.out.print("B 串列: ");
        for (int i : sub2) {
            sum2 += i;
            System.out.print(i + " ");
        }
        System.out.println();
       
        System.out.println("A 串列: " + sum1 + "      B 串列: " + sum2);
        System.out.println("互減: " + (sum1 - sum2));
    }
}
 

Accname

2D-Graphics enthusiast
Reaction score
1,462
Is there any kind of question?
By the way, the (i guess) chinese letters make it kinda hard to read, lol.
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
Is there any kind of question?
By the way, the (i guess) chinese letters make it kinda hard to read, lol.

This code snippet was recycled from Facebook, where our class group is doing a routine cleaning. Since we're graduated, our group is being moved/merged with a larger group where us graduated students with Bachelor's degrees are all in.

The question, translated, involves two integer arrays, Array A and Array B, of size N. N must be an even number. The elements of both arrays are randomized integers. Find an algorithm that shows the smallest difference of the sum of Array A's elements and the sum of Array B's elements. If the difference is positive, Array A's sum is larger. And vice versa.

For example:

Array A: 0, 1, 2, 3
Array B: -1, 0, 1, 2

Sum of Array A: 6
Sum of Array B: 2

The smallest difference between Array A and Array B is 4. Try to obtain the lowest absolute value for this answer. Put a positive sign if Array A is larger, and put a negative sign if Array B is larger.
 

Accname

2D-Graphics enthusiast
Reaction score
1,462
"smallest" difference? I would say the difference is constant and nonambiguous.
Can you have like a "bigger" difference between 2 values?
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
"smallest" difference? I would say the difference is constant and nonambiguous.
Can you have like a "bigger" difference between 2 values?

Since both of the values are random, yes you can/may/might get it.

The point of the question is about creating an algorithm out from the results given. It didn't say how well your algorithm should be or anything else that may restrict it.

You can also try out the code snippet in Eclipse, after refactoring a few things, and just focus on the numbers.
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
I have no clue what this is.

Do you actually have a question about this code? Or did you post it for others to use?

And anyway, a difference is always greater or equal to 0. If sum2 > sum1 then the difference is negative. So you have to call Math.abs(sum1 - sum2) to get a 100% correct value.

And the code is pretty confusing. Not only because of Chinese letters, but the code itself has some issues imo.

1) Don't call your variable 'size' when it's not holding the size of a container. Call it something like 'halfSize' in your case.

2)
Code:
for (int i = 0; i < size; i++) {
    if (flag) {
        ...
    }
    else {
        ...
    }
    flag = !flag;
}
I'd be careful with this, you might end up killing your CPU's branch prediction with the alternation of the if's condition. Why not use 2 loops?
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
Well, I suck at translating the question into English. :( And I forgot some of the contexts behind all of this. :(

Especially the meaning of "difference". I thought difference means "subtraction", and it sounded better... :(

I'd be careful with this, you might end up killing your CPU's branch prediction with the alternation of the if's condition. Why not use 2 loops?

This is interesting, I've never heard of this before. It causes damage??
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
This is interesting, I've never heard of this before. It causes damage??

It doesn't damage your hardware.

But it could slow down your program.

The CPU is very good in executing a lot of stuff in a row. But when you have branching (like an if-statement) the CPU can't know beforehand whether it needs to run the then-part of the else-part of the if-statement.
So the CPU has to evaluate the if-statement before it can continue running.

That is what can make if-statements very slow. To optimize that, CPUs can "remember" the result of if-statements.
If you have an if-statement that is 'true' most of the time, the CPU will optimize for that case. You have faster program execution in the 'true' case and slower executing in the 'false' case.
But your if-statement alternates between 'true' and 'false' all the time, which can cause the prediction to fail a lot.
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
I don't know how to revise the code around then.

How do you insert 2 elements into array A, then another 2 (different) elements into Array B, and repeat until all elements have been exhausted from a large array, without killing the branch prediction?
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
If you only want 2 arrays with N random numbers, you can just do:

Code:
Random r = new Random();
ArrayList<Integer> sub1 = new ArrayList<>();
ArrayList<Integer> sub2 = new ArrayList<>();
 
int n = r.nextInt(50) * 2; //Multiplying by 2 is an easy way to only get even numbers.
 
for(int i=0; i<n; ++i){
    sub1.add( r.nextInt(10) );
    sub2.add( r.nextInt(10) );
}

Because I really don't get why you:
1) Create list1 and add integers to it
2) Sort list1
3) Add elements of list1 to sub1 and sub2
if you can just add random ints into sub1/sub2 immediately.

But if you have a reason why distribute the elements from list1 exactly why you did, this one should do the same:
Code:
int head = 0;
int tail = list1.size() - 1;
for (int i = 0; i < size; i++) {
    sub1.add(list1.get(head));
    sub1.add(list1.get(tail));
    head++;
    tail++;
    sub2.add(list1.get(head));
    sub2.add(list1.get(tail));
    head++;
    tail++;
}

But I still don't get why you sort the list, and then add the head and tail elements to other lists..
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
Code:
//Tails should be decrementing.
tail--;

But yeah, I didn't think straight when I was doing my job helping another classmate at 4AM... :p That completely blew my mind that I didn't think of this.

Wow...
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
You can make the summing easier too:
Code:
int sum1=0;
int sum2=0;
for(int i=0; i<n; ++i){
    sum1 += sub1.get(i);
    sum2 += sub2.get(i);
}

Or, if you don't care about the invidual sums, you can get the total sum easily:
Code:
int sum=0;
for(int i=0; i<n; ++i){
    sum += sub1.get(i) - sub2.get(i);
}
 

tom_mai78101

The Helper Connoisseur / Ex-MineCraft Host
Staff member
Reaction score
1,667
The fact is that you need to find the algorithm that makes the sums of both Array A and Array B so that when subtracted, the result should be as close to 0 as possible, and that both arrays must have randomized integer elements, is enough for me.
 

Accname

2D-Graphics enthusiast
Reaction score
1,462
Tom, I think what you mean is:
You are given a set of integer values;
find 2 subsets of the original set so that the sums of both subsets become equal (or as close to being equal then possible).
The partition problem if I remember correctly.

http://en.wikipedia.org/wiki/Partition_problem

The problem is NP complete.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1
  • The Helper The Helper:
    The recipe today is Sloppy Joe Casserole - one of my faves LOL https://www.thehelper.net/threads/sloppy-joe-casserole-with-manwich.193585/
  • The Helper The Helper:
    Decided to put up a healthier type recipe to mix it up - Honey Garlic Shrimp Stir-Fry https://www.thehelper.net/threads/recipe-honey-garlic-shrimp-stir-fry.193595/
  • The Helper The Helper:
    Here is another comfort food favorite - Million Dollar Casserole - https://www.thehelper.net/threads/recipe-million-dollar-casserole.193614/

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top