In: Computer Science
I'm trying to do some pratice problems in the book and here is one of them.
THIS IS FOR JAVA.
Write a method cleanCorruptData that accepts an ArrayList of integers and removes any adjacent pair of integers in the list if the left element of the pair is smaller than the right element of the pair. Every pair's left element is an even-numbered index in the list, and every pair's right element is an odd index in the list. For example, suppose a variable called list stores the following 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 these pairs should be cleaned (or removed). So the call of cleanCorruptData(list); would change the list to store the following element values: [5, 5, 8, 5, 6, 3]
If the list has an odd length, the last element is not part of a pair and is also considered "corrupt;" it should therefore be cleaned by your method. If an empty list is passed in, the list should still be empty at the end of the call. You may assume that the 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.
ArrayList<Integer>
cleanCorruptData(ArrayList<Integer> list)
{
int l = list.length, j = 0;
ArrayList<Integer> 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;
}