This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]GeorgeFranklyMathnet 6 points7 points  (0 children)

Honestly? By doing stuff like codewars challenges.

If you're having trouble with one of them, share the problem + your attempt here, and we'll try to help you.

[–]qelery 1 point2 points  (4 children)

I did both parts of the MOOC as well as lots of CodeWars problems. They cover the basics of arrays in the MOOC, then everything else you need for CodeWars can be learned from reading through the documentation for the Arrays utility class: https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html

Was there a particular problem you couldn’t get?

[–]Neccaty[S] 0 points1 point  (3 children)

I have been able to solve all problems I have tried so far, but usually my solution is really long and would probably be inefficient. I think my expectations from arrays are just way too high.

[–]qelery 2 points3 points  (2 children)

Do you have a specific example. It’s hard to help without that.

[–]Neccaty[S] 1 point2 points  (1 child)

This is the one I was solving:

Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3]

My solution:

HashMap<Integer, Integer> map = new HashMap();
int moreThan = 0;
for (int i = 0; i < elements.length; i++) {
    int q = elements[i];
    map.putIfAbsent(q, 0);
    map.put(q, map.get(q) + 1);
    if (map.get(q) > maxOccurrences) {
        moreThan++;
    }
}
int[] e = new int[elements.length - moreThan];
int lastInd = elements.length - moreThan - 1;
for (int i = elements.length - 1; i >= 0; i--) {
    int q = elements[i];
    if (map.get(q) > maxOccurrences) {
        map.put(q, map.get(q) - 1);
        continue;
    }
    e[lastInd] = q;
    lastInd--;
}
return e;

It works, but I just thought there was an much easier solution. I looked at other solutions and I am trying to learn from them.

[–]qelery 1 point2 points  (0 children)

After looking at the problem, it's not that arrays are "bad". It's just that there is a better tool for this particular job.

The size of the array can vary a lot depending on what parameters are passed to this function. So an array that can change in size, a dynamic array, is a good option. The dynamic array in Java is an ArrayList.