how to get minimum index number in arraylist java? - java

i m using this code for getting index number but i can't get minimum index number
for(String it : list1){
index = list.indexOf(it);
System.out.println("\n index1 : " +it);
}
for(String it1 : list1){
index1 = list.indexOf(it1);
System.out.println("\nindex2 : " +it1);
}

Use:
int min =Math.min(index ,index1 )
For more information about the min function see the official Documentation

This looks much simple
for (int index = 0; index<list1.size(); index++) {
System.out.println("index of item is: " + index);
}

You could just keep it in another variable on the side:
String minStr;
int minIndex = Integer.MAX_VALUE;
for(String it : list1)
{
index = list.indexOf(item);
if (index < minIndex) {
minIndex = index;
minStr = it;
}
}
System.out.println ("The minimal index is " + minIndex + "( + minStr + ")");

According to the javadoc: List.indexOf(obj) returns the minimum index if the element is present in the list, or -1 otherwise. So basically you don't have to do anything besides calling indexOf

Related

can not determinate index in array

Strings are added to the array, to determine whether the list is ordered by increasing the length of the string. If not, print the index of the first element that violates such ordering.
Everything works correctly if the strings in the array are different, for example, enter
113
13476
Neutral
wa
Answer: index (wa) 3 output.
but if it will be like this:
123
12345
123
Answer: index (123) - 0 but the correct answer is index 2
public class Solution {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
list.add(scan.nextLine());
}
int count = 0;
for(int i = 0; i < list.size(); i++){
if(count+2 > list.size()) {
break;
}
if(list.get(i+1).length() <= list.get(i).length()){
System.out.println(list.indexOf(list.get(i+1)));
break;
}
count = count + 1;
}
}
}
You should change
list.indexOf(list.get(i+1))
to
i+1
since if there are multiple occurrences of the same String in the List, you want to return the index of the first element that violates the ordering, which is i+1 (and not the index of the first String which is equal to that element).
BTW, even if there were no duplicate elements in your List, it would no sense to use list.indexOf(list.get(i+1)) instead of simply i+1.
You don't need to use lastIndexOf - you already have the index:
// Stsrt at index 1, as index 0 can never violate the rule:
for (int i = 1; i < list.size(); i++) {
if (list.get(i).length() < list.get(i - 1).length() {
System.out.println("Rule violated at index " + i + " (" + list.get(i) + ")");
break;
}
}
You could also use PriorityQueue and check within the supplied Comparator
PriorityQueue<String> p = new PriorityQueue<>((a, b) -> {
if (a.length() > b.length()) {
throw new RuntimeException(a);
}
return 0;
});
p.add("foo");
try {
p.add("bar2");
} catch (RuntimeException e) {
System.out.println(p.size());
}
}

How to find the Missing Elements in a given sequence array list using java?`

1.I have an Integer array list with a starting element and arraylist limit.
Example [5,6,9,10]
2.In which I have to iterate and find the missing element and its position.
According to the above example ,my output should be number 7 (position3 ),number 8 (position 4) are missing.
3.Now I am getting all the numbers printed instead of getting the missing elements.
Below is the code :
public static List<Integer> issue_ret=new ArrayList<>();
Iterator<Integer> iter = issue_ret.iterator();
while(iter.hasNext()){
int value = iter.next();
if("1".equals(value)){
iter.remove();
}
else{
System.out.println("Missing value:"+value);
}
}
Can anyone help me to resolve this?
Suggest you a more efficient way than ArrayList.contains() but more limited:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(new Integer[]{5, 6, 9, 10}));
int head = list.get(0);
int tail = list.get(list.size() - 1);
int length = tail - head + 1;
int[] array = new int[length];
for (int i : list) {
array[i - head] = 1;
}
for (int i = 0; i < array.length; i++) {
if (array[i] == 0) {
System.out.println(String.format("Missing %d, position %d", i + head, i + 1));
}
}
The limit is: The top Integer number should not be too large. Anyway, it is a space for time way, whether to use depends on your actual needs.
You are comparing every element with 1
if("1".equals(value))
instead you should keep a counter which will start from your lists first element and then incremented by 1 and perform comparison with this counter.
Try,
List<Integer> integerList = new LinkedList<Integer>();
integerList.add(5);
integerList.add(6);
integerList.add(9);
integerList.add(10);
int first = integerList.get(0);
int last = integerList.get(integerList.size()-1);
for(int i=first+1; i<last; i++){
if(!integerList.contains(i))
System.out.println("Number Not in List : "+i);
}
By getting the first and last element from array you can know the start and end of the array and by iteration over that limit you can get what numbers are missing like below:
List<Integer> input = new ArrayList<Integer>();
input.add(5);
input.add(8);
int firstElement = input.get(0);
int lastElement = input.get(input.size()-1);
for(int i=firstElement+1, j=2; i<lastElement-1; i++,j++){
if(!input.contains(i))
System.out.println("Missing Number : "+i + "(position " + j+")");
}
As we already know that first element and last element is already present in last, no need to check that so we would be only checking of elements exist between first and last element.

Getting next index in Java Integer array

I am trying to search an array for an int but it only give the location of the first index it finds if the int appears more than once. For example, if the number 2 appears at index 3 and 7. It will say 3 found at location 3 twice instead of saying 2 found at location 3 and 7. How can I get the additional index of the location where the number also appears.
// random_integers is an array of random integers of size 10
Arrays.asList(random_integers);
for (int n : random_integers) {
if (n == number) {
System.out.println("Search Value: "
+ number
+ " found at location: "
+ Arrays.asList(random_integers).indexOf(n)
+ " in the unsorted array");
}
}
Thank you.
That's the behavior of indexOf. Instead, use a traditional for loop and just use the current looping variable
for (int i = 0; i < random_integers.length; i++){
if (random_integers[i] == number){
System.out.println("Search Value: " + number + " found at location: " + i);
}
}
This happens because List#indexOf() has no idea about your intention to keep last index where item was found recently, so it returns first index every time. You should iterate over array by index, printing it when occurrence found:
for (int i; i < random_number.length; i++) {
if (random_integers[i] == number) {
System.out.format("Search Value: %s found at location: %s in the unsorted array", number, i);
}
}
The indexOf() method returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.
A traditional for loop will work here.
for(int i=0; i < random_integers.length;i++){
if (random_integers[i] == number){
System.out.println("number=" + number + " location=" + i);
}
}
As what all guys said, use traditional for loop instead. If you want to use asList , try the following code:
int size = Arrays.asList(a).size();
for (int i = 0 ; i < size ; i++){
if (number == Arrays.asList(a).get(i))
System.out.println(" Search Value: " + number +
" found at location: " + i +
" in the unsorted array");
}
This code only works, if you are looking to find the current and next index value of a given array, however, if you are looking to find the index of a given value, refer to Michael's answer on this thread.
int totalLength = random_integers.length;
for (int i=0; i < totalLength; i++){
int nextIndex = i+1;
if (nextIndex == totalLength){
break;
}else{
int currentIndexValue = random_integers[i];
int nextIndexValue = random_integers[nextIndex];
}
}

Finding the same value at multiple indexes

I created a java program that will search for a value in array but my problem is when I input the same value in a different index, the first index is the only one that will be on output.
Example index 0 = 2, index 1 = 3, index 2 = 2
Output : array 2 is found at index 0 only
I break it on the loop to stop but if I did not do that, it will loop the Output
Here's what I want for Output: array 2 is found at index 0,2
Code:
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class Buff {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter how many index :");
int v = Integer.parseInt( in .readLine());
int x;
int[] c = new int[v];
int vv;
for (x = 0; x < v; x++) {
System.out.print("Enter your value :");
c[x] = Integer.parseInt( in .readLine());
}
System.out.print("Enter your search number :");
int xx = Integer.parseInt( in .readLine());
for (x = 0; x < v; x++) {
if (c[x] == xx) {
System.out.print("array " + xx + " found at index :" + x);
break;
} else {
System.out.print("array not found");
}
}
}
}
You can also use StringBuilder if all you care is to output the indexes.
StringBuilder sb = new StringBuilder("array" + xx +" is found at index: ");
for (x = 0; x < v; x++) {
if (c[x] == xx) {
sb.append(x).append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
} else {
System.out.println("array not found");
}
The solution to to make a list of the indexes that match and populate it in your for loop.
then after the for loop is done, print out the results
List<Integer> foundIndexes = new ArrayList<>();
for (x = 0; x < v; x++) {
if (c[x] == xx) {
foundIndexes.add(x);
}
}
//now we looped through whole array
if(foundIndexes.isEmpty()){
System.out.print("array not found");
}else{
System.out.print("array " + xx + " found at index : ");
for(Integer i : foundIndex){
System.out.print(i + ",");
}
}
This will print out array 2 is found at index 0,2, with a trailing comma. It's slightly more complicated to not have a trailing comma at the last index but I will leave that up to you to figure out.
If I understand correctly the problem is the following:
You have elements in an array, you want to check if a particular value is in more than once position of the array, your problem is if you simply remove the break statement, it shows a message every time you don't find the desired number, that's frankly the only problem I see with removing the break statement.
Personally, what I'd do one of these two things:
Option A: You can create a boolean variable that changes if you find a number, then wait to deliver the "array not found" message until you have stopped searching for it, like this:
boolean found = false;
for( x=0; x<v; x++)
{
if(c[x] == xx)
{
System.out.println("array " + xx + " found at index :"+x);
found = true;
}
}
if (found = false)
{
System.out.println("array not found");
}
println does the same as print, only it introduces a \n at the end, so the response looks like this:
array 2 found at index :0
array 2 found at index :2
Instead of:
array 2 found at index :0
array 2 found at index :2
Option B: Probably more elegant solution would be to create other array that store the positions in which you have found the element you are looking for, then print them all at once, you could do this going over the array twice (one to count how many positions the array has to have, another to check the positions of the elements) or simply use an ArrayList, but since this looks like learning material I'm going to guess that's out of the question.
Also if it is possible, try to word your question better because I'm still not even sure if this is what you are asking.

Java duplicates distinct unique array value

I am trying to solve this, but i don't know how...
Values[10] = {1,1,4,4,2,3,3,2,1,3}
to print:
{1,2,3,4} or {1,4,2,3} (not sorted, any order, but distinct)
I also need to count the number of times each number has occurred, both without sort, new arrays or boolean methods or other data structures, please advise as i am stuck.
Is there a simple method i can use to just print the unique values/ distinct values ?
It can be accomplished if your are willing to destroy your current array. and you assume that the array is either of type Integer (so nullable) or if not there is some bound such as all int are poistive so you can use -1.
for(int i = 0; i < values.length; i++){ //for entire array
Integer currVal = values[i]; // select current value
int count = 1; // and set count to 1
if(currVal != null){ // if value not seen
for( int j = i + 1; j < values.length; j++){ // for rest of array
if(values[j] == currVal){ // if same as current Value
values[j] = null; // mark as seen
count++; // and count it
}
}
System.out.print("Number : " + currVal + " Count : " + count + "\n");
//print information
}
// if seen skip.
}
In plain english, Go through the array in 2 loops, roughly O(n^2) time.
Go to index i. If index has not yet been seen (is not null) then go through the rest of array, mark any indexs with same value as seen (make it null) and increment count varable. At end of loop print value and count. If Index has be seen (is null) skip and go to next index. At end of both loops all values will be left null.
Input : Values[] = {1,1,4,4,2,3,3,2,1,3}
Output : Values[] = {1,null,4,null,2,3,null,null,null,null}
Number : 1 Count : 3
Number : 4 Count : 2
Number : 2 Count : 2
Number : 3 Count : 3
Edit: corrected my mistake in output, pointed out by commenters.
Another solution, without creating additional objects:
Arrays.sort(values);
for(int i = 0; i < values.length; i++) {
if (i == 0 || value[i] != value[i-1]) {
System.out.println(values[i]);
}
}
And the shortest solution I can think of:
Integer[] values = {1,1,4,4,2,3,3,2,1,3};
Set<Integer> set = new HashSet<Integer>();
set.addAll(Arrays.asList(values));
System.out.println(set);
Assuming the values are guaranteed to be integers, you could also do it by incrementing a check value, scan over the array, sum the number of that check value in the array, add it to an accumulator and loop while the accumulator < array.length.
Something like this (untested):
public void checkArray(int[] toCheck) {
int currentNum = 0;
int currentCount = 0;
int totalSeen = 0;
StringBuilder sb = new StringBuilder();
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i=0; i<toCheck.length; i++) {
min = Math.min(toCheck[i], min);
max = Math.max(toCheck[i], max);
}
System.out.print("{ ");
for(currentNum = min; currentNum < max; currentNum++) {
for(int i=0; i<toCheck.length; i++) {
if(toCheck[i] == currentNum) currentCount++;
}
if(currentCount != 0) {
if(currentNum == min) System.out.print(currentCount + "(" +currentCount+ ")");
else System.out.print(", " + currentCount + " (" +currentCount+ ")");
}
totalSeen += currentCount;
currentCount = 0;
}
System.out.println(" }");
}
It should be noted that while this technically fulfills all your requirements, it will be far less efficient than gbtimmon's approach.
If your ints were {1,2,3,150000}, for example, it will needlessly spin over all the values between 4 and 149999.
Edit: added better limits from tbitof's suggestion.
Your question isn't quite clear to me, since it sounds like you want to do these things without creating any additional objects at all. But if it's just about not creating another array, you could use a Map<Integer, Integer>, where the key is the number from your original array, and the value is the count of times you've seen it. Then at the end you can look up the count for all numbers, and print out all the keys by using Map.keyset()
Edit: For example:
Map<Integer,Integer> counts = new HashMap<Integer, Integer>();
for( int i : values ) {
if( counts.containsKey(i) ) {
counts.put(i, counts.get(i) + 1);
} else {
counts.put(i, 1);
}
}
// get the set of unique keys
Set uniqueInts = counts.keyset();

Categories