r/javahelp • • Feb 25 '20

How do I modify a character array in place?

I am trying to replace the characters in an array with their frequency.

For example, ['a', 'a', 'b'] should become ['a', '2', 'b', '1'].

I'm finding this quite difficult to do, since Java arrays cannot shrink or expand at runtime and this needs to be done in-place, without extra space.

17 Upvotes

12 comments sorted by

5

u/96dpi Feb 25 '20

You may want to use an ArrayList instead. You can change the size of an ArrayList.

1

u/[deleted] Feb 25 '20

Well, I couldn't use an ArrayList even if I wanted to, I've got to return the same array I get with the modifications.

2

u/darksounds Extreme Brewer Feb 25 '20

Is the array provided long enough to hold the results? That seems like the type of assumption that would be provided if this is a homework assignment.

1

u/[deleted] Feb 25 '20

That depends. Another example of that type could be ['a', 'a', 'a', 'b', 'c', 'c']. Since some elements would always be more than others, we can assume that it's just long enough (or longer) to store the results and we'd return ['a', '3', 'b', '1', 'c', '2']. In this case they're just equal.

3

u/darksounds Extreme Brewer Feb 25 '20

Please provide the text of your assignment. We can't help you figure out what they want you to do from your own analysis of text we can't see, since the problem probably lies in that analysis.

1

u/[deleted] Feb 25 '20

8

u/darksounds Extreme Brewer Feb 25 '20

Ahhhh, that makes sense.

So the answer to [a, a, b] should be [a, 2, b], not [a, 2, b, 1].

There's your issue. The problem states: The length after compression must always be smaller than or equal to the original array.

4

u/darksounds Extreme Brewer Feb 25 '20

I pointed it out in a reply below, but I'm going to post it here so it can be more easily found.

You're not actually trying to replace the characters with their frequency, you're trying to compress the array, as per this leetcode problem.

['a', 'a', 'b'] should become ['a', '2', 'b'] so as to fit inside the original array.

Take a look at example 3 to understand this a little better.

1

u/[deleted] Feb 26 '20

Got it.

6

u/PhantomOTOpera Feb 25 '20

You're correct. Arrays are not dynamic (they can't change size). If you need more space, you should create a new array with a bigger size each time you want to add a new element and then add the new element to the larger array.

1

u/[deleted] Feb 25 '20

Could you explain 'creating a new array each time' ? How would I modify the original array using this new one?

7

u/PhantomOTOpera Feb 25 '20

You can't modify the original array. Once you create an array in java its permanent (in terms of size, the contents may still change). Creating a new array works just like you would create the first array

char[] x = new char[4]; // or whatever size you need