How can I remove all elements to the left of an index?

So I am currently working on an assignment and I am currently stuck. I cannot figure out how to get all elements that are to the left of an index and remove them from an Arraylist.

These are the exact instructions:

For this program, given the sequence, remove all the zeros, if any, and all the digits to their left. Then find the largest remaining digit and if it is even subtract 2 from it or if it is odd subtract 1 from it. If two or more digits become tied as the largest digit, use the rightmost digit as the largest. Repeat the application of the rules to the sequence. How many moves were required to delete the sequence?

This is what I have so far:

(Sorry if the code is a bit messy)

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

public class Main {
  public static void main(String[] args) throws FileNotFoundException {
    File inputFile = new File("input.txt");
    Scanner scanFile = new Scanner(inputFile);

    String input;
    int testCase;
    String testCaseS = "";
    int zero;
    //testCase = scanFile.nextInt();
    //System.out.println(testCase);

    input = scanFile.next();
    //System.out.println(input);
    //input = input.replaceAll(",", "");


    String arr = input;
    String[] items = arr.replaceAll("\[", "").replaceAll("\]", "").replaceAll("\s", "").split(",");

    int[] results = new int[items.length];

    for (int i = 0; i < items.length; i++) {
        try {
            results[i] = Integer.parseInt(items[i]);
        } catch (NumberFormatException nfe) {

        };
    }

    //for (int o = 0; o <= items.length; o++)
      //System.out.println(results[o]);
    boolean choice = false;
    int counter = 0;

    List<Integer> intList = new ArrayList<Integer>();
    for (int i : results)
    {
      intList.add(i);
    }

    if (!choice) {
      for (int u = 0; u < items.length; u++) {
        if (results[u] == 0)
            counter++;
            //intList.removeAll(Arrays.asList(0 ));
        }
      }
      int zeroindex = intList.indexOf(0);



      System.out.println(intList);
  }
}

Answer

If you only want to delete all the elements left from particular index then

list.subList(0, index).clear();

this is the way.

Leave a Reply

Your email address will not be published. Required fields are marked *