In a program I’m writing in an unnamed language, I have a block of text for which the width is unknown, and all I know is the maximum width that this block of text could be. Given this information, I need to find out the smallest possible width that this text could be (assume that I can’t use the metrics of the characters / glyphs or the character count). So far I just have a brute force solution which looks like follows:
for (int i = .1; i < maxTextWidth; i += .1)
{
if (textFitsInGivenWidth(text, i))
{
textWidth = i;
break;
}
}
I’d like to try and optimize this as much as I can. My first thought was to use a binary search, but I’m having trouble implementing this in the proper way (and am not sure if it’s even possible). Does anyone have any suggestions on what I could do here to improve the run time using only what I’ve given in the above solution?
Binary Search is the answer indeed.
http://en.wikipedia.org/wiki/Binary_search_algorithm
for integer binary search, it can be:
The idea is, if you have
textFitsInGivenWidth(text, mid) == True,then you must have
textFitsInGivenWidth(text, i) == Truefor alli>=mid,and if it’s False, then you have
textFitsInGivenWidth(text, i) == Falsefor alli<=midso each time we check the middle of the interval to be checked, and reduce the interval into half . The time is O(logN), in which N=maxTextWidth
update: for float support, see the example below :
and to get a precision of .1, simply change the last line to :