• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

How to delete every third element as a loop from an array?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Adding 6 numbers as 1,2,3,4,5,6
Need to remove values in loop with a difference of 2.

Desired Result : Removal of 3 in the first loop followed by 6 followed by 4 followed by 2 followed by 5 & at last by 1.

Here's my code:


Adding 6 numbers as 1,2,3,4,5,6
Need to remove values in loop with a difference of 2.

Desired Result : Removal of 3 in the first loop followed by 6 followed by 4 followed by 2 followed by 5 & at last by 1.

Here's my code:

while(array.length ! = 1)
{

   for(int i =2; i<array.length; i=i+2)
   {
        array = ArrayUtils.remove(array, i);
        System.out.println("Content of Array after removing an object : "
           + Arrays.toString(array));
   }              
}
Getting result as

Content of Array after removing an object : [1, 2, 4, 5, 6]

Content of Array after removing an object : [1, 2, 4, 5]

Content of Array after removing an object : [1, 2, 5]

Content of Array after removing an object : [1, 2]

thanks for help
 
Saloon Keeper
Posts: 4612
182
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Wang,

welcome to the Ranch and enjoy the stay!

In your while-loop your are testing for 'array.length != 1'. However, once your array is reduced to a length of 2, you enter an infinite loop. So change it to 'array.length > 2'. But as it is now, you wont get your array smaller than 2, since there is no third element.
 
Piet Souris
Saloon Keeper
Posts: 4612
182
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I forgot. When you come to [1, 2, 5], your next remove should be 2. Why not 5?
 
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch (again).

What is ArrayUtils? What does its remove() method do? I suspect it creates a new array with one element fewer, in which case it doesn't strictly speaking remove anything from an array. Since Java® arrays have a fixed size, it isn't possible to fulfil the strict definition of removal from an array. It is possible to create a new array, or to replace the element by 0/null/false.
As CareyPiet said, the outer loop is liable to degenerate into an infinite loop. Why have you got the outer loop at all?

[edit]Somebody pointed out I credited the wrong chap for some information. Sorry Piet.
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Generally you don't want to mutate a collection while you are iterating over it as you will get a ConcurrentModificationException. You may avoid that exception in the particular case of iterating over an array using an index, but you will invalidate your index when the array elements shift.

IMO, a much better approach is to consider the input collection (array) immutable and generate a new collection (array) consisting of only the elements you want to keep. A "filter" operation, available using Java8 streams.

It seems ArrayUtils is not in the Java standard library so I am not sure what the behavior is. If it returns a new array every time you remove a single element, that is grossly inefficient. Also, in Java an array cannot change length. Therefore both the index i and the .length property in the for loop here will "desync" from the underlying array as elements are removed.
 
Campbell Ritchie
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Damon McNeill wrote:Generally you don't want to mutate a collection while you are iterating over it as you will get a ConcurrentModificationException.  . . .

Not if you do it correctly with myIterator.remove(), and the collection supports removal. Collections which don't support removal will throw a different exception.

. . .  only the elements you want to keep. A "filter" operation, available using Java8 streams.

Please explain how filter() would work. Since filter() is usually used with a predicate on the element rather than its index, that is going to involve some very awkward programming.

. . . both the index i and the .length property in the for loop here will "desync" from the underlying array as elements are removed.

Agree; trying to remember indices like that will make for some very strange programming and will be very error‑prone, so your suggestion of copying elements to a new collection sounds much better.
 
Damon McNeill
Ranch Hand
Posts: 92
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My understanding is that only certain implementations of the List interface can support a remove() operation applied to any iterator of the List. It is the weird difference of Iterator<T> and ListIterator<T>. The major difference being essentially, the remove() operation on an iterator will generally be supported if the List is implemented via a linked list vs. an array.

With the array case the external iterators would be invalidated when modifying the underlying array (e.g., it is re-allocated in another area due to inserts or deletions)

With the linked list case, an iterator points to a fixed place in memory (i.e., the address of some node, rather than an offset from some address) and it is possible (with some finess) to NOT invalidate the iterator while supporting concurrent modification during iteration.

Yeah I retract my statement about the filter operation, it doesn't apply at all here )

 
Piet Souris
Saloon Keeper
Posts: 4612
182
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can use a filter, for instance:
 
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Piet:

Yikes to that being Beginning Java these days!

I just saw a brief overview of that technique "Streaming Over Indexes" in Part II of a Master Class taught by Stuart Marks:
https://www.youtube.com/watch?v=2c_KNH3s2S0

He was running out of time (last 12 minutes) so he rushed thru that part...I will remember it can be done, he warned a couple of times there are parts that are tricky to get right in the examples he did, which admittedly were slightly more complex.
 
Piet Souris
Saloon Keeper
Posts: 4612
182
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Working with indices has some advantages:

Every element is different
Integers are comparable and have a decent equals method
They form a consecutive series
And it is simplicity itself to map the results back to the original data

I use this in my permutation and subsequence methods, and some other.

What is the date of that video?
 
Jesse Silverman
Bartender
Posts: 1064
33
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think it was 2017, but they noted they presented that a bunch of times with slight differences in different places.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use Array#splice method to remove an element from the array. Where the first argument is defined as the index and second as the number elements to be deleted.

To remove elements at 3rd position use a while loop which iterates in backward and then delete the element based on the position.

 
Campbell Ritchie
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the Ranch

What language is that? That code won't work in Java®.
 
Damon McNeill
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It would be nice if there were support for an IndexedIterator<T>, where the IndexedIterator could both provide its value in addition to its position in the sequence. This would seem to obviate the need for the regular C-style indexed for-loop... I don't see why either an array, linked list, or stream based collection could not at least support this, its just a simple counter.
 
Campbell Ritchie
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please show an algorithm for the indices to remove every third element. That will show you that an indexed iterator isn't always quite as good an idea as you think.
I am by no means convinced it would obviate the use of a for loop, either. It is of course possible to write languages with only one kind of loop, the while loop.
 
Saloon Keeper
Posts: 24212
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't think anyone noted that in Java actual arrays are immutable. You can remove elements and shift the remaining ones, but you will end up with dead slots at the end of the array.

An "Array" done as a LinkedList collection is fairy easy to use the remove() method to excise elements as your iterate through the list.

An "Array" done as an ArrayList can likewise use the remove() method. As with the case of a true array, there will be dead space at the end, and while the ArrayList will not consider that as part of the official array, that unused space will be held by the ArrayList until its maxSize value is explicitly changed. At which point a new internal array will be allocated and all of the elements copied into it.

So for large arrays in particular, the best approach is to allocate a new array that's 1/3d the size of the original and simply copy from the original using a pattern of copy 2, skip 1.
 
Tim Holloway
Saloon Keeper
Posts: 24212
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mr. Ritchie has been kind enough to note that I got my fractions crossed. We are removing one out of 3 elements, so the target array should not be ⅓ the original array size, but instead ⅔ the original array size. And remember to round up.

As we say down here, you can't put 2 tons of fertilizer in a 1-ton truck.
 
Campbell Ritchie
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
. . . but in small towns here, farmers occasionally dump that second ton of “fertiliseer” outside the bank office. Maybe that is why the banks are closing their branches in so many small towns
 
Tim Holloway
Saloon Keeper
Posts: 24212
167
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:. . . but in small towns here, farmers occasionally dump that second ton of “fertiliseer” outside the bank office. Maybe that is why the banks are closing their branches in so many small towns



Well, suh, here in South Freedom Land, we would nevah condescend to spell "furt-uh-LIE-zah" in a way so inconformant with how it sounds.

But a bank is a bank, and so would agree heartily that it would be a proper home for manure.
 
Campbell Ritchie
Marshal
Posts: 73766
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tim Holloway wrote:. . . spell "furt-uh-LIE-zah" . . . .

Damn!
 
To avoid criticism do nothing, say nothing, be nothing. -Elbert Hubbard. Please critique this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic