Getting next index in Java Integer array - java

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];
}
}

Related

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.

how to get minimum index number in arraylist 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

Calculating average in a TestLuck (Probability) Program

I'm a student, trying to write a program that tests probability. It's called TestLuck it's supposed to generate a user determined amount of IntArrayLogs(ADT's) that are populated with random values. The program is supposed to calculate how many values were generated before there is a match to the first value.
Actual Problem:
"Create application TestLuck; have the user enter the upper limit of the random integer range (the book says 10,000, but you should also test with 365) as well as the number of times to run the test. Compute and output the average."
This is what I came up with, but I'm not getting the correct results for some reason, I tested the methods I use and they seem to work right, I think it's something to do with how I'm keeping track of the counter.
for(int k=0; k<numTests; k++) {
for(int i=0; i<upperLimit; i++) {
arrLog.insert(n);
n = rand.nextInt(upperLimit);
if(arrLog.contains(arrLog.getElement(0))) {
totalCount += i;
break;
}
if(i == upperLimit-1)
totalCount +=i;
}
System.out.println("Total Count: " + totalCount);
arrLog.clear();
}
testAverage = totalCount/numTests;
System.out.println("Average tests before match: " + testAverage);
Contains Method:
// Returns true if element is in this IntLog,
// otherwise returns false.
public boolean contains(int element) {
int location = 0;
int counter = 0;
while (location <= lastIndex) {
if (element == log[location]) { // if they match
counter++;
location++;
if(counter == 2)
return true;
} else
location++;
}
return false;
}
You don't need a contains() method, as this will only take more time to compute something as simple as a comparison.
The question is how many numbers have to be generated before matching the first number, but you need to take into account if this includes the first number. eg. {1,2,3,4,1} count = 5, or {1,2,3,4,1} count = 4. Either way, this wont affect the logic on this answer:
If you re-arrange your method it will work much faster.
for(int k=0; k<numTests; k++){
for(int i=0; i<upperLimit; i++){
arrLog.insert(n);
if(arrLog.getElement(0) == n && i != 0){// i != 0 to prevent it from counting a match on the first iteration
totalCount += i;//totalCount += i+1 if you are counting the first number
break;
}
n = rand.nextInt(upperLimit);
}
System.out.println("Total Count: " + totalCount);
arrLog.clear();
}
testAverage = totalCount/numTests;
System.out.println("Average tests before match: " + testAverage);
If you are required to use a contains() method let me know on the comments and I'll edit the answer.
I would also like to suggest not using any storage data structure, in this case an ADT's IntArrayLog (again, I dont know if you are required to use ADT as part of your course); so that your program will run even faster:
int firstNum;
for(int k=0; k<numTests; k++){
firstNum = rand.nextInt(upperLimit);
for(int i=1; i<upperLimit; i++){//notice this starts in 1
n = rand.nextInt(upperLimit);
if(firstNum == n){
totalCount += i;//totalCount += i+1 if you are counting the first number
break;
}
}
System.out.println("Total Count: " + totalCount);
arrLog.clear();
}
testAverage = totalCount/numTests;
System.out.println("Average tests before match: " + testAverage);
I find some odd things in your code.
First, you are inserting n to arrLog before giving n a value.
Second, you are testing if i == upperLimit-1 after the for loop to add 1 to the counter. You will only meet this condition if the for loop breaks in the last step (in which case you had added 2 to the counter).
Third, in the contains method you are returning true if you find element twice. As I understand the first time should be in position 0 (the first element) and then the test itself, yet you are passing the first element as argument. You should probably begin location in 1 (skipping first element) and count it once:
for (location=1; location<=lastIndex; location++) {
if (element = log[location]) return true;
}
return false;
However it should be easier just to compare n with arrLog.getElement(0)
P.S. I'm assuming everything else is properly initialized.

Methods aren't returning anything in Java

