예제 #1
0
  public List<String> findWords(char[][] board, String[] words) {

    if (board == null || words == null) {
      return new ArrayList<>();
    }

    Trie trie = new Trie();

    for (String word : words) {
      trie.insert(word);
    }

    Set<String> wordsList = new HashSet<>();

    for (int i = 0; i < board.length; i++) {
      for (int j = 0; j < board[0].length; j++) {
        StringBuilder word = new StringBuilder();
        boolean[][] used = new boolean[board.length][board[0].length];
        word.append(board[i][j]);
        search(used, board, word, i, j, trie, wordsList);
      }
    }

    return new ArrayList<>(wordsList);
  }
예제 #2
0
 public List<List<Integer>> palindromePairs(String[] words) {
   List<List<Integer>> ans = new LinkedList<List<Integer>>();
   Trie tree = new Trie();
   for (int i = 0; i < words.length; i++) tree.insert(words[i], i);
   for (int i = 0; i < words.length; i++) tree.searchPalindromePairs(ans, words[i], i);
   return ans;
 }
예제 #3
0
  private boolean add(String s, int index) {
    if (index == s.length()) {
      if (isWord) {
        return false;
      }

      isWord = true;

      return true;
    }

    char c = s.charAt(index);

    for (int i = 0; i < numChildren; i++) {
      if (child[i].ch == c) {
        return child[i].add(s, index + 1);
      }
    }

    // this code adds from the bottom to the top because the addChild method
    // checks for cyclic references.  This prevents quadratic runtime.
    int i = s.length() - 1;
    Trie t = createNode(s.charAt(i--));
    t.isWord = true;

    while (i >= index) {
      Trie n = createNode(s.charAt(i--));
      n.addChild(t);
      t = n;
    }

    addChild(t);

    return true;
  }
예제 #4
0
  public static void main(String[] args) throws NumberFormatException, IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    StringBuilder output = new StringBuilder();

    int cases = Integer.parseInt(bf.readLine());
    for (int i = 0; i < cases; i++) {
      bf.readLine(); // blank-line

      char[][] boogle = new char[4][4];
      for (int j = 0; j < 4; j++) {
        boogle[j] = bf.readLine().trim().toUpperCase().toCharArray();
      }

      String n = "";
      while (n.equals("")) {
        n = bf.readLine().trim();
      }
      int noWords = Integer.parseInt(n);
      Trie t2 = new Trie();
      for (int j = 0; j < noWords; j++) {
        t2.addWord(bf.readLine().trim().toUpperCase());
      }

      output.append("Score for Boggle game #" + (i + 1) + ": " + calculateScore(boogle, t2) + "\n");
    }
    System.out.print(output);
  }
예제 #5
0
 /**
  * get entry from Trie, return null if no entry is present yet *
  *
  * @param pos
  */
 List<CalculationNode> get(final int pos) {
   if (pos == 0) {
     return list;
   }
   final Trie child = children[changeStateNodes[pos - 1]];
   if (child == null) {
     return null;
   }
   return child.get(pos - 1);
 }
예제 #6
0
 /** set entry int Trie, create new entries if no entry is present yet * */
 void set(final List<CalculationNode> list, final int pos) {
   if (pos == 0) {
     this.list = list;
     return;
   }
   Trie child = children[changeStateNodes[pos - 1]];
   if (child == null) {
     child = new Trie();
     children[changeStateNodes[pos - 1]] = child;
   }
   child.set(list, pos - 1);
 }
예제 #7
0
  @Test
  public void testGetChildren() {
    Trie trie = new Trie();
    trie.add("aa");
    trie.add("ab");
    trie.add("bb");

    Node rootNode = trie.getRoot();
    assertEquals(2, rootNode.getChildren().length);
    assertEquals(2, rootNode.getChildren()[0].getChildren().length);
    assertEquals(1, rootNode.getChildren()[1].getChildren().length);
  }
예제 #8
0
  /**
   * Returns all of the words in the trie that begin with the specified prefix rooted at this node.
   * An array of length 0 is returned if there are no words that begin with the specified prefix.
   *
   * @param prefix String prefix.
   * @return Array of Strings.
   */
  public String[] getWords(String prefix) {
    Trie n = getNode(prefix);

    if (n == null) {
      return new String[0];
    }

    String[] arr = new String[n.size()];
    n.getWords(arr, 0);

    return arr;
  }
예제 #9
0
  @Override
  public void runAlgorithm() throws InterruptedException {
    setHeader("trieinsert", s.substring(0, s.length() - 1));
    if (s.compareTo("$") == 0) {
      addNote("badword");
    }

    TrieNode v = T.getRoot();
    v.mark();
    addNote("trieinsertnote");
    addStep("trierootstart");
    pause();
    v.unmark();
    hw = new TrieWordNode(T, s);
    hw.setColor(NodeColor.INSERT);
    addToScene(hw);
    hw.goNextTo(v);

    while (s.compareTo("$") != 0) {
      final char ch = s.charAt(0);
      hw.setAndGoNextTo(s, v);
      TrieNode w = v.getChildWithCH(ch);
      if (w != null) {
        addStep("trieinsertwch", "" + ch);
      } else {
        addStep("trieinsertwoch", "" + ch);
        w = v.addChild(ch, hw.x, hw.y);
      }
      w.setColor(NodeColor.CACHED);
      T.reposition();
      pause();
      v = w;
      v.setColor(NodeColor.INSERT);
      T.reposition();
      s = s.substring(1);
    }
    hw.setAndGoNextTo(s, v);
    final TrieNode w = v.getChildWithCH('$');
    if (w == null) {
      addStep("trieinserteow");
    } else {
      addStep("trieinsertneow");
    }
    pause();
    v.setColor(NodeColor.NORMAL);
    v = v.addChild('$', hw.x, hw.y);
    T.reposition();
    hw.setAndGoNextTo(s, v);
    beforeReturn();
  }
예제 #10
0
 public List<String> findWords(char[][] board, String[] words) {
   List<String> res = new ArrayList<String>();
   Trie trie = new Trie();
   for (String word : words) {
     trie.insert(word);
   }
   boolean[][] visited = new boolean[board.length][board[0].length];
   for (int i = 0; i < board.length; i++) {
     for (int j = 0; j < board[0].length; j++) {
       searchHelper(board, visited, res, trie, "", i, j);
     }
   }
   return res;
 }
예제 #11
0
  @Override
  public void run() {
    if (s.compareTo("$") == 0) {
      addNote("badword");
    }

    TrieNode v = T.getRoot();
    v.mark();
    addNote("trieinsertnote");
    addStep("trierootstart");
    mysuspend();
    v.unmark();
    T.hw = new TrieWordNode(T, s);
    T.hw.setColor(NodeColor.INSERT);
    T.hw.goNextTo(v);

    while (s.compareTo("$") != 0) {
      char ch = s.charAt(0);
      T.hw.setAndGoNextTo(s, v);
      TrieNode w = v.getChildWithCH(ch);
      if (w != null) {
        addStep("trieinsertwch", "" + ch);
      } else {
        addStep("trieinsertwoch", "" + ch);
        w = v.addChild(ch, T.hw.x, T.hw.y);
      }
      w.setColor(NodeColor.CACHED);
      T.reposition();
      mysuspend();
      v = w;
      v.setColor(NodeColor.INSERT);
      T.reposition();
      s = s.substring(1);
    }
    T.hw.setAndGoNextTo(s, v);
    TrieNode w = v.getChildWithCH('$');
    if (w == null) {
      addStep("trieinserteow");
    } else {
      addStep("trieinsertneow");
    }
    mysuspend();
    v.setColor(NodeColor.NORMAL);
    v = v.addChild('$', T.hw.x, T.hw.y);
    T.reposition();
    T.hw.setAndGoNextTo(s, v);
    beforeReturn();
  }
예제 #12
0
  public void initialise() {
    stateNode = stateNodeInput.get().toArray(new StateNode[0]);

    for (int i = 0; i < stateNode.length; i++) {
      stateNode[i].index = i;
    }
    // make itself known
    for (StateNode state : stateNode) {
      state.state = this;
    }

    nrOfStateNodes = stateNode.length;
    // allocate memory for StateNodes and a copy.
    stateNodeMem = new StateNode[nrOfStateNodes * 2];
    for (int i = 0; i < nrOfStateNodes; i++) {
      stateNodeMem[i] = stateNode[i];
      stateNodeMem[nrOfStateNodes + i] = stateNodeMem[i].copy();
    }

    // set up data structure for encoding which StateNodes change by an operation
    changeStateNodes = new int[stateNode.length];
    // Arrays.fill(changeStateNodes, -1);
    nrOfChangedStateNodes = 0;
    trie = new Trie();
    // add the empty list for the case none of the StateNodes have changed
    trie.list = new ArrayList<>();
  } // initAndValidate
예제 #13
0
 /**
  * 11) Colección de profesores distintos que trabajan para algún departamento de una universidad.
  *
  * @param universidad - universidad de la que buscar profesores que trabajan para algún
  *     departamento suyo
  * @return una lista enlazada de las entidades que son profesores que trabajan en algún
  *     departamento del parámetro universidad
  */
 public ListaEnlazada<String> profesoresDeUniversidad(String universidad) {
   ListaEnlazada<String> resultado = new ListaEnlazada<String>();
   int idUniversidad = arbolSujetosObjetos.obtenerValor(universidad);
   if (idUniversidad != -1) {
     Arista a;
     int nodoDepartamento;
     boolean recorridos[] = new boolean[sujetos + objetos];
     for (int i = 0; i < sujetos + objetos; ++i) recorridos[i] = false;
     // Búsqueda las aristas entrantes de idUniversidad con peso 'departamentoDe'
     for (int i = 0; i < nodosEntrantes.get(idUniversidad).size(); i++) {
       a = nodosEntrantes.get(idUniversidad).get(i);
       if (a.propiedad == idPropiedadDepartamentoDe && !recorridos[a.verticeObjetivo]) {
         nodoDepartamento = a.verticeObjetivo;
         recorridos[nodoDepartamento] = true;
         // El nodo es un departamento, buscar las aristas entrantes con peso 'trabajaPara'
         for (int j = 0; j < nodosEntrantes.get(nodoDepartamento).size(); j++) {
           a = nodosEntrantes.get(nodoDepartamento).get(j);
           if (a.propiedad == idPropiedadTrabajaPara && !recorridos[a.verticeObjetivo]) {
             recorridos[a.verticeObjetivo] = true;
             resultado.insertLast(listaSujetosObjetos.get(a.verticeObjetivo));
           }
         }
       }
     }
   }
   return resultado;
 }
예제 #14
0
 /**
  * 10) Colección de estudiantes distintos que cursan alguna asignatura de la que es encargado un
  * determinado profesor.
  *
  * @param profesor - profesor encargado de las asignaturas de las que se buscan los estudiantes
  * @return una lista enlazada de las entidades que son estudiantes de asignaturas que imparte el
  *     parámetro profesor
  */
 public ListaEnlazada<String> estudiantesDelProfesor(String profesor) {
   ListaEnlazada<String> resultado = new ListaEnlazada<String>();
   int idProfesor = arbolSujetosObjetos.obtenerValor(profesor);
   if (idProfesor != -1) {
     Arista a;
     int nodoAsignatura;
     boolean recorridos[] = new boolean[sujetos + objetos];
     for (int i = 0; i < sujetos + objetos; ++i) recorridos[i] = false;
     // Búsqueda las aristas salientes de idProfesor con peso 'encargadoDe'
     for (int i = 0; i < nodosSalientes.get(idProfesor).size(); ++i) {
       a = nodosSalientes.get(idProfesor).get(i);
       if (a.propiedad == idPropiedadEncargadoDe && !recorridos[a.verticeObjetivo]) {
         nodoAsignatura = a.verticeObjetivo;
         recorridos[nodoAsignatura] = true;
         // El nodo es una asignatura, buscar las aristas entrantes con peso 'cursa'
         for (int j = 0; j < nodosEntrantes.get(nodoAsignatura).size(); ++j) {
           a = nodosEntrantes.get(nodoAsignatura).get(j);
           if (a.propiedad == idPropiedadCursa && !recorridos[a.verticeObjetivo]) {
             recorridos[a.verticeObjetivo] = true;
             resultado.insertLast(listaSujetosObjetos.get(a.verticeObjetivo));
           }
         }
       }
     }
   }
   return resultado;
 }
예제 #15
0
  private static void searchWords(
      char[][] boogle,
      boolean[][] used,
      char[] currentWord,
      int pos,
      Set<String> foundWords,
      Trie t,
      int i,
      int j) {
    if (i < 0 || j < 0 || i > 3 || j > 3 || used[i][j]) { // out of bounds
      return;
    }
    char c = boogle[i][j];
    used[i][j] = true;
    currentWord[pos++] = c;

    SearchResult searchResult = t.searchWord(currentWord, pos);
    if (searchResult.isDictionaryWord) {
      String s = getWord(currentWord, pos);
      foundWords.add(s);
    } else if (!searchResult.wordBeginning) {
      used[i][j] = false;
      return;
    }

    searchWords(boogle, used, currentWord, pos, foundWords, t, i - 1, j - 1);
    searchWords(boogle, used, currentWord, pos, foundWords, t, i - 1, j);
    searchWords(boogle, used, currentWord, pos, foundWords, t, i - 1, j + 1);
    searchWords(boogle, used, currentWord, pos, foundWords, t, i, j - 1);
    searchWords(boogle, used, currentWord, pos, foundWords, t, i, j + 1);
    searchWords(boogle, used, currentWord, pos, foundWords, t, i + 1, j + 1);
    searchWords(boogle, used, currentWord, pos, foundWords, t, i + 1, j);
    searchWords(boogle, used, currentWord, pos, foundWords, t, i + 1, j - 1);
    used[i][j] = false;
  }
  /**
   * Define applicable categories in the subString.
   *
   * @param subString The substring to define.
   * @param normalizer The normalizer to use.
   */
  protected void define(StringWrapper.SubString subString, AbstractNormalizer normalizer) {
    final String string = subString.getNormalizedString(normalizer);

    if (trie.contains(string)) {
      subString.addCategory(category);
    }
  }
예제 #17
0
  public static void main(String[] args) {
    Trie trie = new Trie();
    trie.add("Causal");
    trie.add("absurd");
    trie.add("crappy");
    trie.add("spooky");
    trie.add("bullcrap");
    trie.add("bullshit");
    trie.add("Africa");
    trie.add("Asia");
    trie.add("Osiris");
    trie.add("Heman");
    trie.add("OhMyGod");

    trie.printAll();
  }
예제 #18
0
  private void dfs(char[][] board, int x, int y, Trie root, List<String> result) {
    char c = board[x][y];
    if (c == '#' || root.children[c - 'a'] == null) {
      return;
    }

    root = root.children[c - 'a'];
    if (root.word != null) {
      result.add(root.word);
      root.word = null;
    }

    board[x][y] = '#';
    if (x > 0) {
      dfs(board, x - 1, y, root, result);
    }

    if (x < board.length - 1) {
      dfs(board, x + 1, y, root, result);
    }

    if (y > 0) {
      dfs(board, x, y - 1, root, result);
    }

    if (y < board[0].length - 1) {
      dfs(board, x, y + 1, root, result);
    }

    board[x][y] = c;
  }
