Reputation: 65
I have an ArrayList which contains Strings with a size of 1000. I am looping through that ArrayList and finding words and trying to form a square from them. For example as follows:
C A R D
A R E A
R E A R
D A R T
It is working but it involves a lot of nested looping and I am hard-coding the loops in this instance where I am try to form a square 4x4.
I am looking to have the flexibility to pass in the square size for example 5x5 or 6x6 and so on and loop accordingly. How can I go about doing that.
If this was just a single loop, I would have just passed in an Integer and looped according to that Integer. But since I am nesting, the number of For loops needed is going to differ thus confused.
When I am forming a square of 4x4, I end up looping 4 times where each loops checks different substrings to derive a correct square. When 5x5 is needed, I would need 5 loops to make the checks. I mean to solve the issue where I increase decrease loops depending on the parameter/ or a way to loop without creating so many For Loops. Can I get some guidance on this please.
void makeWord(ArrayList<String> arr, int size){ //want to use this size to determine amount of loop
String first, second, third, fourth;
for (int i = 0; i < arr.size(); i++) {
first = arr.get(i);
for (int j = 0; j < arr.size(); j++) {
if(first.substring(1,2).equals(arr.get(j).substring(0,1)) &&
(!first.equals(arr.get(j)))){
second = arr.get(j);
}
else {
second = " ";
}
if (!second.trim().isEmpty()) {
for (int k = 0; k < arr.size(); k++) {
if (first.substring(2, 3).equals(arr.get(k).substring(0, 1)) &&
second.substring(2, 3).equals(arr.get(k).substring(1, 2)) &&
(!first.equals(arr.get(k)) && (!second.equals(arr.get(k))))) {
third = arr.get(k);
} else {
third = " ";
}
}
}
}
}
}
Upvotes: 1
Views: 67
Reputation: 13845
I think the following code snipped solves your issue:
public static void printSqaure(List<String> list, int size){
for(int i=0; i< list.size(); i++){
if(i <= size){
String subStr = list.get(i).substring(0, size);
System.out.println(subStr);
}
}
}
Upvotes: 0
Reputation: 334
I am not completely sure if I got your question right, but if you are looking for a way to make your code more flexible so that you can build squares of any size, your main problem is the way you are storing the strings.
Since your loops depend on the number of strings you define, you limit yourself by hardcoding the string variables. Alternatively you could simply store the text in an array matrix like so:
String[][] matrix = new String[size][size];
This allows you to build squares of any size and furthermore you do not need all those substring()
calls anymore, what will supposingly increase performance, too.
Upvotes: 0