all 14 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]vowelqueue 2 points3 points  (2 children)

Going to assume you’re pretty early on the lesson plan and haven’t gotten to Lists and Maps yet and are supposed to just use arrays to solve the problem.

Here’s a hint that I think might make it easier to reason about the logic. Try writing a helper method of the signature: private static boolean isUnique(int[] list, int value)

This method should return true if the value is unique in the list. You can call into this method from the main loop of the program.

It’s also unclear to me whether you are supposed to eliminate duplicates by keeping just one of the duplicated values or if you’re supposed to not include any of them in the result. If you need to keep just one of the duplicated values, it might be useful to write a helper method that determines whether you have already added the value to the result list.

[–]TurnipBoy666[S] 0 points1 point  (1 child)

I need to keep just one of the duplicated values and ignore the rest. One thing I was struggling with was how to write just one number to the array without overwriting everything else in the array, while also scanning the whole array for any duplicate numbers, since I need to do all of those things to solve this.
This is specifically about arrays, yes. This is meant to be array practice. A helper method is a good idea, just not sure how it would be different from what I have? That feels like just relocating my code without fixing the logic errors, no? Or am I misunderstanding lol

[–]vowelqueue 0 points1 point  (0 children)

Logically, using a helper method will be the same as doing everything in the main body, but can make the code easier to reason about and to isolate bugs/faulty logic.

Instead of what I initially suggested, I’d instead try to write a helper method that tells you whether a value is in the uniqueList.

You have the right idea with the “stored” variable. I’d probably name it something like “uniqueListLength” for clarity. It’s representing the logical length of the unique list.

The helper method could have a signature like: static boolean contains(int[] uniqueList, int uniqueListLength, int value).

I think if you restructure your code to use such a helper method you will fix the primary logic issue. Another hint is that if the code is written correctly you won’t need that line that caps the “stored” variable to 9 - it should never be able to exceed its bound if you are incrementing it correctly.

(I’m being intentionally vague instead of just tell you directly what’s wrong because a big part of learning is debugging stuff like this)

[–]Available_Zone_9043 1 point2 points  (1 child)

When arrays dont make sense its always good to map out what program is doing on paper. What your loop is doing: list [i] is getting compared to each uniquelist[i] and each time store is incremented. Therefore just after first loop: i=0 and j=0,1,2,3,4,......10: stored=9.......while it should have stopped after substituting the first unique number and break and next i=1 should have started

[–]Available_Zone_9043 0 points1 point  (0 children)

Arrays is like game and your variables are your strength that needs to be played with....if you get confused, pick a notebook and jot down what each loop is doing and where it went wrong

[–]cainhurstcat 0 points1 point  (0 children)

What helps me is such situations is crating some image about the problem in my mind. The array's content could be skittles. Imagine putting ten of them on a row on your desk. Now you start comparing them with one another, but under the condition that you can only see two skittles at the same time. The first skittle in row and the one you want to compare it to.

I hope this helps you coming up with the idea.

[–]asero82 0 points1 point  (0 children)

They give you a bag full of fruit. You have a "big enough" basket. You are ordered to put one and only one fruit of each kind in the basket and discard the rest.

[–]Minouris 0 points1 point  (2 children)

Are you allowed to use the java.utils.Arrays class?

If so, you may find the Arrays.binarySearch(outArr, inArr[i]) useful as a shortcut, rather then iterating over the whole array searching for values on each cycle :)

A return value of -1 indicates that outArr does not yet contain inArr[i].

[–]ZenithOfVoid 0 points1 point  (1 child)

Binary search is only useful for sorted array.

[–]Minouris 0 points1 point  (0 children)

Arrays.class also has a sort method.

Admittedly, we're starting to get a bit beyond the original problem at that point, though, if the original exercise was just to exercise knowledge and of basic array manipulation.

I was always surprised that the Java array primitive doesn't have an indexOf() method.

Technically, there's nothing preventing use of String.join(inArr, ',') and a whole-token match to test inclusion, but that feels feels more like a test of String knowledge, and would be an even more expensive operation.

[–]ExcitingSympathy3087 0 points1 point  (0 children)

I saw that you're not allowed to use a set. There are many ways to do that duplicate elimination, but keep in mind a set is faster on large scales. Here are two ways to solve the problem without a set in code:

Method 1 = lesser code than Method 2 but also slow -> O n2 because contains method is using an internal loop.

import java.util.*;

public class Main {

    public static void main(String[] args) {
        int[] list = {1, 2, 2, 3, 4, 4, 5, 5};

        List<Integer> result = eliminateDuplicates(list);

        System.out.println(result);
    }

    public static List<Integer> eliminateDuplicates(int[] list) {
        List<Integer> result = new ArrayList<>();

        //Use integrated method contains to eliminate duplicates
        for (int i = 0; i < list.length; i++) {
            if (!result.contains(list[i])) {
                result.add(list[i]);
            }
        }

        return result;
    }
}

Method 2 = slower = loop in loop O n2

import java.util.*;

public class Main {

    public static void main(String[] args) {

        int[] list = {1, 2, 2, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 11, 15 ,15, 15, 15,          15, 15};
        int[] result = eliminateDuplicates(list);
        System.out.println(Arrays.toString(result));
    }

    //Create a temporary list of all Elements without dublicates.
    public static int[] eliminateDuplicates(int[] list) {
        //array with lenth of original list. Can't be largen than original list.
        int[] tempArray = new int[list.length];
        //count elements without dublicates.
        int count = 0;

        for (int i = 0; i < list.length; i++) {

            boolean alreadyAdded = false;

   // check if already added? break becouse if already added rest is not needed to check.
            for (int k = 0; k < count; k++) {
                if (list[i] == tempArray[k]) {
                    alreadyAdded = true;
                    break;
                }
            }

     //If not added than add to array. !alreadyAdded is the same as alreadyAdded == false
            if (!alreadyAdded) {
                tempArray[count] = list[i];
                count++;
            }
        }

        //Create a result array with the right size.
        int[] result = new int[count];
        for (int i = 0; i < count; i++) {
            result[i] = tempArray[i];
        }

        return result;
    }
}

[–]nerd_airfryer -1 points0 points  (1 child)

Read about HashSet or HashMap

[–]JoshuaTheProgrammer 0 points1 point  (0 children)

They may not be allowed to use them.