Reputation: 1141
I have a two set of vector and I need to insert second set in each of the first set element and print.
my input is like : {RED,BLUE,GREEN},{CSK,MI,RCB}
my output is like : {RED,CSK},{RED,MI},{RED,RCB},{BLUE,CSK},{BLUE,MI},{BLUE,RCB},{Green,CSK},{Green,MI},{Green,CSK}
I tried my code like this. Can you please suggest the way
public static void main(String[]args){
Vector v = new Vector();
v.addElement("RED");
v.addElement("BLUE");
v.addElement("GREEN"");
Vector v2 = new Vector();
Vector v3 = new Vector();
v2.addElement("CSK");
v2.addElement("RCB");
v2.addElement("MI");
for(int i=0; i<v.size(); i++){
for(int j=0; j<v2.length; j++){
v3 = v(i).add(v2(j));
}
}
for(int i=0; i<v3.size(); i++){
System.out.println(v3);
}
}
Upvotes: 1
Views: 2613
Reputation: 1196
well I have a solution too..
public static void main(String[] args) {
Vector<String> v = new Vector<>();
v.addElement("RED");
v.addElement("BLUE");
v.addElement("GREEN");
Vector<String> v2 = new Vector<>();
Vector<String> v3;
Vector<Vector<String>> v4 = new Vector<>();
v2.addElement("CSK");
v2.addElement("RCB");
v2.addElement("MI");
for (String vector_v : v) {
for (String vector_v2 : v2) {
v3 = new Vector<>(); // this declares new vector every time and this new vector is
// added to v4 and thus the list goes
v3.add(vector_v2);
v3.add(vector_v);
v4.add(v3);
}
}
System.out.println(v4);
}
Upvotes: 3
Reputation: 109547
This is called a cartesian product and works as follows:
List<String> rgbs = Arrays.asList("RED", "GREEN", "BLUE");
List<String> modes = Arrays.asList("CSK", "MI", "RCB");
List<List<String>> cartesianProduct = new ArrayList<>();
for (String rgb : rgbs) {
for (String mode : modes) {
List<String> product = new ArrayList<>();
product.add(rgb);
product.add(mode);
cartesianProduct.add(product);
}
}
I did use a bit of new syntax and classes probably still unknown to you, but quite similar to your code.
The important point is that every element of the result is itself a combination of two strings. Here I used a List.
Upvotes: 3
Reputation: 1129
your expected output can be achived in below way.
public static void main(String[]args){
Vector v = new Vector();
v.addElement("RED");
v.addElement("BLUE");
v.addElement("GREEN");
Vector v2 = new Vector();
Vector v3 = null;
v2.addElement("CSK");
v2.addElement("RCB");
v2.addElement("MI");
for(int i=0; i<v.size(); i++){
for(int j=0; j<v2.size(); j++){
v3 = new Vector();
v3.add(v.get(i));
v3.add(v2.get(j));
System.out.println(v3);
}
}
// for(int i=0; i<v3.size(); i++){
// System.out.println(v3);
// }
from above
Upvotes: 2