Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.HashMap;
  4. import java.util.List;
  5.  
  6. public class WordGram {
  7. private String[] myWords;
  8. private int myHash;
  9.  
  10.  
  11. public WordGram(String[] words, int start, int size){
  12. //store size strings from the array source, starting at index start
  13. //store into a private instance variable of wordgram class being constructed
  14.  
  15. myWords = Arrays.copyOfRange(words, start, start+size);
  16.  
  17. }
  18.  
  19. public int hashCode(){
  20. //return a value based on all the strings in myWords
  21. for(int i=0; i < myWords.length; i++){
  22. myHash += i*i*myWords[i].hashCode();
  23. //myHash += (myWords[i].hashCode() * (i+1) * myWords[i].hashCode());
  24. }
  25. return myHash;
  26.  
  27. }
  28.  
  29. public boolean equals(Object other){
  30. //for loop that checks if each elem in this is the same as other
  31. if(!(other instanceof WordGram)) return false;
  32. WordGram wg = (WordGram) other;
  33. for(int i=0; i < wg.length(); i++){
  34. if(! (this.myWords[i].equals(wg.myWords[i]))){
  35. return false;
  36. }
  37. }
  38. return true;
  39.  
  40. }
  41.  
  42. public int compareTo(WordGram o){
  43. //convert into something we can compare to
  44. StringBuilder comp1 = new StringBuilder();
  45. StringBuilder comp2 = new StringBuilder();
  46.  
  47. for(int i=0; i<o.length(); i++){
  48. comp1.append(o.myWords[i]);
  49. }
  50. for(int j=0; j<this.myWords.length; j++){
  51. comp2.append(this.myWords[j]);
  52. }
  53. return comp2.toString().compareTo(comp1.toString());
  54. }
  55.  
  56.  
  57. public int length(){
  58. return myWords.length;
  59. }
  60.  
  61. public String toString(){
  62. StringBuilder str = new StringBuilder();
  63. str.append("{");
  64. for(int i=0; i<myWords.length; i++){
  65. if(i+1 == myWords.length){
  66. str.append(myWords[i]);
  67. str.append("}");
  68. }
  69. else{
  70. str.append(myWords[i]);
  71. str.append(", ");
  72. }
  73. }
  74. return str.toString();
  75. }
  76.  
  77.  
  78. public WordGram shiftAdd(String last){
  79. //get this.mywords and make it to an arraylst
  80. //add last to it
  81. //arraylst splice to remove the first elem
  82.  
  83. ArrayList<String> arrylst = new ArrayList<String>(Arrays.asList(this.myWords));
  84. arrylst.add(last);
  85. ArrayList<String> narrylst = new ArrayList<String>(arrylst.subList(1, arrylst.size()));
  86. String[] word = narrylst.toArray(new String[narrylst.size()]);
  87. WordGram wgrm = new WordGram(word, 0, word.length-1);
  88. return wgrm;
  89.  
  90.  
  91.  
  92.  
  93. }
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement