Finding the index of an array - java

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).

Related

Last element index of an array with larger size

char[] someArray = new char[10];
someArray[0] ='a';
someArray[0] ='b';
someArray[0] ='c';
I want to add 'd' at the 4th position. How to get to the index which is one greater than the last valid element index in the array? someArray.length-1 is returning 9. I want to get 4th position?
EDIT:
The code should be:
char[] someArray = new char[10];
someArray[0] ='a';
someArray[1] ='b';
someArray[2] ='c';
In this case I am aware of the fact that 4th index is free. If I have:
void abc(int[] x){
//I want to add element in the next free index of the array x.
}
Indexing in arrays starts from 0.
When you do someArray.length-1, it takes the length as it was initialized using char[] someArray = new char[10];
If you wish to reach the 4th location in your array, start counting from the 0th index and you would find that you need to use index 3 in your array and hence you might want to use someArray[3] = desired_value
You can use a method to find out the index number of the first empty location in an array :
public static int getFirstEmptyIndex(char[] arr){
int index=0;
for(char a:arr){
if(a==0)
break;
else
index++;
}
return index;
}
public static void main(String[] args) {
char[] someArray = new char[10];
someArray[0]='a';
someArray[1]='b';
someArray[2]='c';
someArray[getFirstEmptyIndex(someArray)]='d';
System.out.println(someArray[3]);
}
First of all, but doing someArray[0] = .. you set the char in the first position of the array, and you override this value in this position in your code.
Secondly, the answer to your question is by doing someArray[3] = 'd'.
All elements in your array are valid, as long you are not reaching an index which is beyond your array size.
here is what I think you need, it's similar to #Mohsen answer, just I think this will be more readable and straight forward.
private int nextFree(char[] arr){
int i = 0;
for(Character x : arr){
if(x == 0)
return i;
i++;
}
return -1;
}
So you will get -1 if no free space rather than getting 0 and accidentally replacing index 0 value.
Bonus::
if you which to get all the free space as an array in Ascending order, look below:
private int[] allFree(char[] ar){
int s = 0;
for(char c : ar){
if(c==0)
s++;
}
int[] k= new int[s];
s=0;
int ss=s;
for(char c : ar){
if(c==0){
k[ss] = s;
ss++;
}
s++;
}
return k;
}
By the way, this is not the best algorithm for such operations, let anyone feel free to improve this.

Matching subsequence of length 2 (at same index) in two strings

Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. For instance a and b is respectively "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
What is wrong with my solution?
int count=0;
for(int i=0;i<a.length();i++)
{
for(int u=i; u<b.length(); u++)
{
String aSub=a.substring(i,i+1);
String bSub=b.substring(u,u+1);
if(aSub.equals(bSub))
count++;
}
}
return count;
}
In order to fix your solution, you really don't need the inner loop. Since the index should be same for the substrings in both string, only one loop is needed.
Also, you should iterate till 2nd last character of the smaller string, to avoid IndexOutOfBounds. And for substring, give i+2 as second argument instead.
Overall, you would have to change your code to something like this:
int count=0;
for(int i=0; i < small(a, b).length()-1; i++)
{
String aSub=a.substring(i,i+2);
String bSub=b.substring(i,i+2);
if(aSub.equals(bSub))
count++;
}
}
return count;
Why I asked about the length of string is, it might become expensive to create substrings of length 2 in loop. For length n of smaller string, you would be creating 2 * n substrings.
I would rather not create substring, and just match character by character, while keeping track of whether previous character matched or not. This will work perfectly fine in your case, as length of substring to match is 2. Code would be like:
String a = "iaxxai";
String b = "aaxxaaxx";
boolean lastCharacterMatch = false;
int count = 0;
for (int i = 0; i < Math.min(a.length(), b.length()); i++) {
if (a.charAt(i) == b.charAt(i)) {
if (lastCharacterMatch) {
count++;
} else {
lastCharacterMatch = true;
}
} else {
lastCharacterMatch = false;
}
}
System.out.println(count);
The heart of the problem lies with your usage of the substring method. The important thing to note is that the beginning index is inclusive, and the end index is exclusive.
As an example, dissecting your usage, String aSub=a.substring(i,i+1); in the first iteration of the loop i = 0 so this line is then String aSub=a.substring(0,1); From the javadocs, and my explanation above, this would result in a substring from the first character to the first character or String aSub="x"; Changing this to i+2 and u+2 will get you the desired behavior but beware of index out of bounds errors with the way your loops are currently written.
String a = "xxcaazz";
String b = "xxbaaz";
int count = 0;
for (int i = 0; i < (a.length() > b.length() ? b : a).length() - 1; i++) {
String aSub = a.substring(i, i + 2);
String bSub = b.substring(i, i + 2);
if (aSub.equals(bSub)) {
count++;
}
}
System.out.println(count);

