• Post Reply Bookmark Topic Watch Topic
  • New Topic

A Better way of doing this  RSS feed

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question - Given an specific integer and an array of integers, find and remove all occurrences of the given integer and return an amended array.

I solved it. Here is my solution -



Is there a better way to do it? Please suggest
 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dan,
That looks fine. You might want to skip outputting the 0 elements at the end.

In the real world, the better way of doing this is to use an ArrayList. But you are understandably not allowed to do that in the assignment.
 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another way would be to take the members of the input array which you want to keep, and copy only them to a new array. Try writing that code and then see if you think it's better.

By the way the code you posted puts zeroes into the result. Is that allowed? Shouldn't the amended array be shorter? I have to mention this, your problem statement doesn't say whether you're allowed to return an array which has numbers which weren't in the input array. (Besides which you appear to assume that zero isn't going to be in the input array.)
 
Ranch Hand
Posts: 924
9
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My humble proposal...


 
Dan Foster
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Paul - What can i move instead of 0 in the vacant places? I cannot shrink an existing array.

But in that way i will have to use another array in which I move the rest items since i cant shorten an already existing array. Cant it be done using a single array?
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dan Foster wrote:Is there a better way to do it? Please suggest

Well, there is what Paul suggested. However, if you want to do this removal in place, then my advice would be to keep track of how many elements have been "removed" and shift all the others according to that value. That way you only move those elements that need moving, and you only move them once.

Your current code shifts all remaining elements (which might also include ones you want to remove) 1 position left - ie, it works rather like ArrayList.remove(int).

Winston
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!