In Java please, it is ok to use stack or queue or string builder but no hash set
ID: 3672045 • Letter: I
Question
In Java please, it is ok to use stack or queue or string builder but no hash set
. Write a recursive method that will find and list all of the one-element sequences of a letters in a char[] array, then all the two-element sequences, then all of the three ele- letters in a char[] array, then all the two-element sequences,then all of the three ele- ment sequences, and so on, such that the characters in each sequence appear in the r as they are in the array. For example, for the following arrays char[] letters = {'A', 'C', 'E', 'G'); the one-element sequences are "A", "C", "E", and "G" the two-element sequences are "AC", "AE", "AG", "CE", "CG", "EG" the three-element sequences are "ACE", "ACG", "AEG", "CEG" the four-element sequence is "ACEG"Explanation / Answer
import java.util.ArrayList; import java.util.List; import muset.Alphabet.Letter; public class Sequence { private final List letters; public final Alphabet alphabet; public Sequence(Alphabet alphabet, List letters) { super(); this.letters = letters; this.alphabet = alphabet; } public Letter letterAt(int i) { return letters.get(i); } /** * * @param letter * @return A new Sequence containing all the letters in this plus an additional one at the end. */ public Sequence append(Letter letter) { List result = new ArrayList(letters); result.add(letter); return new Sequence(alphabet, result); } public int length() { return letters.size(); } @Override public String toString() { return letters.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((letters == null) ? 0 : letters.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Sequence other = (Sequence) obj; if (letters == null) { if (other.letters != null) return false; } else if (!letters.equals(other.letters)) return false; return true; } /** * * @param string * @return A sequence where each letter is on Character long */ public static Sequence buildSimpleSequence(Alphabet alphabet, String string) { List result = new ArrayList(string.length()); for (char c : string.toCharArray()) result.add(alphabet.getLetter("" + c)); return new Sequence(alphabet, result); } public Sequence subsequence(int fromIndex, int toIndex) { return new Sequence(alphabet, letters.subList(fromIndex, toIndex)); } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.