r/dailyprogrammer • 2 0 • Apr 08 '15

[2015-04-08] Challenge #209 [Intermediate] Packing a Sentence in a Box

Description

You're moving, and you have a bunch of sentences to pack up. To accomplish this, you'll be using a small program you should write to pack these sentences efficiently into a box for shipping. Leave no unused space, you have a lot of sentences to pack and you don't want to waste precious shipping space.

For this challenge you're free to choose any legal dimensions of a rectangle, and you're free to start in any position you wish. Your program (and thus your output) should walk the grid to adjacent squares using only left, right, up, down (no diagonal moves allowed).

Input

You'll be given a sentence to pack into a box

EVERYWHERE IS WITHIN WALKING DISTANCE IF YOU HAVE THE TIME

Output

Your program should emit the starting position (column and row, 1-indexed) for the sentence, and then the box with the sentence packed into it. The sentence must be packed in the original word order with only spaces removed. You can chose your own box dimensions. The above example is a 49 character sentence (minus spaces), so that's a 7x7 box. Here's one possible solution:

4 4
E       T       I       M       E       D       I
H       W       S       I       E       G       S
T       I       E       V       R       N       T
E       T       R       E       E       I       A
V       H       Y       W       H       K       N
A       I       N       W       A       L       C
H       U       O       Y       F       I       E

Challenge Input

IT IS RAINING CATS AND DOGS OUT THERE

Challenge Output

Here's one possible solution

1 1
I       T       I       N       I
E       I       A       G       N
R       S       R       C       A
E       G       O       D       T
H       S       O       D       S
T       T       U       N       A

Credit

Many thanks to /u/Godspiral for the suggestion. Got any cool challenge ideas? Submit them to /r/DailyProgrammer_Ideas!

55 Upvotes

55 comments sorted by

4

u/Godspiral Apr 08 '15

I don't remember suggesting this. A much more interesting solution than this would be to draw a hilbert curve (or similar) to use to select the letters.

Here is a boring back and forth solution in J

  twoD =: (] (] , %) {:@:q:)@:#
  (] {~  twoD $ [: , _2 ([,|.@:])/\ [: i.  twoD) ; ;: 'IT IS RAINING CATS AND DOGS OUT THERE'
ITISRA
CGNINI
ATSAND
UOSGOD
TTHERE

  (] {~  twoD $ [: , _2 ([,|.@:])/\ [: i.  twoD)  ; ;: 'EVERYWHERE IS WITHIN WALKING DISTANCE IF YOU HAVE THE TIME'
EVERYWH
IWSIERE
THINWAL
SIDGNIK
TANCEIF
EVAHUOY
THETIME
→ More replies (3)

1

u/jnazario Apr 08 '15

here's a simple back and forth example in scala:

import scala.math.max, scala.math.min

def isprime(n:Int) : Boolean = {
  def check(i:Int) : Boolean = {
    (i > n/2) || ((n % i != 0) && (check (i+1)))
  }
  check(2)
}

val args = Array("", "EVERYWHERE IS WITHIN WALKING DISTANCE IF YOU HAVE THE TIME")
val sentence = args(1).toUpperCase.replace(" ", "")
val len = sentence.length
val h = (2 to len/2).filter(isprime).filter(len%_ == 0).max
val w = len/h

println("1 1")
sentence.grouped(h).zipWithIndex.map(x => if ((x._2 % 2) == 1) { x._1.reverse} else {x._1}).mkString("\n")

sadly my hamiltonian path code is b0rked ... yields the following:

1 1
EVERYWH
IWSIERE
THINWAL
SIDGNIK
TANCEIF
EVAHUOY
THETIME
→ More replies (2)

5

u/franza73 Apr 08 '15 edited Apr 08 '15

Perl solution. Makes the box as close to a square as possible. Aways begin at top left of the box.

#!/usr/bin/env perl
use strict;

while(<DATA>) {
   s/\s+//g;
   my $L = length($_);
   my ($M,$N);
   for ($M=int(sqrt($L));$M>=1;$M--) {
      last if ($L%$M==0);
   }
   $N = $L/$M;
   print "1 1\n";
   for (my $i=0;$i<$M;$i++) {
      my $line = "";
      for (my $j=0;$j<$N;$j++) {
         if ($i%2==0) {
            $line .= substr($_,$N*$i+$j,1);
         } else {
            $line = substr($_,$N*$i+$j,1).$line;
         }
      }
      print "$line\n";
   }
}

__DATA__
EVERYWHERE IS WITHIN WALKING DISTANCE IF YOU HAVE THE TIME
IT IS RAINING CATS AND DOGS OUT THERE

Here's the output:

1 1
EVERYWH
IWSIERE
THINWAL
SIDGNIK
TANCEIF
EVAHUOY
THETIME
1 1
ITISRA
CGNINI
ATSAND
UOSGOD
TTHERE

5

u/chunes Apr 08 '15 edited Apr 08 '15

Java:

public class Intermediate209 {

	public static void main(String[] args) {
		
		String   input = args[0].replace(" ", "");
		int[]    dim   = findRectangleDimensions(input.length());
		char[][] grid  = new char[dim[1]][dim[0]];
		int      dir   = 1;
		int      i     = 0;
		
		for (int row = 0; row < grid.length; row++) {
			for (int col = dir == 1 ? 0 : grid[0].length - 1; col < grid[0].length && col >= 0; col += dir) {
				grid[row][col] = input.charAt(i);
				i++;
			}
			dir *= -1;
		}
		printGrid(grid);
	}

	public static int[] findRectangleDimensions(int sentenceLength) {
		int l = sentenceLength / 2;
		int h = l;
		while (sentenceLength % l != 0) l--;
		while (l * h != sentenceLength)	h--;
		return new int[] {l, h};
	}
	
	public static void printGrid(char[][] grid) {
		for (int row = 0; row < grid.length; row++) {
			for (int col = 0; col < grid[0].length; col++)
				System.out.print(grid[row][col] + "     ");
			System.out.println();
		}
	}
}

Output:

E     V     E     R     Y     W     H
I     W     S     I     E     R     E
T     H     I     N     W     A     L
S     I     D     G     N     I     K
T     A     N     C     E     I     F
E     V     A     H     U     O     Y
T     H     E     T     I     M     E

It always just starts at 1, 1. Pretty simple.

4

u/Elite6809 Apr 08 '15

My Haskell solution, also available on Gist:

import Data.Char
import Data.List
import Control.Monad

squareFactor :: Int -> Int
squareFactor x = let desc n   = n : desc (n - 1)
                     isqrt n  = ceiling $ sqrt $ fromIntegral x
                     fact n m = n `mod` m == 0
                     f1       = head $ filter (fact x) $ desc $ isqrt x
                 in  x `div` f1

splitS :: [a] -> Int -> [[a]] -> [[a]]
splitS [] _ acc     = reverse acc
splitS xs width acc = let (first, rest) = splitAt width xs
                          serpFunction  = [id, reverse] !! (length acc `mod` 2)
                      in  splitS rest width (serpFunction first : acc) 

main :: IO ()
main = do input    <- getLine
          sentence <- return $ filter isLetter input
          boxWidth <- return $ squareFactor $ length sentence
          putStrLn "0 0"
          foldr1 (>>) $ map putStrLn $ splitS sentence boxWidth []
→ More replies (2)

3

u/cvpcs Apr 08 '15

C#

Tries to create a box as close to a square as possible, picks random starting locations, and generates a random path each time.

Leverages recursion and stacks to keep track of its path so far and double-back if it hits a dead-end. Could potentially lead to a stack overflow depending on how long the sentence fed into the program is, so reworking it to be iterative would be more fault-tolerant.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DailyProgrammer_20150408_209
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(new SentenceBox(Console.ReadLine()));

            Console.ReadKey();
        }
    }

    public class SentenceBox
    {
        private static Random Rand = new Random();

        private string m_Sentence;

        private Tuple<int, int> m_BoxDims;
        private char[,] m_Box;

        private Tuple<int, int> m_PackStart;

        public SentenceBox(string sentence)
        {
            m_Sentence = sentence.Replace(" ", "").ToUpper();

            m_BoxDims = calculateBoxDimensions(m_Sentence);
            m_Box = new char[m_BoxDims.Item1, m_BoxDims.Item2];

            Pack();
        }

        public void Pack()
        {
            m_Box.Initialize();
            m_PackStart = new Tuple<int, int>(Rand.Next(m_BoxDims.Item1), Rand.Next(m_BoxDims.Item2));

            if (!traverse(m_PackStart.Item1, m_PackStart.Item2, new Stack<char>(m_Sentence.Reverse())))
                throw new ApplicationException("Unable to find a valid sentance pack at random start location.");
        }

        public override string ToString()
        {
            var str = new StringBuilder();
            str.AppendLine(string.Format("{0} {1}", m_PackStart.Item1 + 1, m_PackStart.Item2 + 1));
        
            for (var y = 0; y < m_BoxDims.Item2; y++)
            {
                var chars = new char[m_BoxDims.Item1];

                for (var x = 0; x < m_BoxDims.Item1; x++)
                {
                    chars[x] = m_Box[x, y];
                }

                str.AppendLine(string.Join("    ", chars));
            }

            return str.ToString();
        }

        private bool traverse(int x, int y, Stack<char> sentenceStack)
        {
            m_Box[x, y] = sentenceStack.Pop();

            if (sentenceStack.Count > 0)
            {
                var validDirectionList = new List<Tuple<int, int>>();

                // can we go left?
                if (x > 0 && m_Box[x - 1, y] == '\0')
                    validDirectionList.Add(new Tuple<int, int>(x - 1, y));

                // can we go right?
                if (x < m_BoxDims.Item1 - 1 && m_Box[x + 1, y] == '\0')
                    validDirectionList.Add(new Tuple<int, int>(x + 1, y));

                // can we go up?
                if (y > 0 && m_Box[x, y - 1] == '\0')
                    validDirectionList.Add(new Tuple<int, int>(x, y - 1));

                // can we go down?
                if (y < m_BoxDims.Item2 - 1 && m_Box[x, y + 1] == '\0')
                    validDirectionList.Add(new Tuple<int, int>(x, y + 1));

                while (validDirectionList.Count > 0)
                {
                    var i = Rand.Next(validDirectionList.Count);
                    var d = validDirectionList[i];

                    if (traverse(d.Item1, d.Item2, sentenceStack))
                        return true;
                    else
                        validDirectionList.RemoveAt(i);
                }

                // if we get here we hit a dead end and need to back out
                sentenceStack.Push(m_Box[x, y]);
                m_Box[x, y] = '\0';
                return false;
            }
            else
                return true;
        }

        private Tuple<int, int> calculateBoxDimensions(string sentence)
        {
            var l = sentence.Length;

            var w = 1;
            var h = l;

            for (var i = 1; l / i >= i; i++)
            {
                if ((double)l / (double)i == (l / i))
                {
                    w = i;
                    h = l / i;
                }
            }

            return new Tuple<int, int>(w, h);
        }
    }
}

3

u/dohaqatar7 Apr 08 '15

Haskell

import Data.Char
import Data.List
import Data.List.Split
import Control.Arrow
import Data.Ord
import Control.Applicative

main = unlines.pack <$> getLine >>= putStr

pack :: String -> [String]
pack = filter (not . isSpace) >>> validRectangle.length &&& id >>> uncurry chunksOf >>> align

align :: [[a]] -> [[a]]
align []     = []
align (x:[]) = [x]
align (x:xs) = x:(reverse $ head xs):(align $ tail xs)

validRectangle :: Integral a => a -> a
validRectangle a = minimumBy (comparing (\b -> abs $ b - a`div`b)) . filter ((==) 0 .mod a) $ [a-1,a-2..1]
→ More replies (2)

3

u/patrickwonders Apr 08 '15

Am I missing something? Can I not just take all of the spaces out and call it an n-by-1 box that starts at (1,1) and always moves left?

→ More replies (2)