I'm trying to do some pratice problems in the book and here is one of them. THIS...

Free

70.2K

Verified Solution

Question

Programming

I'm trying to do some pratice problems in the book and here isone of them.

THIS IS FOR JAVA.

Write a method cleanCorruptData that accepts an ArrayList ofintegers and removes any adjacent pair of integers in the list ifthe left element of the pair is smaller than the right element ofthe pair. Every pair's left element is an even-numbered index inthe list, and every pair's right element is an odd index in thelist. For example, suppose a variable called list stores thefollowing element values: [3, 7, 5, 5, 8, 5, 6, 3, 4, 7]

We can think of this list as a sequence of pairs: (3, 7), (5,5), (8, 5), (6, 3), (4, 7). The pairs (3, 7) and (4, 7) are \"bad\"because the left element is smaller than the right one, so thesepairs should be cleaned (or removed). So the call ofcleanCorruptData(list); would change the list to store thefollowing element values: [5, 5, 8, 5, 6, 3]

If the list has an odd length, the last element is not part of apair and is also considered \"corrupt;\" it should therefore becleaned by your method. If an empty list is passed in, the listshould still be empty at the end of the call. You may assume thatthe list passed is not null. You may not use any other arrays,lists, or other data structures to help you solve this problem.

THIS IS FOR JAVA.

Answer & Explanation Solved by verified expert
4.3 Ratings (599 Votes)

ArrayList cleanCorruptData(ArrayList list)
{
   int l = list.length, j = 0;
   ArrayList result; // contains the resultant list
   for (int i = 0; i < l; i+=2)
   {
       int firstElement = list[i];
       if (i+1 < l) // checking for odd and even length
       {
           int secondElement = list[i+1];
      
           if (firstElement >= secondElement) // if the condition is true, then put it in the result list else remove
           {
               result[j++] = firstElement;
               result[j++] = secondElement;
           }
       }
   }
   return list;
}


Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students