'Odd number Sequence Replaced by Count

I am working on java Program

here is program Question: Consider Java Program. It reads integers from the standard input (until it gets a negative number) and puts them into an array. After that it calls processArray on the array, and then prints the contents of the array on standard output. in program any sequence of two or more consecutive odd numbers in the array are removed from the array and replaced by a single number representing the length of that sequence. The processArray function/method should modify the array in-place (preferably without creating a new array), and it should return the new length of the modified array.

For example, if these numbers were provided on the standard input:

222
3
35
62
124
61
29
375
66
7
-1

Then the program should print:

222
2
62
124
3
66
7

Note that the sequence 3, 35 has been replaced by 2 and the sequence 61, 29, 375 has been replaced by 3.

here is my code:

import java.util.*;
import java.io.*;

public class Main {
    public static int processArray(ArrayList<Integer> array) {
        ListIterator<Integer>iterator=array.listIterator();
        while (iterator.hasNext()) {
            Integer integer = (Integer) iterator.next();
            int count=0;
            if (integer%2!=0) {
                count=count++;
                iterator.remove();
                continue;
            }
            if(integer==-1)
                break;
            else
                iterator.previous();
            iterator.add(count);
            iterator.next();


        }

        return array.size();
    }

    public static void main (String[] args) {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        Scanner in = new Scanner(System.in);
        while(in.hasNextInt()) {
            int num = in.nextInt();
            if (num < 0) 
                break;
            arrayList.add(new Integer(num));
        }
        int new_length = processArray(arrayList);
        for(int i=0; i<new_length; i++)
            System.out.println(arrayList.get(i));
    }
}

My Logic Not Working Properly help to improve logic



Solution 1:[1]

Adding another issue:

You should remove:

if (integer == -1) break;

since you have eliminated the negative numbers on the first loop

Solution 2:[2]

  • You should add another loop inside the processArray() that executes when an odd number is found and increments the count

  • Before the loop store the number as backup

  • Then before adding check the count if it's more than 1 then replace the number with the count otherwise, use the backup integer

    You should also save the iterator position of the first odd number.

Solution 3:[3]

In processArray you need to move int count=0; to outside (before) the while loop.

Within the while loop your handling of the odd case is mostly correct. However, you need to add an else clause to handle the even case. It should look something like this (pseudocode):

if odd
    count++;
    remove current element
else
    if count > 0 
        add count to the array
        set count to zero
    add current element

Everything else within the while loop can be removed.

You also need to handle the case where the list ends with a sequence of odd numbers. You need to handle this after the while loop has ended, by checking if count > 0.

Solution 4:[4]

Try below Logic.

public static int processArray(ArrayList<Integer> array) {
    int count=0;
    for(int i=0;i<array.size();i++)
    {
        if((array.get(i)%2)!=0) //odd
        {
            count++;
            if(count>1)     //I had to replace length of  odd seq greater than or equal to 2
            {
                array.set(i,count);     //set curren count to current odd no and remove previous odd number
                array.remove(i-1);
                if(i>0)     //For handling change in indices
                    i=i-1;
                else
                    i=0;
            }
        }
        else
        {
            count=0;
        }
    }
    return array.size();
}

Solution 5:[5]

lis=[]

while True:
    inp= int(input())

    if inp<0:
        break

    else:
        lis.append(inp)


def processArray(lis):
    count=0
    for x in lis:
        ind=lis.index(x)

        if x%2!=0:                             # if number = odd
            if ind!=len(lis)-1:                #  if not last element
                count=count+1         #count of odd sequence
                y=x                   #storing x for later use as x is removed from list
                lis.remove(x)
                lis.insert(ind,-1)    #replacing x with -1 as removing x changes entire list index structure, messing with for loop iteration
                #print('odd ',x, lis, count)  

            if ind==len(lis)-1 and count>1:     # if last element and count of odd > 1
                lis.remove(x)                   
                lis.append(count+1)            
                break

        elif x%2==0:            # if number = even
           # print('even ',x, lis, count)

            if count==1:        # if count of odd =1, keeping same number back from -1 to y 
                lis.remove(-1)
                lis.insert(ind-1,y)
                count=0
               # print('even count=1 ',x, lis, count)

            if count>1 :        # if count of odd >1, adding count element in list
                 lis.insert(ind-1,count)
                 count=0
                # print('even count>1 ',x, lis, count)

    while -1 in lis:            # removing all -1
           lis.remove(-1)

    return len(lis)

print('length of modified list ',processArray(lis))
print(lis)

Solution 6:[6]

Try below Python Code: First replace the last consecutive odd number with the count and then the preceding odd number with -1. Finally, remove all -1 from the list.

Reason: It would be convenient to traverse the whole list with replacing consecutive odd numbers with -1, else the structure and indices of numbers would change and makes it difficult to iterate.

l=[222,3,35,62,124,61,29,375,66,7,-1]
count = 0
for i in range(0,len(l)):
    if l[i]%2!=0 and i!=len(l)-1:
        count +=1
    else:
        if count > 1:
            l[i-1]=count
            while count != 1:
                l[i-count]= -1
                count -= 1
        count = 0
l = [i for i in l if i>=0 ]

print(l)

Output: [222, 2, 62, 124, 3, 66, 7]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jessica Dionisio
Solution 2 Community
Solution 3
Solution 4 vaibhav k
Solution 5 Siddharth Sinha
Solution 6