Having trouble checking an array - java

I'm supposed to search through a character array for another character array. The problem that I'm having is that I am supposed to check if the words match as well. Also, I keep getting an out of bounds exception when the search term is longer than the original string.
The charArray is the array of the search term.
The indexArray is the char array of the original string.
public int indexOf(String parameter) { //does same thing as previous method but with a String instead
int index = -1;
char charArray[] = parameter.toCharArray();
int counter = 0;
for (int i = 0; i < indexArray.length; i++) { //goes through the array and find which array element is = to the char
if (indexArray[i] == charArray[0]) { //checks if the index is equal to the first AND second letter of the word
for (int j = i; j < charArray.length; j++) {
if (indexArray[j] == charArray[j]) {// this is where the Exception java.lang.ArrayIndexOutOfBoundsException: 14 error happens
counter++;
}
if (counter == charArray.length) {
index = i;
return index;
}
}
}
}
return index;
}

Say if the indexArray is "grape" and charArray is "pineapple". At i = 3, indexArray[i] == charArray[0] returns true. Now you set j = 3 and check until j < 9, and obviously indexArray[j] will give you an ArrayIndexOutOfBoundsException.
You should change it to:
// There is no point to check indices that the subsequent string is shorter than the search string.
for (int i = 0; i < indexArray.length - charArray.length; i++) {
if (indexArray[i] == charArray[0]) {
for (int j = 0; j < charArray.length; j++) {
if (indexArray[i + j] == charArray[j]) {
// ...
}
}
}
}

Related

How to check for duplicates in an entire 2d array? [duplicate]

This question already has answers here:
How do i find and count duplicates in a 2 dimensional array?
(4 answers)
Closed 5 years ago.
I am a beginner coder just learning arrays. I recently learned 2d arrays and I am trying to find out if there is a duplicate in a 2d array. I know how to check if there is a duplicate in the same column or row, but I cannot figure out how to compare a number if it is not in the same column or row as the number I am trying to compare it to. Here is my code as of now:
public static boolean correctNumbers(int[][] values) {
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
int num = values[i][j];
for (int k = j + 1; k < values.length; k++) {
if (num == values[i][k] || num > values.length * values.length || num < 1) {
return false;
}
}
for (int l = i + 1; l < values.length; l++) {
if (num == values[l][j] || num > values.length * values.length || num < 1) {
return false;
}
}
}
}
return true;
}
I need to create a method and I cannot use any other methods in creating it.
Thanks for the help!
Edit: It returns false if there is duplicates in the array, a number in the array is less than 1, or greater than total number of elements in the array. In other words this method is checking to see if the array contains all the values of 1 to (i*j) in the array. I realized I did a bad job of explaining that part. Thanks again!
You can simplify the logic by saving the numbers into a hashset and when you're iterating them check each one if it's already there (meaning duplicate) otherwise add it:
public static boolean correctNumbers(int[][] values) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values[i].length; j++) {
int num = values[i][j];
if (set.contains(num)) {
return false;
}
set.add(num);
}
}
return true;
}
EDIT
We can use an array for the same functionality the hashset is doing in the code above:
public static boolean correctNumbers(int[][] values) {
int n = values.length;
int[] dict = new int[n * n + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j < values[i].length; j++) {
int num = values[i][j];
if (num < 1 || num > n || dict[num] != 0) {
return false;
}
dict[num] = 1;
}
}
return true;
}

Removing duplicate characters in a String array

