MilkTable
MilkTable

Reputation: 41

Check if another instance of int exists in an int array

Say I have an int array called sequence with values

[1, 3, 2, 4, 3, 5, 4, 6, 1, 3]

I want to check if another instance of 1 exists besides the first one in the array, and if it does, I would like to get its index in the array.

So far, this is what I've done:

// Get the first and second number of the sequence array
int firstNumberIndex = 0;
int firstNumber = sequence[0];
int secondNumber = sequence[1];
// Check that firstNumber < secondNumber
if (firstNumber < secondNumber) {
    // Remove firstNumber from the sequence array
    instance = removeElement(sequence, firstNumberIndex);
    // Check whether another instance of
    // firstNumber exists in sequence array
    if (contains(sequence, firstNumber)) {
        // Here, I would like to get the index of
        // the other instance of '1', for example
    }
}

Upvotes: 0

Views: 208

Answers (3)

Yann TM
Yann TM

Reputation: 2075

a fast answer uses a hash:

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Snippet {
    public static void main(String[] args) {
        int[] sequence = {1, 3, 2, 4, 3, 5, 4, 6, 1, 3};
        Map<Integer, List<Integer>> indexMap = new LinkedHashMap<>();
        for (int i = 0; i < sequence.length; i++) {
            int val = sequence[i];
            indexMap.computeIfAbsent(val, k -> new ArrayList<>()).add(i);
        }
        System.out.println(indexMap);
    }
}

output:

{1=[0, 8], 3=[1, 4, 9], 2=[2], 4=[3, 6], 5=[5], 6=[7]}

So it gives for every value in the sequence all the indexes at which this value is found, which may or may not be more than what the OP asked for.

The values are returned in order encountered (thanks to LinkedHashMap), and the indexes are sorted. Overall it is O(length of the sequence) in time.

Upvotes: 1

user15766209
user15766209

Reputation:

  1. You can use List#indexOf method two times to get the second occurrence of an object in the List<Integer>:
    public static int getSecond(List<Integer> list, int val) {
        // index of the first occurrence
        int i = list.indexOf(val);
        // if found and not the last one
        if (i > -1 && i < list.size() - 1) {
            // index of the second occurrence from
            // the sublist after the first occurrence
            int j = list.subList(i + 1, list.size()).indexOf(val);
            // if found, return the composite index
            if (j > -1) return j + i + 1;
        }
        // not found
        return -1;
    }
    
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 3, 2, 4, 3, 5, 4, 6, 1, 3);
        System.out.println(getSecond(list, 3)); // 4
        System.out.println(getSecond(list, 1)); // 8
        System.out.println(getSecond(list, 6)); // -1
        System.out.println(getSecond(list, 7)); // -1
    }
    
  2. You can use IntStream if only an array int[] is required:
    public static int getSecond(int[] arr, int val) {
        return IntStream
                // iterating over array indices
                .range(0, arr.length)
                // filter the search elements
                .filter(i -> arr[i] == val)
                // skip the first one
                .skip(1)
                // take the second one
                .findFirst()
                // if not found
                .orElse(-1);
    }
    
    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 4, 3, 5, 4, 6, 1, 3};
        System.out.println(getSecond(arr, 3)); // 4
        System.out.println(getSecond(arr, 1)); // 8
        System.out.println(getSecond(arr, 6)); // -1
        System.out.println(getSecond(arr, 7)); // -1
    }
    

Upvotes: 0

Bohemian
Bohemian

Reputation: 425053

Preferring readability over raw execution speed:

List<Integer> list = new ArrayList<>();
IntStream.of(sequence).forEach(list::add);
int index = list.subList(1, list.size()).indexOf(sequence[0]) + 1;

See live demo.

index will be 0 if no second occurrence exists.

Upvotes: 2

Related Questions