- #1
lypena35
- 18
- 0
Hello,
I am stuck on this java problem. I was wondering if anyone can figure out what I am doing wrong. Thank you!
Problem
1. Given an array of ints, return true if there is a 1 in the array with a 2 somewhere later in the array.
ex: has12([1, 3, 2]) → true
has12([3, 1, 2]) → true
has12([3, 1, 4, 5, 2]) → true
2. Given two arrays of ints sorted in increasing order, outer and inner, return true if all of the numbers in inner appear in outer. The best solution makes only a single "linear" pass of both arrays, taking advantage of the fact that both arrays are already in sorted order.
ex:
linearIn([1, 2, 4, 6], [2, 4]) → true
linearIn([1, 2, 4, 6], [2, 3, 4]) → false
linearIn([1, 2, 4, 4, 6], [2, 4]) → true
My Code.
//linearIn method goes here
I am stuck on this java problem. I was wondering if anyone can figure out what I am doing wrong. Thank you!
Problem
1. Given an array of ints, return true if there is a 1 in the array with a 2 somewhere later in the array.
ex: has12([1, 3, 2]) → true
has12([3, 1, 2]) → true
has12([3, 1, 4, 5, 2]) → true
2. Given two arrays of ints sorted in increasing order, outer and inner, return true if all of the numbers in inner appear in outer. The best solution makes only a single "linear" pass of both arrays, taking advantage of the fact that both arrays are already in sorted order.
ex:
linearIn([1, 2, 4, 6], [2, 4]) → true
linearIn([1, 2, 4, 6], [2, 3, 4]) → false
linearIn([1, 2, 4, 4, 6], [2, 4]) → true
My Code.
Code:
public class ArrayProblems{
public static void main(){
int[] a = {1,3,2};
int[] b = {3,1,2};
int[] c = {3,1,4,5};
int[] d = {1,2,4,6};
int[] e = {1,2,4,4,6};
int[] f = {2,4};
int[] g = {2,3,4};
boolean test1 = has12(a);
boolean test2 = has12(b);
boolean test3 = has12(c);
System.out.println("Test 1: " + test1); //should print true
System.out.println("Test 2: " + test2); //should print true
System.out.println("Test 3: " + test3); //should print false
System.out.println("Test 4: " + lieanrIn(d,f)); //should print true
System.out.println("Test 5: " + lieanrIn(d,g)); //should print false
System.out.println("Test 6: " + lieanrIn(e,f)); //should print true
}
[U] //has12 method goes here[/U]
public int has12(int[]array){
int indexOf1=0;
int indexOf2=0;
int i=0;
int j=0;
for( i=0,i<=array.length,i++){
if (array[i]==1){
indexof1=i;
break
}
}
if (i== array.length){
return false;
}
for(i=indexOf1+1<=array.length){
if (array[i]==1){
idexof2=i;
break
}
}
if(i==array.length){
return false;
}
if(indexOf1<indexof2){
return true;
}
//linearIn method goes here
Code:
public int linearIn(int[]a,int[]b){
for(i=0, i<b.length,i++){
for(i=0,i<a.length,i++){
if(a[j]==b[i]){
i=i+1;
}
if(j==a.length){
return false;
}
}
}
return true;
}
}
}