I have a sample input like [q w e r r t] and I want to remove duplicates and print [q w e r t] with arrays. I don't see why the output is different for the below code snippet.
for(int j=0; j< array.length; j++) {
for(int k=j+1; k< array.length; k++) {
if(array[j] == array[k]) {
continue;
}
System.out.print(array[j] + " ");
j = k;
}
}
Update: I wanted to use this logic for a sorted array. I used Arrays.sort(). I changed == to .equals() for Strings.
public static void main(String args[]) throws IOException {
// Enter size of array and assert the type of input
System.out.println("Enter size of array in integers");
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("Please enter integers");
sc.next();
}
;
// Accepting the values into the array and sorting them
int demoInt = sc.nextInt();
String[] array = new String[demoInt];
String[] outputMarkers = new String[demoInt];
System.out.println("Enter the values");
for (int i = 0; i < array.length; i++) {
Scanner scNum = new Scanner(System.in);
array[i] = scNum.next();
if (i == array.length - 1) System.out.println("Array is full");
}
Arrays.sort(array);
System.out.printf("Sorted array is : %s", Arrays.toString(array));
//Checking for duplicates //Sample: a a a s d f
for (int j = 0; j < array.length; j++) {
for (int k = j + 1; k < array.length; k++) {
if (array[j].equals(array[k])) {
continue; //returns to for loop with increment
}
System.out.print(array[j] + ". ");
j = k;
}
}
}
Input: a a a d f
Output: a d f
Your problem is that you are checking each character against all the characters after it. Imagine an array with no duplicates; once you get to the last character, you have printed out all the characters before it. But when j = array.length - 1, then k = array.length, and the second for loop does not run at all, and your last character will never be printed.
Your code would always fail to print the last element correctly. The only case in which it would be correct is if your last element is a duplicate of a previous element, but not of the second-to-last element.
Try this code instead:
outerloop:
for (int j = 0; j < array.length; j++) {
for(int k = 0; k < j; k++) {
if(array[j] == array[k]) {
continue outerloop;
}
}
System.out.print(array[j] + " ");
}
The premise of the code is that it loops through each of the characters. If it matches any of the previous characters, the code skips that element and continues to the next one.
EDIT: Looks like you edited the question for a sorted array instead. That means if the last element is a duplicate, it will be a duplicate of the element before it so we don't have to worry about the corner case in my previous block of code.
for(int j=0; j< array.length; j++) {
for(int k=j+1; k< array.length; k++) {
if(array[j] == array[k]) {
continue;
}
System.out.print(array[j] + " ");
j = k;
}
}
System.out.print(array[array.length-1] + " ");
If you are looking to remove the values rather than just skip over them when printing, you will want to start from the end of your array and work towards 0, calling array.remove(i) when you find an object that matches a previously checked object.
Though that is just to do it as a loop exercise. It would be easier to push your array into a Set.
You can use a Boolean array of size 122, make all the values in the array as false, iterate the give character array, if the ASCII value of character is false, thena make it true and print it.
Below is the example code, here I have taken a string and removing all the duplicates and printing the resulting string:
static String removeDuplicate(String s) {
boolean[] flagArr = new boolean[122];
int sLength = s.length();
StringBuilder resultStr = new StringBuilder();
for (int i = 0; i < sLength; i++) {
char tempChar = s.charAt(i);
int tempVal = (int) tempChar;
if (!flagArr[tempVal]) {
flagArr[tempVal] = true;
resultStr.append(tempChar);
}
}
return resultStr.toString();
}
The complete code is at
Removing Duplicate Characters From String Without Using Set | jain Tarun Blog
Why not use only one loop ?
//assuming array has length >= 2
System.out.print(array[0] + " ");
for(int j=1; j< array.length; j++) {
if(array[j] == array[j - 1]) {
continue;
}
System.out.print(array[j] + " ");
}

WAP to return the length of longest common substring between two strings

Two strings are given and we have to find the length of longest common substring. I don't know what's wrong with my code.
The outer loop takes a substring of B and the inner loop increases the substring by one character at a time.
For the input "www.lintcode.com code", "www.ninechapter.com code" the output is coming 5 but it should be 9
public class Solution {
/**
* #param A, B: Two string.
* #return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
int k = 0, temp = 0;
if(B.length() == 0){
return 0;
}
for(int i = 0; i < B.length()-1; i++){
String bb = B.substring(i, i+1);
if(A.contains(bb)){
for(int j = 1; j < A.length()-i; j++){
String bbb = B.substring(i, i+j);
if(!A.contains(bbb))
break;
temp = bbb.length();
}
}
if(temp > k)
k = temp;
}
return k;
}
}
Just replace this:
for(int j = 1; j < A.length()-i; j++)
with this:
for(int j = 1; j < B.length()-i+1; j++)
I believe you could reduce your function size a little with this...not sure if your method is more efficient or not though...
public int longestCommonSubstring(String A, String B) {
int longestSubstring = 0;
for (int x=0; x < A.length(); x++) {
for (int y=x; y < A.length() + 1; y++) {
String testString = A.substring(x,y);
if (B.contains(testString) && (testString.length() > longestSubstring)) {
longestSubstring = testString.length();
}
}
}
return longestSubstring;
}

How can I change the indexes in field?

I have a field a[] inside is 1, 5, 3, 2, 4
when i reach number 3 in for loop i want to send it(number 3) to the end of field so it will have index 4 and indexes of other numbers (2 and 4) have to be one less a[2] = 2, a[3] = 4
How can i do that? It can be a field with for example 100 values in.
Thanks for the reply!
My program look like this:
for(int i = 0; i < a.length; i++) {
if(a[i] == 3) {
// i dont know what have to go there
}
}
int match = 3;
for(int i = 0; i < a.length; i++) {
if(a[i] == match) {
a[i] = a[i+1];
a[i+1] = a[i+2];
a[i+2] = match;
}
}
Note that there is ZERO error checking
[edit] With some safety (no 'need' for error checking in this version as I just move the entire array one position to the left and put the match variable at the end.
int match = 3;
for(int i = 0; i < a.length; i++) {
if(a[i] == match) {
for int j = i; j < a.length-1; j++) {
a[j] = a[j+1];
}
a[j] = match;
break;
}
}
}
[/edit]

Move left if there is a zero

I am trying to create a program that will take an array of integers, say {2,0,32,0,0,8} that can be of any length, and make it so all of the nonzero numbers are to the left at the lower indexes, and all the zeros are moved to the end.
For example, {2,0,32,0,0,8} becomes {2,32,8,0,0,0}.
This array can be of any length and contain any nonnegative integers.
This is what I have so far:
public static int[] moveLeft(final int[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
for (int j = 0; j < a.length; j++) {
if (a[j] == 0) {
a[j] = a[i];
a[i] = 0;
}
}
}
}
return a;
}
However, when I do this, it doesn't work for the first and second characters. If I have {1,2,0,1} it will return {2,1,1,0} when it should return {1,2,1,0}. Any help?
Your inner loop should stop before index i. Change this
for (int j = 0; j < a.length; j++) {
to
for (int j = 0; j < i; j++) {
And then your code works for me.

Categories