Skip to content

Instantly share code, notes, and snippets.

@danielhunex
Created February 11, 2020 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielhunex/df095473cb11e9e4952e17319974b5e1 to your computer and use it in GitHub Desktop.
Save danielhunex/df095473cb11e9e4952e17319974b5e1 to your computer and use it in GitHub Desktop.
Olo-interview
using System;
using System.Text;
using System.Collections.Generic;
namespace WordWrapper
{
public class Program
{
/***
* When placing orders through the Olo system, customers are allowed to add special instructions to their orders, for instance specifying that they don't need utensils or that they want their steak cooked a certain way.
Restaurant receipt printers have restrictions for how many characters can fit on each line. This means that in many cases special instructions must be wrapped and put on multiple lines in order for the text to fit.
Write a function 'WordWrap' that takes as input a string (the special instructions) and an integer (the character limit) and returns the special instructions wrapped onto lines with no line exceeding the character limit.
*/
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
public static string[] WordWrap(string input, int count)
{
if (String.IsNullOrWhiteSpace(input))
{
return new string[0];
}
if (input.Length <= count)
{
return new string[] { input };
}
int start = 0;
int totalLengthSoFar = 0;
var result = new List<string>();
string[] inputArray = input.Split(' ');
for (int i = 0; i < inputArray.Length; i++)
{
if (inputArray[i].Length < count)
{
result.Add(inputArray[i]);
int remaining = count - inputArray[i].Length;
while (i + 1 < inputArray.Length && inputArray[i + 1].Length < remaining)
{
int additionalWordLength = inputArray[i + 1].Length;
if (additionalWordLength < remaining)
{
result[result.Count - 1] = result[result.Count - 1] + ' ' + inputArray[i + 1];
remaining -= additionalWordLength;
i++;
}
}
}
else
{
int st = 0;
int soFar = 0;
while (soFar < inputArray[i].Length)
{
var length = inputArray[i].Length - soFar >= count ? count : inputArray[i].Length - soFar;
var line = inputArray[i].Substring(st, length);
result.Add(line); // append -
soFar += count;
st += count;
}
}
}
//while (totalLengthSoFar < input.Length)
//{
// var length = input.Length - totalLengthSoFar >= count ? count : input.Length - totalLengthSoFar;
// var line = input.Substring(start, length);
// if (line[line.Length - 1] == ' ' || line.LastIndexOf(' ') < 0 )
// {
// result.Add(line);
// totalLengthSoFar += count;
// start += count;
// }
// else
// {
// int lastIndex = line.LastIndexOf(' ');
// line = line.Substring(0, lastIndex);
// result.Add(line);
// totalLengthSoFar += lastIndex;
// start += lastIndex;
// }
//}
return result.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment