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

Framed

Today's goal is to write a function that takes in a list of strings and prints them, one per line, in a rectangular frame. For example the list ["Hello", "World", "in", "a", "frame"] gets printed as:

*********
* Hello *
* World *
* in    *
* a     *
* frame *
*********

Permalink: http://problemotd.com/problem/framed/

Comments:

  • Ben - 10 years, 2 months ago

    C#

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    class Program
    {
        static void Main()
        {
            List<String> strings = new List<string>{"Hello", "World", "in", "a", "frame"};
            OutputInFrame(strings);
            Console.Read();
        }
    
        public static void OutputInFrame(List<String> strings)
        {
            int maxLength = strings.Max(x => x.Length);
            string topAndBottom = "*".PadRight(maxLength + 2, '*');
            Console.WriteLine(topAndBottom);
            strings.ForEach(x => Console.WriteLine("*" + x.PadRight(maxLength) + "*"));
            Console.WriteLine(topAndBottom);
        }
    }
    

    reply permalink

  • Max Burstein - 10 years, 2 months ago

    Thanks for the submission!

    reply permalink

  • Anonymous - 10 years, 2 months ago

    Python

    framethis = input('Type a string >')
    box = ''
    words = []
    
    #Takes input and makes a list of the individual words
    for x in framethis:
        if x == ' ':
            words.append(box)
            box = ''
        else:
            box += x
    words.append(box)
    
    #Finds length of longest word in input
    longest = 0
    for x in words:
        if len(x) > longest:
            longest = len(x)
    
    #Creates top of frame
    firstline = ''
    for x in range(longest + 5):
        firstline += '*'
    
    #Prints input within a frame
    print(firstline)
    for x in words:
        space = longest - len(x)
        print('*',x,' ' * space, '*')
    print(firstline)
    

    reply permalink

Content curated by @MaxBurstein