This question follows my brevious one on how to Return value of smallest index of repeated number in array.
In this function given to me by #Andreas:
private static void printFirstIndexOfRepeated(int[] values) {
Integer firstIndex = null;
Map<Integer, Integer> mapValueToIndex = new HashMap<>();
for (int i = 0; i < values.length; i++) {
Integer prevIndex = mapValueToIndex.put(values[i], i); // put() returns old value, or null
if (prevIndex != null && (firstIndex == null || prevIndex < firstIndex))
firstIndex = prevIndex;
}
if (firstIndex != null)
System.out.println("First index of repeated: " + firstIndex);
else
System.out.println("No repeat found");
}
Function test:
int [] array = {10,5, 4, 3, 5, 6};
printFirstIndexOfRepeated(array);
Output
First index of repeated: 1 // it looks for 5 and return the value of smallest index of repeated 5 in array.
Due to my lack of programming knowledge with Map, I'm new and I know only Array. I need some help to transform this function and add another parameter like (int number) to decide witch number I'm looking for and not automatically
The desired one: printFirstIndexOfRepeated(int[] values, int number)
So because you basically just want the index of the first occurrence of a given number inside an array, you don't need the Map at all. Instead you can just use a simple for loop:
private static int printFirstIndexOfRepeated(int[] values,int number) {
for(int i = 0; i < values.length; i++){
if(values[i] == number){
//System.out.println("The first index of " + number + " is " + i);
return i;
}
}
//System.out.println(number + " is not a member of the array.");
return -1;
}
This function returns the first index of a given number or -1 if the number was not found. You can uncomment the print lines to also get an output if you like (or just delete them).
Related
Written this code, would like to get better approach using any algorithm to find missing numbers from an sorted or unsorted array. If its an unsorted array, i would sort and execute the following.
private static void identifyMissingValues(Integer[] ar) {
for(int i = 0; i < (ar.length - 1); i++) {
int next = ar[i + 1];
int current = ar[i];
if((next - current) > 1) {
System.out.println("Missing Value : " + (current + 1));
}
}
}
Any code faster or better than this, please suggest.
Any code faster or better than this, please suggest.
No there is no such thing - you cannot improve on an O(n) algorithm if every element must be visited.
Use BitSet instead of sorting.
int[] ar = {7, 2, 6, 8, 10, 4, 3, 2};
int min = IntStream.of(ar).min().getAsInt();
BitSet b = new BitSet();
for (int i : ar)
b.set(i - min);
int i = 0;
while ((i = b.nextClearBit(i + 1)) < b.length())
System.out.println(i + min);
result
5
9
Sorting the array would take O(n*log(n)).
You can do better if you add all the elements of the array to a HashSet (O(n)) running time, and then check for each number between 0 and ar.length - 1 (or whatever the relevant range is) whether the HashSet contains that number. This would take O(n) time.
Your approach is good, but I added something more for more than one numbers are missing..
eg : ar={1,2,4,6,10} // Sorted Array
private static void identifyMissingValues(Integer[] ar) {
for (int i = 0; i < (ar.length - 1); i++) {
int next = ar[i + 1];
int current = ar[i];
if ((next - current) > 1) {
for (int ind = 1; ind < next - current; ind++)
System.out.println("Missing Value : " + (current + ind));
}
}
}
Output is,
Missing Value : 3
Missing Value : 5
Missing Value : 7
Missing Value : 8
Missing Value : 9
Can I know the Input and Expected output number series ?
According to your code i feel the series should be a difference of 1,If i'm not wrong.
So you have an array of n elements which starts with an integer i and contains all integers from i to i+n is that right? Eg:
arr = [1,2,3,4,5]
So, the sum of all numbers in the array should be the sum of numbers from i to i+n.
Eg: sum(arr) = 1+2+3+4+5 = 15
The formula for the sum of numbers 1 to n is n(n+1)/2
So you can have a for loop as:
int counter = 0;
for(Integer i : integers)
counter += i
To get the sum of numbers in your array.
If your array starts at one, you check whether the counter variable equals n(n+1)/2, where n is the length of your array.
If your array doesn't start at one, for example arr = [78, 79, 80, 81] then you need to tweak this approach a little, but I'm sure you can figure it.
You can do:
Set<Integer> mySet = new TreeSet<Integer>(Arrays.asList(ar));
int min = mySet.first();
for (int i = 0; i < mySet.size(); i++) {
int number = min + i;
if (!mySet.contains(number)) {
System.out.println ("Missing: " + number);
i--;
}
}
Integer [] list = new Integer[]{1, 12, 85, 6, 10};
Integer previous = null;
Arrays.sort(list);
System.out.println(list);
for(int index = 0; index < list.length; index++){
if(previous == null){
previous = (Integer) list[index];
continue;
}
Integer next = previous + 1;
if(((Integer) list[index] - previous) > 1){
System.out.println("Missing value " + next);
index--;
}
previous = next;
}
For this program, I have a user input elements into a 5 space array using the private static void add() method. After adding these elements, the user is then able to use the private static void delete() method which allows them to input a number present in the array that they wish to remove. When entering numbers to remove, the program works perfectly fine unless I try to remove the last number for the currentSize of the array. For example, if I have an array with the following indexes and values:
0. = 1
1. = 2
2. = 3
3. = 4
4. = <empty>
The currentSize of the array is currently 4. If I try to remove value 4 in index 3, the program will not remove value 4. If I attempt to remove values 3, 2, or 1 after trying to remove value 4, these values will not remove either. On the other hand if I want to remove any of the values below value 4 first, i.e) values 1, 2, and 3, the program works correctly until I try to remove value 4 in index 0. If I attempt to remove value 4 at this point, nothing is removed. If I try to add a value, say 1, after attempting to remove value 4, value 4 is replaced with value 1. If I attempt to remove value 4 twice at index 0 and then attempt to add a new value, I get an IndexOutOfBoundsException: -1 . I believe that this has something to do with currentSize-- decrementing when it is not suppose to in the remove element algorithm present in the private static void delete() method. If anyone has a solution for this it would be greatly appreciated, thank you. The program is posted below. I have commented the section of the private static void delete() method that is giving me issues. This is the stack trace that I am getting:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at ArrayManager.add(ArrayManager.java:35)
at ArrayManager.main(ArrayManager.java:216)
/**
* A class that contains methods to carry out the Add, Update, Delete, Drop, Resize, and End commands to alter the state of an array with 5 integers.
*/
public class ArrayManager
{
// Array of 5 integers to be modified
private static int [] values = new int [5];
private static int currentSize = 0;
private static int position = 0;
//private static int index = 0;
static Scanner in = new Scanner(System.in);
/**
* A method that inserts an entered value into the array as long as it is between 1 and 99. If the array is full, an error message will be printed explaining that the array is full.
*/
private static void add()
{
System.out.println("Enter values between 1 and 99, inclusive that you would like to add to the array.");
if(in.hasNextInt())
{
int n = in.nextInt();
if(n >= 1 && n <= 99)
{
if(currentSize < values.length)
{
values[currentSize] = n;
currentSize++;
}
else
{
System.out.println("ERROR: The array is currently full.");
}
}
else
{
System.out.println("ERROR: The number entered must be between 1 and 99, inclusive.");
}
}
else
{
System.out.println("ERROR: String has been entered. Enter an Integer.");
}
}
/**
* A method that asks the user to enter a value they wish to delete in the array. The following values are then shifted down in index in the array. If the value chosen does not exist in the array, an error message is displayed explaining that the value entered does not exist in the array.
*/
private static void delete()
{
int n = 0;
System.out.println("Please enter the value in the array that you wish to remove.");
if(in.hasNextInt())
{
n = in.nextInt();
for(position = 0; position < values.length; position++)
{
if(values[position] == n)
{
// The stack trace points me back to this section of code which removes the specified value in the values array.
for(int i = position + 1; i < currentSize; i++)
{
values[i - 1] = values[i];
values[i] = 0;
}
currentSize--;
break;
}
else if(position == values.length - 1)
{
System.out.println("ERROR: The value entered does not exist in the array.");
}
}
}
else
{
System.out.println("ERROR: String has been entered. Enter an Integer.");
}
}
/**
* A method that prints out the modified array.
*/
public static void printArray()
{
System.out.println("* Current Array Contents *");
for(int i = 0; i < values.length; i++)
{
if(values[i] != 0)
{
System.out.println(i + ". = " + values[i]);
}
else if(values[i] == 0)
{
System.out.println(i + ". = <empty>");
}
}
}
The corner case where position is the index of last element of the values array, is not handled properly. In such a scenario, the code starts to iterate the elements from the next index in order to shift all the elements by 1 position and the condition is not met by the condition in for loop.
for(int i = position + 1; i < currentSize; i++)
for(int i = position + 1; i < currentSize; i++)
{
values[i - 1] = values[i];
values[i] = 0;
}
The solution would be to check for that condition and handle it explicitly.
if(values[position] == n ) {
if( position != values.length - 1 ) {
for(int i = position + 1; i < currentSize; i++)
{
values[i - 1] = values[i];
values[i] = 0;
}
} else {
values[i] = 0;
}
currentSize--;
break;
}
So far, I only get the part where I can count one particular value in an array array. However, I would like to know how to get occurrence of 'every' number in an array and display them.
Here is the code I've got -
public class CIS3618thAssignment
{
public static void main(String[] args) {
int[] randomNumbers = new int[100];
for(int index = 0; index < randomNumbers.length; index++)
{
randomNumbers[index] = (int) (Math.random()*100);
}
for(int index = 0; index < randomNumbers.length; index++)
{
System.out.println(randomNumbers[index]);
}
System.out.println("Occurrence of 2 is " + GetOccurrence(2, randomNumbers, 0, randomNumbers.length));
}
public static int GetOccurrence(int k, int[] numbers, int startIndex, int endIndex)
{
if(endIndex<startIndex)
return 0;
if(numbers[startIndex]>k)
return 0;
if(numbers[endIndex]<k)
return 0;
if(numbers[startIndex]==k && numbers[endIndex]==k)
return endIndex-startIndex +1;
int midInd = (startIndex+endIndex)/2;
if(numbers[midInd]==k)
return 1+GetOccurrence(k, numbers, startIndex, midInd-1) + GetOccurrence(k, numbers, midInd+1,endIndex);
else if(numbers[midInd]>k)
return GetOccurrence(k, numbers, startIndex, midInd-1);
else
return GetOccurrence(k, numbers, midInd+1, endIndex);
}
}
So, in the source code, I am only capable of getting the occurrence of the value = 2 out of the array.
By reading your codes, it seems that you are trying to find the element by binary search? But you know that binary search works on sorted array. I didn't see the sorting part in your codes.
For your requirement, why not just build a Map<Integer,Integer> the key is the number, the value is the occurrence? It makes your implementation a lot easier.
You could use HashMap, where key is given number and value is number of occurrences.
You iterate over array and if the key(number) already exists, increment value(occurrences). Else, add new key and set its value to 1.
Check this DEMO.
I guess is what you want...
I didn't use Map or recursion as in your code, important for-loop to count is this one:
int[] results = new int[100];
// fill map with results
for(int index = 0; index < randomNumbers.length; index++)
{
// if number on randomnumbers is 2, this line sum +1 in position 2 of the array
results[randomNumbers[index]] = results[randomNumbers[index]] + 1;
}
Put this line in the loop:
System.out.println("Occurrence of 2 is " + GetOccurrence(2, randomNumbers, 0, randomNumbers.length));
And change it as follows:
for(int index = 0; index < randomNumbers.length; index++) {
System.out.println("Occurrence of " + randomNumbers[index] + " is " + GetOccurrence(randomNumbers[index], randomNumbers, 0, randomNumbers.length));
}
Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
Is there a way for java to check an array of integers for a specified user input and return boolean value and also the index where it resides? I have my way but I also wanted to know which index did it found the exact integer
Snippet of the code:
int numUser = Integer.parseInt(inputUser);
boolean ispresent = false;
for(int x = 0; x<=4; x++){
if(sum[x] == numUser){
ispresent = true;
}else{
ispresent = false;
}
}
if(ispresent== true){
System.out.println("The number is in the array");
}else{
System.out.println("The number is not in the array");
}
You could maybe return an -1 for when it doesn't find it in the array. Since there is no -1 index in an array, you can tell that it does not appear in the array.
If the value does appear in the array, you can return that index. Since you are returning an int always.
Your problem is the very typical indexOf(). It is usually a convention to return -1 when the element was not found, and the index (which is greater or equal to 0) otherwise.
You have different ways to get to that result.
Convert your array to a List
int numUser = Integer.parseInt(inputUser);
int index = Arrays.asList(sum).indexOf(numUser);
if (index < 0) {
System.out.println("The number is not in the array");
} else {
System.out.println("The number is in the array: " + index);
}
Use Apache ArrayUtils
int numUser = Integer.parseInt(inputUser);
int index = ArrayUtils.indexOf(sum, numUser);
if (index < 0) {
System.out.println("The number is not in the array");
} else {
System.out.println("The number is in the array: " + index);
}
Write it yourself
int numUser = Integer.parseInt(inputUser);
int index = -1;
for (int i = 0; i < sum.length; ++i) {
if (sum[i] == numUser) {
index = i;
break;
}
}
if (index < 0) {
System.out.println("The number is not in the array");
} else {
System.out.println("The number is in the array: " + index);
}
If you don't mind converting to a List, I would use the first method (clearer code with least dependencies). If you do mind and are already using Apache Utils in your project, the second method is fine, and avoid the conversion. If you want to keep as little dependencies and are fine with more complex source code, the third method might be what you are after!
You could use:
int result = Arrays.asList(array).indexOf(value);
boolean contained = result != -1;
A result of -1 means, that the value is not in the array; in case result >= 0, it is the actual index.
Use
int numUser = Integer.parseInt(inputUser);
int indexOfNumUser = Arrays.asList(sum).indexOf(numUser);
if the numUser exists then indexOfNumUser contains the index of the num in the array. If not it contains -1.
You also could try to replace array of Integers with ArrayList, if you do not have use it.
This will make your task much easier to solve.
Strictly in "standard" Java, you should use the answers posted before (convert to List and use indexOf).
But if you want to stick with the Array, use from ApacheCommons ArrayUtils.indexOf(int[], int).
From the Documentation:
Returns:
the index of the value within the array, INDEX_NOT_FOUND (-1) if not found or null array input