For Python, I can do something like array.index(element) to get the index for an element in array. How can I do this in Java using regular arrays, not arrayList? Is there a similar function?
You can use Arrays.asList then use List.indexOf. The other suggestions to use Arrays.binarySearch are good but require the array to be sorted.
You have to use Arrays.binarySearch method (array has to be sorted).
If sorting an array is unacceptable you have only one solution - full scan. Simply loop through the array to find the index of the element. Same can be acheieved by converting array to List using Arrays.asList and then using list's indexOf method.
You can do:
Arrays.asList(regularArray).indexOf(elementYouWant);
or, if the array is sorted, you can use
Arrays.binarySearch();
If you don't want to use Java Collections may can use this. You need implements equals method in your class.
public int index(Object[] array, Object element) {
for(int i = 0; i < array.lenght; i++) {
if (array[i] == element) {
return i;
}
if (array[i].equals(element) {
return i;
}
}
return -1;
}
The best way is writing your own function. each built-in method has issue like need sorted array for binarySearch or creating a new list object for asList method.
Use a method like this.
public int index( int search, int[] arr ){
for( int i=0; i< arr.length ; i ++ )
if( arr[ i ] == search)
return i;
return -1;
}
There are a couple of ways
1) Arrays.binarySearch
2) or you can loop though and find it.
public int getArrayIndex(int[] myArray, obj myObject)
{
int length = Array.getLength(myArray);//get the size of the array
for (int i = 0; i < lenght; ++i)
{
if (myArray[i] == myObject)
{
return(i);
}
}
return(-1);//didn't find what I was looking for
}
Related
This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 4 years ago.
I have this method header:
public boolean remove(Object anObject)
{....}
I need the body of the method to remove the first occurrence of a specified element from an int array and shift the remaining elements in the array to the left. I have thought about starting with
for (int i = 0; i < arr.length; i++) {
if (arr[i] == anObject)
}
but this is not working as expected.
Any help would be great, thanks!
I have a solution for you. Use a for loop that runs and shifts all of your array data over by one.
Building off of your original code:
for (int i = 0; i < arr.length-1; i++) {
if (arr[i].equals(anObject)){
for (int k = i; k < arr.length; k++){ //starts replacing ON the duplicate value
arr[k] = arr[k+1]; //replaces the value with the 1 higher one; aka moving all your array values left
}
}
And like what #camickr said:
You need to use stringName.equals(Object); to compare strings because they are non-primative data types.
Hope this helps. Good luck.
What you're trying to achieve can be done quite easily through the use of an ArrayList, as camickr mentioned. Overall, the use off ArrayLists for objects can be considered better practice in general.
Simply declare an ArrayList of type the object you are using, and add and remove instances of said object by using
myArrayList.add(object);
myArrayList.remove(index);
Here's a solution that works using only true array of objects, rather than any of the Java Collections. The outline of how this works in pseudocode is:
Iterate through all members of the array, checking for equality to anObject.
When a match is found, remove the element.
Iterate through the remaining members of the array, shifting them forward one spot.
At the end of the array, mark the final member as null.
I've included some extra code that won't be necessary for your assignment, but will help you to visualize how the method is working on the array:
public class ArrayMethodTester {
private Object[] array = {3, 5, 1, 6, 8, 7, 0, 9, 2, 4};
public static void main(String[] args) {
ArrayMethodTester testArray = new ArrayMethodTester();
testArray.printArray();
testArray.remove(7);
testArray.printArray();
}
public boolean remove(Object anObject) {
for (int i = 0; i < array.length; i++) {
if(array[i].equals(anObject)) {
for (int j = i; j < array.length - 1; j++) {
array[j] = array[j + 1];
}
array[array.length - 1] = null;
return true;
}
}
return false;
}
private void printArray() {
System.out.printf("[%s", array[0]);
for (int i = 1; i < array.length; i++) {
System.out.printf(",%s", array[i]);
}
System.out.println("]");
}
}
but i learned this will not get me my answer
if (arr[i] == anObject)
You should NOT be using "==" for object comparison.
if (arr[i].equals(anObject))
Instead you should be using the equals(..) method.
Then once you know the index of the item you want to remove. So now you just need to copy the next item to that index and repeat until you reach the end of the array. The last item would then be set to null to indicate no value exists.
Let's say I have an array in the length of n, and the only values that can appear in it are 0-9. I want to create a recursive function that returns the number of different values in the array.
For example, for the following array: int[] arr = {0,1,1,2,1,0,1} --> the function will return 3 because the only values appearing in this array are 0, 1 and 2.
The function receives an int array and returns int
something like this:
int numOfValues(int[] arr)
If you are using Java 8, you can do this with a simple one-liner:
private static int numOfValues(int[] arr) {
return (int) Arrays.stream(arr).distinct().count();
}
Arrays.stream(array) returns an IntStream consisting of the elements of the array. Then, distinct() returns an IntStream containing only the distinct elements of this stream. Finally, count() returns the number of elements in this stream.
Note that count() returns a long so we need to cast it to an int in your case.
If you really want a recursive solution, you may consider the following algorithm:
If the input array is of length 1 then the element is distinct so the answer is 1.
Otherwise, let's drop the first element and calculate the number of distinct elements on this new array (by a recursive call). Then, if the first element is contained in this new array, we do not count it again, otherwise we do and we add 1.
This should give you enough insight to implement this in code.
Try like this:
public int myFunc(int[] array) {
Set<Integer> set = new HashSet<Integer>(array.length);
for (int i : array) {
set.add(i);
}
return set.size();
}
i.e, add the elements of array inside Set and then you can return the size of Set.
public int f(int[] array) {
int[] counts = new int[10];
int distinct = 0;
for(int i = 0; i< array.length; i++) counts[array[i]]++;
for(int i = 0; i< counts.length; i++) if(counts[array[i]]!=0) distinct++;
return distinct;
}
You can even change the code to get the occurrences of each value.
You can try following code snippet,
Integer[] arr = {0,1,1,2,1,0,1};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
Output: [0, 1, 2]
As you asked for a recursive implementation, this is one bad way to do that. I say bad because recursion is not the best way to solve this problem. There are other easier way. You usually use recursion when you want to evaluate the next item based on the previously generated items from that function. Like Fibonacci series.
Ofcourse you will have to clone the array before you use this function otherwise your original array would be changed (call it using countDistinct(arr.clone(), 0);)
public static int countDistinct(int[] arr, final int index) {
boolean contains = false;
if (arr == null || index == arr.length) {
return 0;
} else if (arr.length == 1) {
return 1;
} else if (arr[index] != -1) {
contains = true;
for (int i = index + 1; i < arr.length; i++) {
if (arr[index] == arr[i]) {
arr[i] = -1;
}
}
}
return countDistinct(arr, index + 1) + (contains ? 1 : 0);
}
int numOfValues(int[] arr) {
boolean[] c = new boolean[10];
int count = 0;
for(int i =0; i < arr.length; i++) {
if(!c[arr[i]]) {
c[arr[i]] = true;
count++;
}
}
return count;
}
I know I could use the contains() method, but I can't figure out how to use it for a two dimensional array and how to return something.
Right now my code looks like this:
public class Array {
public static void main(String[] args) {
int z = 2;
int[][] data = new int[1][4];
data[0][0] = 0;
data[0][1] = 3;
data[0][2] = 2;
data[0][3] = 6;
for (int i = 0; i < data[0].length; i++) {
if (data[0][i] == z) {
System.out.println("Array data has z");
}
}
}
}
Checking with a loop works, but we were advised to use the contains method.
But how can I use the contains method in my case?
The method contains() is valid for Collections, not for Array.
In order to use this method, you need to convert your arrays into Collections first. As you have a two-dimensional array, I suggest you loop through it and analyze each of its one-dimensional subarrays to look for the desired value.
public boolean containsValue(int[][] data, int z) {
for (int i = 0; i < data.length; i++) {
if (Arrays.asList(data[i]).contains(z)) {
return true;
}
}
return false;
}
Another approach would be to use ArrayUtils.contains() method if you are using it in your project, as already shown here.
Finally, you can perform an O(n²) comparison with two for blocks to search for the desired value without the overhead of converting your array into a list, as stated above. However, I believe the approach shown in the code snippet above will be faster.
I am looking to verify if all of the integers in a 2d array are unique, return true if they are unique otherwise false.
The below code is what I have for a simple array. But I am not sure how to go about modifying it.
public boolean verifyUniqueIntegers(int array []){
boolean result = true;
for (int i = 0; i < array.length; i++) {
if(array[i] <= 0 || array[i] > n*n){
result = false;
}
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
result = false;
}
}
return result;
}
The best way to approach this problem is to use a mathematical construct called a set. The key property of a set for your purposes is that they can not contain duplicates by definition. Java provides a data structure allowing us to create sets found in java.util.Set. This is the generic interface that specifies how sets should behave. However, interfaces provide only specification, not implementation, so you'll have to use Set in conjunction with another class java.util.HashSet, which implements Set. You seem like a novice programmer, so I wrote a test program to show you how this works.
import java.util.*;
public class SetTest {
public static void main(String[] args) {
int[] set = {1,2,3,4,5,6,7};
int[] nonSet = {1,2,3,4,5,4};
System.out.println(verifyUniqueIntegers(set));
System.out.println(verifyUniqueIntegers(nonSet));
}
public static boolean verifyUniqueIntegers(int[] array) {
Set<Integer> set = new HashSet<Integer>();
for(int i : array) // This is a construction called a for-each loop
if(!set.add(i)) // This is an example of what's called autoboxing
return false;
return true;
}
}
Here I've used a static method for convenience, but you can of course change this into an instance method for your purposes once you give it a try.
First, I create a for-each loop to iterate over all the elements in the array that's passed into verifyUniqueIntegers(). For each loops use what are called iterators to create a reference to each element, one at a time, and make it available in the body of the loop. When the end of the body is reached, the for-each loop automatically resets i to the next element in the array, as long as there are elements left in the arry. You can ready more about for-each loops in the Oracle Java Tutorials.
Then, the method calls set.add(i). This attempts to add i to the set that we previously defined. This is an example of what's called autoboxing. Since the Set interface is generic, it can contain elements of any object type. Since int is a primitive, we must use the wrapper class Integer to specify the elements in our set. When we call set.add(i) you don't have to convert the int into an Integerbecause the java compiler does it for you.
This method returns true if i is not a duplicate, then adds it to the Set. It returns false if i is a duplicate and does nothing. Thus, we can take advantage of the method check the uniqueness of each element in your array. The method returns false as soon as a duplicate is found, and otherwise returns true. Hope this helps, good luck!
Your algorithm is slow. To make it faster, you should use something like HashMap.
Create empty HashMap<Integer>.
Iterate on all 2d-array elements (for-for loop).
For every element check if your HashMap contains it.
If yes then return false, it means that not all elements in your array are unique.
If no, add element to HashMap.
After for-for loop return true.
As a beginning programmer, choose basic solutions without the sophistication of more complex parts of the library that do in truth offer more power. The main thing for you here is to learn how to use 2D arrays.
You can do it very simply because of the hidden specification that you did not mention but is in the code. None of the numbers can be greater than N * N.
Start with pseudo-code. The basic algorithm is to have a checking array of length N * N. Put a marker in each element as you find the number in the source array, using the number as the index into the checking array. If there is already an element there, then the number is not unique. The code becomes something like this:
final int N = 10; // Your choice of N, or perhaps input it.
int [][] needsChecking = new int [N] [N]; // fill it up.
public boolean arrayIsGood (int [][] src) {
final int N2 = N * N;
boolean [] checker = new boolean [N2];
for (int i = 0; i < N2; i++) { // Initialize Checker
checker [i] = false;
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int value = src [i][j];
if ((value <= 0) || (value > N2))
return false;
if (checker [value - 1]) // already found
return false;
checker [value - 1] = true;
} // for j
} // for i
return true; // if we get here every element has passed.
} // arrayIsGood (int [][])
Some of the other answers are more elegant or more extensible or handle space usage better or may find the result faster, etc. But master the basics first.
public boolean verifyUniqueIntegers(int array []){
Set<Integer> set = new HashSet<>(array.length);
for (int i : array)
{
if (set.contains(i))
return false;
set.add(i);
}
return true;
}
or maybe:
public boolean verifyUniqueIntegers(Integer array []){
return new HashSet<>(Arrays.asList(array)).size() == array.length;
}
I am trying to find the index of an array. My array is the following:
char[] closingBrackets = { ')', ']', '}', '>' };
when I do:
int i = openingBrackets.indexOf(']');
or
int i = openingBrackets.indexOf(]);
Eclipse gives me an error then recommending that I change it to openingBrackets.length which is not what I want.
I want in this case for i to hold the value 1 since it is the second item in the array. Where am I going wrong? Or is there another library that I should be using to find this?
indexOf is a method for Strings. To see where the element is at, loop through the array, checking each value to see if it matches, and when you get to it, return the number of the loop tracking in (the int)
int index;
for(int i = 0; i < array.length; i++) {
if(array[i] == ']') {
index = i;
}
}
Arrays dont have methods. You could use
int index = Arrays.asList(closingBrackets).indexOf(']');
provided closingBrackets is defined as a Character array
Character[] closingBrackets = { ')', ']', '}', '>' };
First, you can't call indexOf on an array. I think you are getting confused with ArrayList. To find the index of an object in an array, make a method like this: (this would require you to make it an Character[])
public static <E> int indexOf(E[] array, E item) {
for (int i = 0; i < array.length; i++)
if(array[i].equals(item))
return i;
throw new InvalidParameterException("Item not in array.");
}
Or you could convert the array to an ArrayList<Character> and call the method indexOf(int).