Problem of the Day
A new programming or logic puzzle every Mon-Fri

Max Font Size

We'll round out our week of word processing with a slightly more challenging problem. Today's goal is to create a function that takes in a string and returns the maximum font size (as an integer) usable for that string to fit on 3 or less lines. A line is considered 960px wide. For this problem we will use a monospace font, meaning that all characters are of the same width (e.g. 'l' and 'm' take up the same horizontal space, as do space characters). Words cannot be split in half, so you will need to wrap to the next line if needed. Here is an example:

maxFontSize('Problem of the Day')
> 137px

"Problem" is the longest word and can max out line 1 at 960px / 7 characters ≈ 137px/character. "of the" can fit on line 2 with "day" going on line 3. If the problem were to solve for only 2 lines then the longest line would be "of the Day" which would lead to a max font size of 960/10 = 96px.

Permalink: http://problemotd.com/problem/max-font-size/

Comments:

  • ujjl - 10 years, 7 months ago

    Haskell

    screenWidth = 960
    maxLines = 3
    
    maxFontSize text = show (last [fontSize | fontSize <- [1.. screenWidth], length (align fontSize wordLengths)<= maxLines, fontSize* maximum wordLengths <= screenWidth]) ++ "px"
        where wordLengths = map length ( words text )
    
    align _ [] = []
    align fontSize (x:y:xs)
        | (x + y+1)*fontSize <= screenWidth = align fontSize (x+y+1:xs)
        | otherwise = x:(align fontSize (y:xs))
    align _ [x] = [x]
    
    main = putStrLn ( maxFontSize "Problem of the Day" )
    

    reply permalink

Content curated by @MaxBurstein