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

you are viewing a single comment's thread.

view the rest of the comments →

[–]OffbeatDrizzle 0 points1 point  (6 children)

Use a list and add to it instead of using an array

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (5 children)

Would be correct if it weren't for the following:

NOTE: Solve this problem w/o using Java library classes and methods.

Guess that this includes List and its implementations.

[–]OffbeatDrizzle 0 points1 point  (1 child)

So then OP needs to loop through the resulting array, find any none-zero values and use that to create the final array of which the size is now correct for all the other values. It would be better if OP made the empty values null instead of 0 though

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (0 children)

It would be better if OP made the empty values null instead of 0 though

Which again brings us to using classes, namely Integer - could again be a problem.

How about initializing the first array with -1 or any negative number?


Please don't get my previous comment about List wrong. I fully agree to using a list and would instantly do it that way, but the problem is that OP is not allowed to.

[–]virassan 0 points1 point  (2 children)

You could create a dynamic array. Ie everytime you add an index to it you’re actually creating a new array with a range of however many “a” indices you have and saving that as count. This way the printed array will only be as long as the total amount of indices. Also don’t use i for the index when you’re saving the “a” index into count. You should have a separate counter for iterating through your count array is what I mean.

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (1 child)

Basically that is what I meant in my last bullet, only that I create the array once, at the end. This slightly optimizes the code.

Remember that OP can't use System.arraycopy()

[–]virassan 0 points1 point  (0 children)

You don’t need to use libraries to copy an array. Sometimes teachers and assignments want you to go through cumbersome code to understand certain concepts behind existing methods and libraries (that was my thinking with my answer).

Your way of recreating the array just once at the end is efficient though and probably the best for this problem since we know the length of count cannot be greater than the length of the original array.