Consider the following class: public class Sequence { private ArrayList<Integer>
ID: 3566327 • Letter: C
Question
Consider the following class:
public class Sequence
{
private ArrayList<Integer> values;
public Sequence() { values = new ArrayList<Integer>(); }
public void add(int n) { values.add(n); }
public String toString() { return values.toString(); } }
Add a method
public Sequence append(Sequence other)
that creates a new sequence, appending this and the other sequence, without modify- ing either sequence.
For example, if a is
1 4 9 16
and b is the sequence
9 7 4 9 11
then the call a.append(b) returns the sequence
1 4 9 16 9 7 4 9 11
without modifying a or b.
------------------
Add a method
public Sequence merge(Sequence other)
to the Sequence class of above exervise that merges two sequences, alternating ele- ments from both sequences. If one sequence is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer sequence. For example,
if a is
1 4 9 16
and b is
9 7 4 9 11
then a.merge(b) returns the sequence
1 9 4 7 9 4 16 9 11
without modifying a or b.
Explanation / Answer
package vijay;
import java.util.ArrayList;
import java.util.Iterator;
public class Sequence {
private ArrayList<Integer> values;
public Sequence() { values = new ArrayList<Integer>(); }
public void add(int n) { values.add(n); }
public String toString() { return values.toString(); }
public Sequence append(Sequence other)
{
Sequence sn=new Sequence();
Iterator<Integer> it=values.iterator();
while(it.hasNext())
sn.add(it.next());
Iterator<Integer> it1=other.values.iterator();
while(it1.hasNext())
sn.add(it1.next());
return sn;
}
public Sequence merge(Sequence other)
{
int c=0;
Sequence sn=new Sequence();
Iterator<Integer> it=values.iterator();
Iterator<Integer> it1=other.values.iterator();
while(it.hasNext()||it1.hasNext()){
if(c<values.size()){
sn.add(it.next());}
if(c<other.values.size()){
sn.add(it1.next());}
c++;
}
/*while(it1.hasNext())
sn.add(it1.next());*/
return sn;
}
public static void main(String[] args) {
Sequence s=new Sequence();
s.add(1);
s.add(4);
s.add(9);
s.add(16);
Sequence s1=new Sequence();
s1.add(9);
s1.add(7);
s1.add(4);
s1.add(9);
s1.add(11);
Sequence snew=s.append(s1);
Sequence snew1=s.merge(s1);
Iterator<Integer> it1=snew.values.iterator();
System.out.println("append results are...");
while(it1.hasNext())
System.out.println(it1.next());
Iterator<Integer> it11=snew1.values.iterator();
System.out.println("merge results are...");
while(it11.hasNext())
System.out.println(it11.next());
}
}
o/p:
append results are...
1
4
9
16
9
7
4
9
11
merge results are...
1
9
4
7
9
4
16
9
11
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.