• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

for loop logic problem

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

I'm designing a project which has become quite big & complex, so can't explain it here. Hwr, I invented a similar abstract problem that if solved I think can be applied to my code. Below is the code, along with comments that describe what I want it to do. I have tried to keep it as simple as possible, the code can be copied and pasted into any main method, here it is:-

// Aim of the program is to get the ints out of the 2 int arrays, and put them in a combined array
// However, I have initialised the combined array's index[0], index[2], index[4] and [6] to array1's ints (using 'cac' variable)
// Now I want to program an algorithm that will search array2 for the same int as array1,
// These ints should be stored in combined_array[1],[3],[5],and [7]
// Basically I want combined_array to have the values stored in this order:-
// 3,3,2,2,1,1,2,2

int array1 [] = {3,2,1,2}; // int array1
int array2 [] = {1,2,3,2}; // int array2
int combined_array [] = new int [array1.length + array2.length]; // combined_array, will hold values of array1and2
int cac=0, cac2=1; // combined array counters, used in for()s below
for (int i=0; i<array1.length; i++) {
combined_array[cac] = array1[i]; // initialise combined_array to array1, starting at combined_array[0], then
cac+= 2; // // combined_array[2],[4], and finally [6]
}//~for

int a=0, b=0; // placeholders for array1 & 2 values

for (int i=0; i<array1.length; i++) // loop through array1
{
a = array1[i];
for (int j=0; j<array2.length; j++) // loop through array2 searching for the matching value
{
b = array2[j];
if (a==b & cac2 < combined_array.length) { // check if the int stored in array1 = int in array2
combined_array[cac2]=array2[j]; // if it's the same store it in combined_array
cac2 += 2; // increase the counter
}//~if

}//~for
}//~for

for (int i=0; i<combined_array.length; i++) { // print out values stored in combined_array[]
System.out.print(combined_array[i] + "\t"); // trying to get: 3,3,2,2,1,1,2,2
// however, can only get 3,3,2,2,1,2,2,1
} System.out.println("\n\n"); // pagebreak

[ June 04, 2006: Message edited by: Moh ]

[ June 04, 2006: Message edited by: Moh ]

[ June 04, 2006: Message edited by: Moh ]
[ June 05, 2006: Message edited by: Mohammed Malik ]
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

On your way in you may have overlooked our naming policy, which requires that all display names be real (sounding) names consisting of a first and last name. You need to go here and fix yours right away. Thanks.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have two very simple bugs that can be found with a few println's.

Just add a few println's when you set the variables a and b, and when you set the members of the array (along with their indexes) and you should quickly see your problem.

Henry
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
it is best to set ur system up into iterations

array1 = {3,2,1,2}
array2 = {1,2,3,2}

combined_array = new int[8]
combined_array = {3, ,2, ,1, ,2, }

for(i=0; i <4; i++)
for(j=0; j<4; j++)

i=0
a = 3
j=0 j = 1 j=2 j=3
b=1 b = 2 b = 3 b=2
b4 if
cac2 = 1 cac2=1 cac2=1 cac2=3
after if
cac2 = 1 cac2=1 cac2=3 cac2=3

i=1
a=2

j=0 j=1 j=2j=3
b=1b=2b=3b=2
b4 if
cac2=3 cac2=3cac2=5 cac2=5
after if
cac2=3cac2=5cac2=5cac2=7

as you can see after i=0 j=0
the combined array will look as such {3,3,2, ,1, ,2, }
after i=1 j=0
the array will look as such {3,3,2,2,1,2,2,} because there are two 2's and cac2 will be incremented twice and two will be put into position combined_array[3] and combined_array[5] and cac2 will now point to position combined_array[7] in which it will place the 1 after i making the combined_array = {3,3,2,2,1,2,2,1}

as {3,2,1,4} and {1, 4,2,3} or any mixture of the first array.
by having an element twice, you are risking that the condition will be met twice and will occur
 
Mohammed Malik
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ernest Friedman-Hill:
Hi,

Welcome to JavaRanch!

On your way in you may have overlooked our naming policy, which requires that all display names be real (sounding) names consisting of a first and last name. You need to go here and fix yours right away. Thanks.



Hi 2u2 sorry about that, itz now changed.
 
Mohammed Malik
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by stephen shields:
as you can see after i=0 j=0
the combined array will look as such {3,3,2, ,1, ,2, }
after i=1 j=0
the array will look as such {3,3,2,2,1,2,2,} because there are two 2's and cac2 will be incremented twice and two will be put into position combined_array[3] and combined_array[5] and cac2 will now point to position combined_array[7] in which it will place the 1 after i making the combined_array = {3,3,2,2,1,2,2,1}

as {3,2,1,4} and {1, 4,2,3} or any mixture of the first array.
by having an element twice, you are risking that the condition will be met twice and will occur




Thanks for ur reply Stephen,

Do u know if there's a way of telling Java something like "look at the array elements, if the element has been seen before, please ignore in the next iteration" - This would solve the repeated element being found problem, but I'm not sure how to code it..

I was thinking I might have to use a dynamic array that deletes the element at it's index position once it has been found, then making a new array (with updated size, ie size-1) to store the remaining elements, which is then used in future searches..

This problem is one of those things humans can do really easily, but (that I find at least) is very hard to put into words, using the rules of Java. I'm goning to try to solve this problem later tonight, wish me luck!

