Implement the stack family instance method flip declared as follows (this is a S
ID: 3811809 • Letter: I
Question
Implement the stack family instance method flip declared as follows (this is a Stack):/** * Reverses ("flips") {@code this} * * @ updates this * @ensures this = rev (#this) */public void flip(); Implement the sequence family instance method flip declared as follows (this is a sequence ):/** * Reverses ("flips"){@code this}. * *@updates this * @ ensures this = rev(#this) */public void flip (); Provide a second, different implementation of the instance method flip for Sequence. If your first implementation is iterative (i.e., uses a loop), your second one should be recursive and vice versa.Explanation / Answer
Included 3 parts in one program... please check
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.media.Track;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.Sequence;
/**
*
* @author paramesh
*/
public class Flips {
// 1) implemented recursively for stack<T>
public static <T> void flip(Stack<T> st) {
if (st.isEmpty()) {
return;
}
T e = st.pop();
flip(st);
addValueBottom(st, e);
}
private static <T> void addValueBottom(Stack<T> st, T val) {
if (st.isEmpty()) {
st.push(val);
return;
}
T temp = st.pop();
addValueBottom(st, val);
st.push(temp);
}
// 2) implemented iteratively
public static <T> void flip(Sequence t) throws InvalidMidiDataException {
// getting tracks of sequence
javax.sound.midi.Track[] track = t.getTracks();
// temp sequence to store the reversed sequence
Sequence sequence = new Sequence(Sequence.PPQ, 1);
javax.sound.midi.Track[] tempTrack = sequence.getTracks();
for(int i=track.length;i>0;i--){ // reversely storing tracks.. flipping
tempTrack[i] = track[i];
}
}
// 3) implementing recursively
public static <T> void flip(Sequence t, Sequence t1, int i, int j) throws InvalidMidiDataException {
// getting tracks of sequence
javax.sound.midi.Track[] track = t.getTracks();
javax.sound.midi.Track[] tempTrack = t1.getTracks();
if( i > 0){
tempTrack[j] = track[i];
i--;
j++;
flip(t,t1,i,j); // calling recursively
}
}
public static void main(String args[]) {
// creating stack
Stack<Integer> st = new Stack<Integer>();
st.push(1);
st.push(2);
st.push(3);
flip(st);
}
}