Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- public class WordGram {
- private String[] myWords;
- private int myHash;
- public WordGram(String[] words, int start, int size){
- //store size strings from the array source, starting at index start
- //store into a private instance variable of wordgram class being constructed
- myWords = Arrays.copyOfRange(words, start, start+size);
- }
- public int hashCode(){
- //return a value based on all the strings in myWords
- for(int i=0; i < myWords.length; i++){
- myHash += i*i*myWords[i].hashCode();
- //myHash += (myWords[i].hashCode() * (i+1) * myWords[i].hashCode());
- }
- return myHash;
- }
- public boolean equals(Object other){
- //for loop that checks if each elem in this is the same as other
- if(!(other instanceof WordGram)) return false;
- WordGram wg = (WordGram) other;
- for(int i=0; i < wg.length(); i++){
- if(! (this.myWords[i].equals(wg.myWords[i]))){
- return false;
- }
- }
- return true;
- }
- public int compareTo(WordGram o){
- //convert into something we can compare to
- StringBuilder comp1 = new StringBuilder();
- StringBuilder comp2 = new StringBuilder();
- for(int i=0; i<o.length(); i++){
- comp1.append(o.myWords[i]);
- }
- for(int j=0; j<this.myWords.length; j++){
- comp2.append(this.myWords[j]);
- }
- return comp2.toString().compareTo(comp1.toString());
- }
- public int length(){
- return myWords.length;
- }
- public String toString(){
- StringBuilder str = new StringBuilder();
- str.append("{");
- for(int i=0; i<myWords.length; i++){
- if(i+1 == myWords.length){
- str.append(myWords[i]);
- str.append("}");
- }
- else{
- str.append(myWords[i]);
- str.append(", ");
- }
- }
- return str.toString();
- }
- public WordGram shiftAdd(String last){
- //get this.mywords and make it to an arraylst
- //add last to it
- //arraylst splice to remove the first elem
- ArrayList<String> arrylst = new ArrayList<String>(Arrays.asList(this.myWords));
- arrylst.add(last);
- ArrayList<String> narrylst = new ArrayList<String>(arrylst.subList(1, arrylst.size()));
- String[] word = narrylst.toArray(new String[narrylst.size()]);
- WordGram wgrm = new WordGram(word, 0, word.length-1);
- return wgrm;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement