Reputation: 23
I had a coding interview and this question was given. Given a string of words, break up that string into words and output them on separate lines not to exceed N characters long per line. The sample given to me was "A red sweater." and a line length of 8. The words can't be broken up and you have to fit as many words per line as you can. So, for the given example, "A" & "red" would fit on one line and "sweater." added to that line is over the allowed length of characters, so it would get output on a new line.
I started out by splitting the String into a String []. Then created a method that took in the String [] and the line length. I made some assumptions on the edge cases and then looped through the String [].This is where I got very confused on what could I use to represent a single line and how to add a subarray on a single line. I looked up algorithms that will find all subarrays that get close to a sum, but it appeared that it recycles elements and I can't do that.
This is as far as I got before the time ran out:
import java.util.ArrayList;
import java.util.List;
class Solution {
public static void main(String[] args) {
String sentence = "A red sweater.";
String[] words = sentence.split(" ");
Solution newSol = new Solution();
System.out.println(newSol.convertToLines(words, 8));
}
public List<String> convertToLines(String[] myArr, int bound) {
List<String> result = new ArrayList<String>();
if (myArr.length == 0) {
return result;
}
for (int i = 0; i < myArr.length; i++) {
if (myArr[i].length() > bound) {
System.out.println("One or more words is larger than your boundary");
break;
}
//This is where I got into trouble
//This doesn't account for more than 2 elements
//nor how I would output them on separate lines
if (myArr[i].length() + myArr[i].length() <= bound) {
result.add(myArr[i] + " " + myArr[i + 1]);
} else {
result.add(myArr[i]);
}
}
return result;
}
}
I searched all over for this particular problem and couldn't find it. I assume that there is a pattern or something I am missing, but after hours messing with it, I'm still at a loss as where to go from here. I have never coded something similar to this. While it's too late for the interview, I would still like to know how this could be solved so that I can learn from it and keep on learning.
Upvotes: 2
Views: 1489
Reputation: 1666
Gabriel Rouleau's code above will skip a lot of words when iterating in the loop.
For example in string "A red sweater." it will loop for "A", add to line
variable then "red" is added to line
variable then sweater is iterated but not added to line variable. It is never revisited to be added in the next line.
Fixing that problem by iterating with the primitive for loop syntax and decrementing the iteration index if a word needs to be revisited for the next line.
String sentence = "A red sweater with some other stuff.";
String[] words = sentence.split(" ");
int bound = 8;
if(words.length == 0) return;
String line = "";
Boolean first = true;
for (int i = 0; i < words.length; i++) {
if(first) {
line = words[i];
first = false;
} else {
if ((line + " " + words[i]).length() < bound) {
line += " " + words[i];
} else {
System.out.println(line);
line = words[i];
first = true;
i--;
}
}
}
System.out.println(line);
Also, this code fixes the problem that the original question was having (Considering more than 2 elements).
Code tested and runs successfully!
Upvotes: 1
Reputation: 335
For best practices the constants like Limit length per word is to do on constants.
So first lets create a constant variable.
final int MAX_WORDS_PER_LINE = 8;
Lets guess you have a String array with sentences:
String[] sentences = {"Hello World Im learning.", "Other Word here"};
So out logic will be like this. We will iterate for each sentence on sentences. And after that for each word on sentence.
So our code will look like this.
// We use StringBuilder to save the word that we need to print.
StringBuilder wordToPrint = new StringBuilder();
for (String sentence: sentences) {
// for each sentence we will save the words like this:
String[] words = sentence.split(" ");
// there we will iterate for each word on words
for(String word: words) {
// and check if length of word that we have to print + current word length is more than max words length per line.
if (wordToPrint.length() + word.length() > MAX_WORDS_PER_LINE) {
//So if its true we need to print that word and clear the word to print.
System.out.println(wordToPrint);
wordToPrint.delete(0, wordToPrint.length());
}
// So everytime we need to append an space and the current word.
wordToPrint.append(" ").append(word);
}
}
Upvotes: 1