public boolean has12(int[] nums) {
int onePlace=0;
int twoPlace=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1){
onePlace=i;
}
if(nums[i]==2){
twoPlace=i;
}
}
return (twoPlace>onePlace);
}
public boolean has12(int[] nums) {
int onePlace=0;
int twoPlace=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1){
onePlace=i;
}
if(nums[i]==2){
twoPlace=i;
}
}
return (twoPlace>onePlace);
}
Expected Runi think i am good on this unless you want to make some suggestions on improvement, corrections?
has12([1, 3, 2]) → true true OK
has12([3, 1, 2]) → true true OK
has12([3, 1, 4, 5, 2]) → true true OK
has12([3, 1, 4, 5, 6]) → false false OK
has12([3, 1, 4, 1, 6, 2]) → true true OK
has12([2, 1, 4, 1, 6, 2]) → true true OK
has12([2, 1, 4, 1, 6]) → false false OK
has12([3, 5, 9]) → false false OK
has12([3, 5, 1]) → false false OK
has12([3, 2, 1]) → false false OK
has12([1, 2]) → true true OK
has12([1, 1]) → false false OK
has12([1]) → false false OK
has12([]) → false false OK
other tests
OK
By hand, what should the answer be for:
5 1 6 2 7 7 8 1 0 9//yes
Does your program agree with your by hand answer?// let me start eclipse in debug mode and double check it
Another one is the given termination criteria.sure. how to achieve above?
And last but not least there is a simple restructuring possible to minimize the number of if-tests.
other two points.
>> By hand, what should the answer be for: 5 1 6 2 7 7 8 1 0 9//yes
>> Does your program agree with your by hand answer?// let me start eclipse in debug mode and double check it
OK. Reason I gave you this case is that your program should produce a different result. Also, for this small program, it is useful to walk through the program by hand to see what result you come up with. Then walk through in the debugger. If you do that, you get three results, not all the same. Which one(s) is/are correct?
Given an array of ints, return true if there is (not like all 1's to say 5 1 6 2 7 7 8 1 0 9 false due to bolded 1 )a 1 in the array with a 2 somewhere later in the array.
has12([1, 3, 2]) → true
has12([3, 1, 2]) → true
has12([3, 1, 4, 5, 2]) → true
public boolean has12(int[] nums) {
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 1) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == 2) {
return true;
}
}
}
}
return false;
}
By hand, what should the answer be for:
5 1 6 2 7 7 8 1 0 9
Does your program agree with your by hand answer?