Question: Need help with a programming assignment in java using recursion, NO LOOPS! Here are the two methods that I need to implement that I am
Need help with a programming assignment in java using recursion, NO LOOPS!
Here are the two methods that I need to implement that I am having trouble with:
void printPattern(int n)
Precondition: n>0 Postcondition: print a pattern of n+1 lines ( 0 to n ): line i (i = 0 to n) has i stars ("*"), followed by (n-i) stripes ("-")
For example, printPattern(3) prints:
--- *-- **- ***
hint: use a private recursive helper function, with more parameters, that does the work, e.g.:
private void printPattern(int stars, int stripes)
You may need another helper function...
ArrayList intersection( ArrayList AL1, ArrayList AL2)
Precondition: AL1 and AL2 are not empty, and elements in AL1 are unique, and elements in AL2 are unique, (but AL1 and AL2 can contain the same elements) Postcondition: return an ArrayList with elements that are in both AL1 and AL2, *** in the order they occur in AL1 ***, and *** leave AL1 and AL2 unchanged ***
For example:
ArrayList AL1 = new ArrayList(); ArrayList AL2 = new ArrayList(); AL1.add("a"); AL1.add("b"); AL1.add("c"); AL2.add("b"); AL2.add("c"); AL2.add("d"); AL2.add("e"); ArrayList intersect = A3.intersection(AL1,AL2); System.out.println(AL1 + " intersect " + AL2 + " = " + intersect); prints: [a, b, c] intersect [b, c, d, e] = [b, c] hint: What kind of helper method would you use here?
Below is the code I have written so far, but it does not work:
public void printPattern(int n) {
if (n>0)
helperPrintPattern(0,n);
}
//Helper method for printPattern
private void helperPrintPattern(int stars, int stripes ) {
if(stars< 0){
return;
}
else{
System.out.println();
printStars(stars);
printStripes(stripes - stars);
helperPrintPattern(++stars,--stripes);
}
}
//Helper method for stars
private void printStars(int i){
if (i!=0){
System.out.println("*");
printStars(i-1);
}
}
//Helper method for stripes
private void printStripes(int j){
if (j!=0){
System.out.println("-");
printStripes(j-1);
}
}
public ArrayList intersection(ArrayList AL1, ArrayList AL2) {
ArrayList empty = new ArrayList();
if(!AL1.isEmpty() && !AL2.isEmpty()){
intersection(AL1,AL2,empty,0,AL1.size()-1,0,AL2.size()-1);
}
return empty;
}
//Intersection helper function
private ArrayList intersection(ArrayList AL1,ArrayList AL2,ArrayList result, int Findex1, int Lindex1, int Findex2, int Lindex2){
if(Findex1<=Lindex1){
if(Findex2<=Lindex2){
if(AL1.get(Findex1).equals(AL2.get(Findex2))){
result.add(AL1.get(Findex1));
}
intersection(AL1,AL2,result,Findex1,Lindex1,++Findex2,Lindex2);
}
else{
intersection(AL1,AL2,result,++Findex1,Lindex1,Findex2,Lindex2);
}
}
return result;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