PS: there was a simple line of code wrong in my original post where I put " b = array1[j];", obviously this should be " b = array2[j];" - I've editted it if anyone else would like to try a hand at this problem
 
Henry Wong
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Do u know if there's a way of telling Java something like "look at the array elements, if the element has been seen before, please ignore in the next iteration" - This would solve the repeated element being found problem, but I'm not sure how to code it..



You can force the loop to skip the current iteration, and go to the next iteration of the loop, with the "continue" keyword.

You can force the loop to skip all remaining iterations, and break out of the loop, with the "break" keyword.

Henry
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Here is your code which I modified with simple changes and works fine
hope this helps.

public class TestForLoopAnju{
public static void main(String[] args){
int array1 [] = {3,2,1,2}; // int array1
int array2 [] = {1,2,3,2}; // int array2
int combined_array [] = new int [array1.length + array2.length]; // combined_array, will hold values of array1and2
int cac=0, cac2=1; // combined array counters, used in for()s below


for (int i=0; i<array1.length; i++) { //loop thru array1
combined_array[cac] = array1[i]; // initialise combined_array to array1, starting at combined_array[0], then
System.out.print(combined_array[cac]+ "\t" ); // trying to get: 3,3,2,2,1,1,2,2
for (int j=0; j<array2.length; j++) {// loop through array2
if (combined_array[cac] == array2[j]) { //checks for exact match and if found then enters the loop
cac+= 1; //increments the combined_array index before assigning the value to combined_array
combined_array[cac] = array2[j]; //assigns second array value to combined_array
break; // breaks the for loop once the match is found and moves on to the first for loop
}

}
System.out.print(combined_array[cac]+ "\t" ); // trying to get: 3,3,2,2,1,1,2,2
cac+=1; //increment combined_array index to assign the next value of first array.
}
}

}

Thanks
 
Anju Kumar
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry I missed out to remove cac2 variable.
you can remove that, not required in the above code
 
Mohammed Malik
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Anju for your reply,

Your code is very good - I have learnt alot from it. There is one small problem with it, but that's due to me not explaining what I was trying to do properly. I think I should never post an abstract example on these forums again! I hope I'm forgiven (I haven't posted on a programming forum for a few years now). The only problem with the code is that the final '2' in array1, is being matched with the 1st '2' in the array2 (I wanted it matched with the 2nd '2' in array2).

Some of you may have wondered why I don't just clone array1 & then put it in the combined array - the reason is that the project I'm working on, not only contains ints, but other bits of information (which can't be matched) specific to what I called 'array2'.

Anyways, here's the code modified with new names & using vectors. I haven't used vectors much, and this took a few hours to figure out (initialising them is so much different than arrays). On the off-chance someone might have to do something similar, please find the code below (name the java file 'MatchingIntsWithVectors'). Thanks again to Anju, Stephen & Henry for comments and help


import java.util.Vector;
public class MachingIntsWithVectors{ // abstract matching ints demo
public static void main(String args[]) {

// trying to get: 3,3,2,2,1,1,2,2

Vector <Integer> v1 = new Vector<Integer>(); // initialise v1 vector (without generix x)
Integer a1 [] = {3,2,1,2}; // size is automatically set when adding elements
for (int i=0; i<a1.length; i++){ // add elements to vector using array
v1.add(a1[i]);
//System.out.print(v1.get(i) + " "); // debug
}

Vector <Integer> v2 = new Vector<Integer>(); // v2 vector
Integer a2 [] = {1,2,3,2};
for (int i=0; i<a2.length; i++){ // add elements to vector using array
v2.add(a2[i]);
//System.out.print(v2.get(i) + " "); // debug
}

Integer cvdef = -1; // needed to init cv vector's size in below for()
Vector <Integer> cv = new Vector<Integer>(); // Combined Vector
for (int i=0; i<v1.size() + v2.size(); i++) {
cv.add(cvdef);
}

int cvc=0; // Combined Vector Counter

for (int i=0; i<v1.size(); i++) //loop thru v1
{

cv.set( cvc, v1.get(i) ); // initialise cv to v1, starting at cv[0], then all remaining even indexes

//System.out.print(cv.get(cvc)+ "\t" ); // print out cv's even no indexes
for (int j=0; j<v2.size(); j++) // loop through v2
{
if (cv.get(cvc) == v2.get(j) ) //checks for exact match and if found then enters the loop
{
cvc+= 1; //increments the cv index before assigning the value to cv
cv.set(cvc, v2.get(j) ); //assigns second array value to cv
v2.remove(j); // remove this value so it's not found agn (only wana find & match ints once)
break; // breaks the for loop once the match is found and moves on to the first for loop
}//~if
}//~for
//System.out.print(cv.get(cvc)+ "\t" ); // print out vc's odd no indexes
cvc+=1; //increment cv index to assign the next value
}//~for
// */

// Print entire cv Vector
for (int i=0; i<cv.size(); i++){
System.out.print(cv.get(i) + " "); // debug
} System.out.print("\n" + cv.size() + "\n" + v2.size()); // size of cv & v2 printed (v2 should be 0, once all matches found)

System.out.println("\n\n"); // page-break

}//~main()
}//~class
[ June 07, 2006: Message edited by: Mohammed Malik ]
 
If I had asked people what they wanted, they would have said faster horses - Ford. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic