home - (5, 3) - (2, 0) - column 5, row 3 and column 2, row 0
Am I missing something?
public static void main(String[] args) {
int[][] wordSearch = new int[][]{
{'f', 'd', 'e', 'r', 'l', 'k'},
{'u', 's', 'a', 'm', 'e', 'o'},
{'l', 'n', 'g', 'r', 'o', 'v'},
{'m', 'l', 'p', 'r', 'r', 'h'},
{'p', 'o', 'e', 'e', 'j', 'j'}
};
//detectAllWords(wordSearch, "fuck", "ship");
for (Word word : detectAllWords(wordSearch, "home", "same")) {
System.out.println(word.toString());
}
/*
Expected result
home - (5, 3) - (2, 0)
same - (1, 1) - (4, 1)
*/
}
package com.codegym.task.task20.task2027;
import java.util.ArrayList;
import java.util.List;
/*
Word search
*/
public class Solution {
public static void main(String[] args) {
int[][] wordSearch = new int[][]{
{'f', 'd', 'e', 'r', 'l', 'k'},
{'u', 's', 'a', 'm', 'e', 'o'},
{'l', 'n', 'g', 'r', 'o', 'v'},
{'m', 'l', 'p', 'r', 'r', 'h'},
{'p', 'o', 'e', 'e', 'j', 'j'}
};
//detectAllWords(wordSearch, "fuck", "ship");
for (Word word : detectAllWords(wordSearch, "home", "same")) {
System.out.println(word.toString());
}
/*
Expected result
home - (5, 3) - (2, 0)
same - (1, 1) - (4, 1)
*/
}
public static List<Word> detectAllWords(int[][] wordSearch, String... words) {
List<Word> wordsFound = new ArrayList<>();
for (String word : words){
char[] wordLetters = word.toCharArray();
int firstLetter = wordLetters[0];
int lastLetter = wordLetters[wordLetters.length-1];
for (int i = 0; i < wordSearch.length; i++){
for (int j = 0; j < wordSearch[i].length; j++){
if (wordSearch[i][j] == firstLetter) {
for (int k = 0; k < wordSearch.length; k++){
for (int l = 0; l < wordSearch[k].length; l++) {
if (wordSearch[k][l] == lastLetter){
if ( !wordsFound.isEmpty() && wordsFound.get(0).getName().equals(word)) continue;
wordsFound.add(0, new Word(word));
wordsFound.get(0).setStartPoint(j, i);
wordsFound.get(0).setEndPoint(l, k);
}
}
}
}
}
}
}
return wordsFound;
}
public static class Word {
private String text;
private int startX;
private int startY;
private int endX;
private int endY;
public Word(String text) {
this.text = text;
}
private String getName(){
return this.text;
}
public void setStartPoint(int i, int j) {
startX = i;
startY = j;
}
public void setEndPoint(int i, int j) {
endX = i;
endY = j;
}
@Override
public String toString() {
return String.format("%s - (%d, %d) - (%d, %d)", text, startX, startY, endX, endY);
}
}
}