예제 #19
0
  public void search(
      boolean[][] used,
      char[][] board,
      StringBuilder word,
      int i,
      int j,
      Trie trie,
      Set<String> wordsList) {
    if (trie.search(word.toString())) {
      wordsList.add(word.toString());
      return;
    }

    if (trie.startsWith(word.toString())) {
      if (i > 0 && !used[i - 1][j]) {
        used[i - 1][j] = true;
        word.append(board[i - 1][j]);
        search(used, board, word, i - 1, j, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }

      if (i < board.length - 1 && !used[i + 1][j]) {
        used[i + 1][j] = true;
        word.append(board[i + 1][j]);
        search(used, board, word, i + 1, j, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }

      if (j > 0 && !used[i][j - 1]) {
        used[i][j - 1] = true;
        word.append(board[i][j - 1]);
        search(used, board, word, i, j - 1, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }

      if (j < board[0].length - 1 && !used[i][j + 1]) {
        used[i][j + 1] = true;
        word.append(board[i][j + 1]);
        search(used, board, word, i, j + 1, trie, wordsList);
        word.deleteCharAt(word.length() - 1);
      }
    }
  }
예제 #20
0
  private void addToTrie(Trie root, String word) {
    for (char c : word.toCharArray()) {
      int index = c - 'a';
      if (root.children[index] == null) {
        root.children[index] = new Trie();
      }
      root = root.children[index];
    }

    root.word = word;
  }
예제 #21
0
 /**
  * 7b) Colección de las clases que son superclase de una clase.
  *
  * @param clase - clase de la que se buscan las superclases
  * @return una lista enlazada de las superclases del parámetro clase
  */
 public ListaEnlazada<String> superClasesDe(String clase) {
   ListaEnlazada<String> resultado = new ListaEnlazada<String>();
   int idClase = arbolSujetosObjetos.obtenerValor(clase);
   if (idClase != -1) {
     boolean recorridos[] = new boolean[sujetos + objetos];
     for (int i = 0; i < sujetos + objetos; ++i) recorridos[i] = false;
     // Búsqueda en profundidad
     DFS(idClase, idPropiedadSubClaseDe, recorridos, resultado);
   }
   return resultado;
 }
예제 #22
0
  /**
   * Sets the character of this trie.
   *
   * @param c Character.
   * @throws IllegalArgumentException if this trie has a sibling with the same character.
   */
  public void setChar(char c) throws IllegalArgumentException {
    if (c == ch) {
      return;
    }

    if ((parent != null) && parent.hasChar(c)) {
      throw new IllegalArgumentException("duplicate chars not allowed");
    }

    ch = c;
  }
예제 #23
0
 /**
  * 8) Colección de entidades que son de una determinada clase.
  *
  * @param clase - clase de la que se buscan las entidades
  * @return una lista enlazada de las entidades que son del parámetro clase
  */
 public ListaEnlazada<String> entidadesDeClase(String clase) {
   ListaEnlazada<String> resultado = new ListaEnlazada<String>();
   int idClase = arbolSujetosObjetos.obtenerValor(clase);
   if (idClase != -1) {
     boolean recorridos[] = new boolean[sujetos + objetos];
     for (int i = 0; i < sujetos + objetos; ++i) recorridos[i] = false;
     // Búsqueda en profundidad hacia atrás
     DFSinversa(idClase, recorridos, resultado);
   }
   return resultado;
 }
예제 #24
0
    public List<String> findWords(char[][] board, String[] words) {

      Trie trie = new Trie();
      for (String word : words) {
        trie.insert(word);
      }

      int m = board.length;
      int n = board[0].length;

      boolean[][] visited = new boolean[m][n];

      for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
          dfs(board, visited, "", i, j, trie);
        }
      }

      return new ArrayList<String>(result);
    }
예제 #25
0
  /**
   * Removes the specified string from the trie. Returns true if the string was removed or false if
   * the string was not a word in the trie.
   *
   * @param s String.
   * @return true or false.
   */
  public boolean remove(String s) {
    Trie t = getNode(s);

    if ((t == null) || !t.isWord) {
      return false;
    }

    t.isWord = false;

    while ((t != null) && (t.numChildren == 0) && !t.isWord) {
      Trie p = t.parent;

      if (p != null) {
        p.removeChild(t);
      }

      t = p;
    }

    return true;
  }
  public static void main(String[] args) {
    Trie t = new Trie();
    t.insert("are");
    t.insert("area");
    t.insert("base");
    t.insert("cater");
    t.insert("cat");
    t.insert("basement");

    System.out.println(t.searchPrefix("cater"));
  }
예제 #27
0
 public void searchHelper(
     char[][] board, boolean[][] visited, List<String> res, Trie trie, String str, int i, int j) {
   int m = board.length;
   int n = board[0].length;
   if (i < 0 || i >= m || j < 0 || j >= n) {
     return;
   }
   if (!trie.startWith(word)) {
     return;
   }
   if (visited[i][j]) {
     return;
   }
   str = str + board[i][j];
   if (trie.search(str) && !res.contains(str)) {
     res.add(str);
   }
   visited[i][j] = true;
   searchHelper(board, visited, res, trie, str, i + 1, j);
   searchHelper(board, visited, res, trie, str, i - 1, j);
   searchHelper(board, visited, res, trie, str, i, j + 1);
   searchHelper(board, visited, res, trie, str, i, j - 1);
   visited[i][j] = false;
 }
예제 #28
0
  /**
   * Removes the specified trie from the child array. Does nothing if the specified trie is not a
   * child of this trie. Otherwise the parent of the trie is set to null.
   *
   * @param t Trie Object.
   */
  public void removeChild(Trie t) {
    for (int i = 0; i < numChildren; i++) {
      if (t == child[i]) {
        for (int j = i + 1; j < numChildren; j++) {
          child[j - 1] = child[j];
        }

        numChildren--;
        child[numChildren] = null;
        t.parent = null;

        break;
      }
    }
  }
예제 #29
0
    public void dfs(char[][] board, boolean[][] visited, String str, int i, int j, Trie trie) {
      int m = board.length;
      int n = board[0].length;

      if (i >= m || j >= n || i < 0 || j < 0) return;

      if (visited[i][j]) return;

      str = str + board[i][j];
      //   System.out.println(str);

      if (!trie.startsWith(str)) return;

      if (trie.search(str)) {
        result.add(str);
      }

      visited[i][j] = true;
      dfs(board, visited, str, i - 1, j, trie);
      dfs(board, visited, str, i + 1, j, trie);
      dfs(board, visited, str, i, j - 1, trie);
      dfs(board, visited, str, i, j + 1, trie);
      visited[i][j] = false;
    }
예제 #30
0
  /** return current set of calculation nodes based on the set of StateNodes that have changed * */
  private List<CalculationNode> getCurrentCalculationNodes() {
    List<CalculationNode> calcNodes = trie.get(nrOfChangedStateNodes);
    if (calcNodes != null) {
      // the list is pre-calculated
      return calcNodes;
    }
    // we need to calculate the list of CalculationNodes now
    try {
      calcNodes = calculateCalcNodePath();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }

    trie.set(calcNodes, nrOfChangedStateNodes);

    //    	System.err.print(Arrays.toString(changeStateNodes) + ":");
    //    	for (CalculationNode node : calcNodes) {
    //    		Log.warning.print(node.m_sID + " ");
    //    	}
    //    	System.err.println();

    return calcNodes;
  } // getCurrentCalculationNodes