I wrote a class in Java with 5 methods. Linear search, which returns true if the value is found and false if it's not found. Linear search 2, which returns the location of the value, if found. binary search. which searches for the value within the array as well, print Int array, which prints 10 numbers a time, and selection sort, which sorts the array so I can do the binary search. Everything is compiling fine, but for some reason, none of my methods are returning anything (except the void printIntArray method).
EDIT:
Thanks, guys, I didn't realize I needed that. For some reason I thought it would return the value on its own... Another question, though. The binarySearch method doesn't appear to be doing anything. After the print statement "Searching for 11 in the random array using binary search"...., nothing is printed.
EDIT 2:
My binarySearch method wasn't working because I accidentally had mid + 1 for both else statements (else if (key < array[mid]) should have been mid - 1). THANKS so much to everyone! I added the fixes.
public class sortingSearching {
public static boolean linearSearch (int [] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array [i] == key)
return true;
}// end for
return false;
}
public static int linearSearch2 (int [] array, int key) {
for (int i = 0; i < array.length; i++) {
if (array [i] == key)
return i;
}//end for
return -1;
}//end linearSearch2
public static boolean binarySearch (int [] array, int key) {
int left = 0;
int right = array.length - 1;
int mid = (left + right) /2;
while (left <= right) {
if (array[mid] == key)
return true;
else if ( key < array[mid])
right = mid - 1;
else
left = mid + 1;
mid = (left + right) /2;
} //end while
return false;
}//end binarySearch
public static void printIntArray (int [] array) {
for (int i = 0; i < array.length; i++) {
if (i%10 == 0)
System.out.println();
System.out.print(array[i] + " ");
} // end for
}
public static void selectionSort (int [] array) {
for (int start = 0; start < array.length - 1; start ++) {
int minI = start;
for (int i = start + 1; i < array.length; i++)
if (array[i] < array[start])
minI = i;
int temp = array[start];
array[start] = array[minI];
array[minI] = temp;
}//end for
} //end selectionSort
public static void main (String args []) {
int [] array = new int [20];
for (int i =0; i < array.length; i++)
array[i] = (int)((Math.random() * 100) + 1);
//print the array using printArray
printIntArray(array);
System.out.println();
//use linearSearch to search for 30, 86, and 87
System.out.println("Searching for 30 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(linearSearch(array, 30));
System.out.println("Searching for 86 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(linearSearch(array, 86));
System.out.println("Searching for 87 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(linearSearch(array, 87));
//use linearSearch to locate the first occurrences of 25, 80, and 91
System.out.println("Searching for the location of 25 in the random array. If -1 is " +
"returned, the number was not found in the array.");
System.out.println(linearSearch2(array, 25));
System.out.println("Searching for the location of 80 in the random array. If -1 is " +
"returned, the number was not found in the array.");
System.out.println(linearSearch2(array, 80));
System.out.println("Searching for the location of 91 in the random array. If -1 is " +
"returned, the number was not found in the array.");
System.out.println(linearSearch2(array, 91));
//use selectionSort to sort the array
selectionSort(array);
//use binarySearch to search for 11, 28, 74, and 99
System.out.println("Searching for 11 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 11));
System.out.println("Searching for 28 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 28));
System.out.println("Searching for 74 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 74));
System.out.println("Searching for 99 in the random array using binary search. If true is returned, " +
"the value was found. If false was returned, the value was not found.");
System.out.println(binarySearch (array, 99));
} //end main
} //end sortingSearching
Also, I'm sorry all the print statements in the main method are distracting. I thought about taking them out for ease of reading, but I wanted it to be exactly as I've been running it.
linearSearch(array, 30);
They do return something. But DO something with the return value!
boolean value = linearSearch(array, 30);
System.out.println(value);
or even simpler:
System.out.println(linearSearch(array, 30));
In response to your edit
You need to initiate left to 1. You're performing integer division, which can never reach zero. Hence right gets stuck on 1 and left is always less than it.
They don't return anything because you are not assigning the return value to any variable.
Make this:
boolean foo= linearSearch(array, 86);
System.out.println(foo);
or
System.out.println(linearSearch(array, 86));
And so on.
You must put the sorting/searching method calls inside the println() statements, otherwise the results won't get printed! Like this:
System.out.println(
"Searching for 30 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found." +
linearSearch(array, 30));
Alternatively, store the result in a local variable - but again, you have to pass the variable to println():
boolean result = linearSearch(array, 30);
System.out.println(
"Searching for 30 in the random array. If true is returned, " +
"the value was found. If false was returned, the value was not found." +
result);
They return what they are supposed to, just that you choose not to do anything with what they return.
You can solve the problem by wrapping the function calls in a System.out.println(), or storing the return values by using ret = yourfunction(params) and displaying ret later.

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