If I want to compare index 0 with index 1, 2 and 3 for instance, how is that possible?
boolean iftrue = false;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < i; j++) {
if (IntValue(array[j]) == IntValue(array[i + j])) {
iftrue = true;
}
}
}
return iftrue;
}
Just to put Sotirios' suggestion into code... Recall he suggested you save the first elem and compare other elements against it.
public boolean sameAsFirstElem(int[] array) {
boolean isEqual = false;
int firstElem = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == firstElem) {
return true;
}
}
return isEqual;
}
Take 0th element is an variable and go on searching from 1st index onward. If you find the match stop else go all the way upto end of the array and report that match not found. This can be done in linear time O(N) where N is the size of the array. No need to have two loops and hence increase the time complexity to O(N^2)
boolean sameAsFirstElem(Object[] array) {
boolean isEqual = false; //Assume match will not be there, if we come across any,
// we will set it to true
int firstElement = IntValue(array[0]);
for (int i = 1; i < array.length; i++) {
if (IntValue(array[i]) == firstElement) {
isEqual = true; //Indicating that match has found
}
}
return isEqual;
}
I am assuming that IntValue(Object) return int, and hence the int firstElement, and taking Object as a parameter.
Related
I am looking to return true if all the elements in A are found within B and false otherwise. Currently, I have written the code below but the function seems to only return false.
public static boolean con(int[] a, int[] b) {
if (a == null || a.length == 0) {
return false;
}else if (b == null || b.length == 0) {
return false;
}
for (int i = 0; i < a.length; i++)
{
for (int j = i + 1; j < b.length;j++)
{
if (a[i] == (b[j])) {
return true;
}
}
}
return false;
}
It is easy to make mistakes when you program with indices. Luckily, in this case there is no need to do that:
public static boolean con(int[] a, int[] b) {
loop: for (int ai : a) {
for (int bi : b) {
if (ai == bi) {
continue loop;
}
}
return false;
}
return true;
}
Always use the strengths of the language, not the weaknesses.
There are a couple of issues in your code as pointed out in the comments that are causing your code to return false, however, the other issue is that your return true if a[i] == (b[j]) which will be true and cause a return if the first element in the array is a match regardless of the rest of the array and if it matches or not.
Here is a working version with comments that help explain what has been changed:
public static boolean con(int[] a, int[] b) {
//Use a flag to track if the integers are found
Boolean flag = true;
//return false for null or 0 length
if (a == null || a.length == 0 || b == null || b.length == 0) {
return false;
}
//Check integers
for (int i = 0; i < a.length; i++){
//Use an inner flag to track each integer
Boolean innerFlag = false;
//Start the inner loop from 0 and incriment it
//Only use j = i if you need the integers to be in order?
for (int j = 0; j < b.length; j++){
if (a[i] == (b[j])) {
//we can not return from the method until all elements are checked
//so set the flag instead and break so the next element can be checked
innerFlag = true;
break;
}
}
//if an element does not exist we can set the flag false and break and return immediatly
if (innerFlag == false){
flag = false;
break;
}
}
return flag;
}
Why you use the int j = i + 1 and not just j to compare all b from the beginning of the array with j = 0... anyway if you change that and test it with two equals filled array it will give true at the first element, and if the array are different will give you true when both coincide, but you are not storing the results in any place,
I think what you could do is add a counter with the length of a:
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (a[i] == (b[j])) {
count--;
if(count == 0)
return true;
}
It kinda work, test it thoroughly and tell me.
If you really want to do it manually, you could use something like this:
private static boolean containsAll(Integer[] arrayA, Integer[] arrayB) {
Set<Integer> matches = new HashSet<>();
boolean containsAll = false;
for (int i = 0; i < arrayA.length; i++) {
for (int j = 0; j < arrayB.length; j++) {
if (arrayA[i] == arrayB[j]) {
matches.add(arrayA[i]);
}
}
}
if (matches.size() == arrayA.length) {
containsAll = true;
}
return containsAll;
}
Since a set can only store unique values, even if arrayB has duplicated elements, it will still work. It won't work if arrayA has duplicated elements, though.
elementIsUsed(int curYPos, int curXPos, int nextYPos, int nextXPos)
if curYPos == nextYPos && curXPos == nextXPos in array[][], return true.
How do I iterate over a (long) array[][] to reach my solution?
I've tried iterating using a for loop but this gives me an error.
for(index = 0; index < array.length; index++)
{
if(array[curYPos][curXPos] == array[nextYPos][nextXPos])
{
isUsed = true;
}
}
Question Summary:
Given two String arrays, return an integer representing how many matches are between them (ignore duplicates).
Real Answer:
http://www.javaproblems.com/2013/11/java-ap-1-commontwo-codingbat-solution.html
My Code
public int commonTwo(String[] a, String[] b) {
int count = 0;
boolean done = false;
for (int i = 0; i<a.length-1; i++){
if(a[i].equals(a[i+1])){
i++;
for (String j:b)
if (a[i].equals(j) && !done){
done = true;
count++;
}
}
else{
for (String j:b)
if(a[i].equals(j) && !done){
done = true;
count++;
}
}
done = false;
if(i == a.length-2)
for (String j:b)
if (a[i+1].equals(j) && !done){
done = true;
count++;
}
}
return count;
}
Image of output: [1]: http://i.stack.imgur.com/0esjC.png
So what it was intended to do was to go through all of the array a,if it equals the next one then go to that index, then add to count if there's a match between the arrays. The done boolean was used to make it so it doesn't add to count if there're duplicates of b that matches a and to end it once a match is found.
Lastly,
if(i == a.length-2)
was intended to make it so if it's the second before the last index number (as the last index number won't be checked in some cases), and not the same as the last index number, then it would check for matches for the last index number after checking the one before the last essentially. I understand why both errors occur and was wondering what could be done to fix it, particularly for the second one/comments on the code. Also, a third issue I notice would be (["a"], ["a"]) → 1 but the code will result in 0.
This question can be done is linear time O(N) that is a single traversal of both arrays a and b.
You should increment i as long as same string appears.So
if(a[i].equals(a[i+1]))
i++;
should be replaced by
while(i+1<a.length&&a[i].equals(a[i+1])){
i++;}
Also you do not need to go through entire array b for a single string of array a since both are in alphabetical order.You should only compare the string from the array b as long there is no match.Once a match is found then you should remember that index and next time matching should continue from that index onwards for the array b
Also you don't need the boolean variable done.
Keeping these things in mind the correct code is:
public static int commonTwo(String[] a, String[] b) {
int count = 0;
int j=0,i;
for (i = 0; i<a.length-1&&j<b.length-1;){
//SKIP DUPLICATES FOR ARRAY a
while(i+1<a.length&&a[i].equals(a[i+1])){
i++;}
//SKIP DUPLICATES FOR ARRAY b
while(j+1<b.length&&b[j].equals(b[j+1])){
j++;}
//MATCH THE STRINGS FROM ARRAY a AND ARRAY b
while(i<a.length&&j<b.length&&a[i].compareTo(b[j])!=0)
{
//INCREMENT I IF STRING IN ARRAY a IS LESS THAN STRING IN ARRAY b
if(a[i].compareTo(b[j])<0)
++i;
//INCREMENT J IF STRING IN ARRAY b IS LESS THAN STRING IN ARRAY a
else ++j;
}
//IF ABOVE LOOP BREAKS BECAUSE OF MATCH
if(i<a.length&&j<b.length)
{count++; ++j; ++i;}
}
//IF THE LAST ELEMENT OF ARRAY a IS LEFT FOR COMPARISON
if(i==a.length-1)
{
while(j<b.length)
{
//SKIP DUPLICATES OF ARRAY b
while(j+1<b.length&&b[j].equals(b[j+1]))
++j;
if(a[i].equals(b[j]))
{++count;}
++j;
}
}
//IF THE LAST ELEMENT OF ARRAY b IS LEFT FOR COMPARISON
if(j==b.length-1)
{
while(i<a.length)
{
//SKIP DUPLICATES OF ARRAY a
while(i+1<a.length&&a[i].equals(a[i+1]))
++j;
if(a[i].equals(b[j]))
++count;
++i;
}
}
return count;
}
This is the simplest solution i could come up with that uses only one loop.
public int commonTwo(String[] a, String[] b) {
int count = 0;
int i = 0;
int j = 0;
String s = "";
while (i < a.length && j < b.length) {
if (a[i].compareTo(b[j]) < 0)
i++;
else if (a[i].equals(b[j]) && a[i] != s) {
s = a[i];
count++;
i++;
j++;
}
else j++;
}
return count;
}
public int commonTwo(String[] a, String[] b) {
int ctr = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
if (i > 0 && a[i] == b[j] && a[i] != a[i - 1]) {
ctr++;
break;
} else if (i == 0 && a[i] == b[j]) {
ctr++;
break;
}
}
}
return ctr;
}
I am trying to write a program using two methods that determines if a sub array is located within an array. subArray() is supposed to receive two arrays and return the index of the start of the sub array within the array. If the sub array is not located in the array it returns -1. subArray() then calls subArrayAppearsAt() and passes in the two arrays and a location. subArrayAppearsAt() is supposed to return true if the sub array is located in the array starting at the location passed in, false otherwise.
Currently if I pass in array {1,2,3} and sub array {2,3}, it returns 2 as the starting position but it should return 1.
If I pass in array {1,2,3,4,5} and sub array {4}, it returns -1, but it should return 3.
Does anyone see why this might be happening?
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
else
return -1;
}
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i) {
{
if (subArray[0] == largeArray[i])
{
boolean subArrayFound = true;
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
subArrayFound = false;
j=subArray.length;
}
/* Sub array found - return its index */
if (subArrayFound==true)
{
return true;
}
}
}
}
/* Return default value */
return false;
}
Look at this part
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
it sets result every time it goes through the loop. If you test if {4} is conatined in {1, 2, 3, 4, 5} it will set result to the return value of subArrayAppearsAt(array, subArray, 4); which will return false
So for that problem you could do something like
for ( i = 0; i <= limit; i++) {
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
The other problem is, that i will be incremented after it goes into the for-loop the last time, and then you return that value. That problem should be solved with my code solution too.
I didn't test my solution but it should work ;)
EDIT
Sorry that wasn't all correct. Your subArrayAppearsAt() returns true too early. Edit your subArrayAppearsAt() function to this and it should work
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i)
{
if (subArray[0] == largeArray[i])
{
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
return false;
}
}
return true;
}
return false;
}
The problem is that if you want to know the start position you should put the if that checks the result inside de loop
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++){
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
}
public static void main(String[] args) {
int[] first = {1,2,4,5,3,2,1,3,4,5,6,33,432,21,5};
int[] second = {2,1};
System.out.println(findpos(first, second));
}
private static int findpos(int[] a, int[] b){
for(int i=0; i<a.length; i++){
if(a[i]!=b[0]){
continue;
}
if(a.length - i < b.length) return -1;
int itemp = i;
boolean found = true;
for(int j=0; j<b.length; j++){
if(itemp < a.length && a[itemp]!=b[j]){
found = false;
}
itemp++;
}
if(found){
return i;
}
}
return -1;
}
I am writing a program with multiple methods, and one of them asks to find the index where the second strings starts in the rightmost area of the first string.
The method accepts two strings as parameters and returns the character index of the position where the second string begins in the rightmost area of the first.
For example:
IN: mississippi, ss
OUT: 5
The catch of this method is that I can only use charAt, substring and length from the String class, and no other class methods.
With the help of some users from this site, we came up with this:
public static int findInStr1(String s1, String s2) {
for (int i = 0; i < s1.length() - s2.length(); i++) {
boolean found = true;
for (int j = 0; j < s2.length(); j++) {
if (s1.charAt(i) != s2.charAt(j)) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
The above method gives me the index where string 2 starts in string 1, but I am trying to code a method that gives me the index of where string 2 starts in the rightmost area of string 1.
You can adjust your method to scan the first String from the right to the left :
public static int findInStr1(String s1, String s2) {
for (int i = s1.length() - 1; i >= s2.length() - 1; i--) {
boolean found = true;
for (int j = s2.length() - 1; j >= 0; j--) {
if (s1.charAt(i-(s2.length()-1-j)) != s2.charAt(j)) {
found = false;
break;
}
}
if (found) {
return i-s2.length()+1;
}
}
return -1;
}