Avoiding duplicates without Sets?

I am in a beginner Java class and I haven't gotten the chance to learn how to avoid duplicated values when storing values inside arrays.
String[] newAlphabet = new String[26];
for(int I = 0; I < newAlphabet.length; I++){
int random = (65 + (int)(Math.random() * ((90 - 65) + 1));
char ascii = (char)random;
String letters = ascii + "";
if(letters != newAlphabet[0] && letters != newAlphabet[1] ... so on and so on until
newAlphabet[25])
newAlphabet[I] = letters;
}//end
So this is my pseudo code for part of my program and the point of it is to avoid having duplicated letters inside the array.
The problem that I am having is inside the if statement. Instead of typing letters != newAlphabet[] to 25, is there another way of doing it?
I have seen some of the forums in stackedoverflow that I should use HashSet but I have not learned that? I can ask my teacher if I am allowed but is there another way to avoid this problem?
I have been thinking of using for-each loop to search through all the elements in the array but I haven't thought out the plan long enough if it's valid.
As you are talking about a beginner Java class, I am assuming you are fairly new to programming. So, rather than just give you a library function that will do it for you, let's walk through the steps of how to do this with just the basic code so you can get a better idea of what is going on behind the scenes.
Firstly, for any repetitive action, think loops. You want to check, for each letter in your new alphabet, if the one you are about to add matches it. So...
boolean exists = false; //indicates whether we have found a match
for (int j = 0; j < 26; j++) { //for each letter in the new alphabet
//true if this one, or a previous one is a match
exists = exists || letters == newAlphabet[i];
}
//if we don't have a match, add the new letter
if (!exists) newAlphabet[I] = letters;
Now, as you are building up your new alphabet as we go, we don't have a full 26 letters for most cases of running this code, so only check the parts of the new alphabet we have defined:
boolean exists = false;
for (int j = 0; j < I; j++) { //note in this line we stop before the insertion point
exists = exists || letters == newAlphabet[i];
}
if (!exists) newAlphabet[I] = letters;
Finally, we don't need to keep checking if we have already found a match, so we can change the loop to stop when we have found a match:
boolean exists = false;
int j = 0;
while (!exists && j < I) { //we now also stop if we have already found a match
exists = letters == newAlphabet[i];
//as we are stopping at the first match,
//we no longer need to allow for previous matches
}
if (!exists) newAlphabet[I] = letters;
You could use the asList method:
if( Arrays.asList(newAlphabet).contains(letters) ) {
newAlphabet[I] = letters;
}
It's not the most efficient, but since your array is only 26 elements long, I would favor clarity over efficiency.
Some explanation: asList is a static method on the Arrays class. This just means that we don't have to create an Arrays object to call it. We simply say Arrays.asList() and pass it the arguments. The asList method takes an array (newAlhpabet in this case) as a parameter, and builds a java.util.List out of it. This means that we can call List methods on the return value. contains() is a method on List that returns true if the List contains an element that is equal to the parameter (letters in this case).
Based on this line it looks like all you're trying to do is produce the letters A to Z in some other order:
int random = (65 + (int)(Math.random() * ((90 - 65) + 1));
If I'm understanding that right, then really all you're trying to do is shuffle the alphabet:
// Initialize new alphabet array
String originalAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] newAlphabet = originalAlphabet.toCharArray();
// Shuffle the new alphabet by swapping each character to a random position
for (int i=0; i<26; i++) {
int j = (int)(Math.random() * 26);
char temp = newAlphabet[i];
newAlphabet[i] = newAlphabet[j];
newAlphabet[j] = temp;
}
// Print the new alphabet
for (int i=0; i<26; i++) {
System.out.print(newAlphabet[i]);
}
System.out.println();
Here's a sample output: VYMTBIPWHKZNGUCDLRAQFSOEJX
You have a couple options.
Loop through the array and do basically what you're doing now.
Insert the characters in sorted order so you can perform binary search to determine if a letter is already in the list. As a bonus, if you use option 2, you'll already know the insertion point.
Check out Arrays.binarySearch(): http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
You could use this :
if(Arrays.binarySearch(newAlphabet, letters) < 0){
newAlphabet[I] = letters;
}
You should either include a while loop to make sure each index of the array is filled before moving to the next or you could make use of the return value of Arrays.binarySearch which is (-(insertion index) - 1) to fill the array and exit when the array is filled up.

how to delete array elements

Write a method deleteElement which takes as input an int[] and an int target and deletes all occurrences of target from the array. The method should return the newint[]
. Question to consider:
Why is it that we have to return an array and can't simply change the input parameter array?
public class warm5{
public static void main(String[] args){
int[] array1= {1,2,2,3,4,5,2};
int target1 = 2;
deleteElement(array1,target1);
public static int[] deleteElement(int[] array, int target){
for(int i = 0, i<array.length, i++){
if(array1[i] == target){
}
}
}
}
}
Here is what i wrote, im not sure how to continue it to remove the 2's in the array.
please help!
You can't delete elements from an array, by definition they're of fixed size. What you can do is create a new array, copy all the elements from the old array except the ones that you intend to delete and return the new array. Or, use an ArrayList, which has operations that allow removing elements:
public E remove(int index)
public boolean remove(Object o)
public boolean removeAll(Collection<?> c)
protected void removeRange(int fromIndex, int toIndex)
First, iterate through your array and figure out how many of your target element are present.
Once you know that, you know the size of your new array. As Oscar mentions, you can't "remove" from an array, you just make a new array without the elements you don't want in it.
int targetCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
targetCount++;
}
}
Now you know how many items will be in your new array: array.length-targetCount.
int[] newArray = new int[array.length-targetCount];
int newArrayIdx = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != target) {
newArray[newArrayIdx] = target;
newArrayIdx++;
}
}
Here we iterate through the old array and check each element to see if it's our target. If it's not, we add it to the new array. We have to keep track of our old array's index and our new array's index independently or we may risk trying to assign an index outside of the array bounds.
This is a common interview question. In the solution presented by Oscar you do not know what will be the size of the new array. So the solution does not work or is memory inefficient.
Trick is to loop over the array and at any time when you encounter an element equal to the given element you put that element towards the end of the array and swap it with the element that was there at the end position. By doing this you are collecting all occurrences of given element at the end of the array.
Here is a working logic
deleteElement(int[] given, int elem) {
int endIdx = array.length - 1;
for(int idx = 0; idx <= endIdx; idx++) {
if(given[idx] == elem) {
//swap idx with endIdx
int tmp = given[endIdx];
given[endIdx] = given[idx];
given[idx] = tmp;
endIdx--;
}
}
return Arrays.copyOfRange(given, 0, endIdx);
}

Java array analog for python list.index()?

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
}

Categories

Resources