Reputation: 3696
My objective is to draw 2 rectangles adjacent to each other. I wrote the code for drawing a rectangle but I could not draw 2 adjacent rectangles. I see where to problem is but I am not sure how to fix it. Help is greatly appreciated.
class DrawRectangles
{
static void Main(){
Console.WriteLine(DrawRectangle(8,8)+DrawRectangle(4,3));
}
static string DrawRectangle(int width,int length){
StringBuilder sb = new StringBuilder();
string first = "+" + " -".StringMultiplier(width-1)+ " + ";
sb.AppendLine(first);
for(int i=0; i<length-1;i++)
sb.AppendLine("|"+" ".StringMultiplier(2*width-1)+"|");
sb.Append(first);
return sb.ToString();
}
}
internal static class StringExtensions
{
public static string StringMultiplier(this string value,int count){
StringBuilder sb = new StringBuilder(count);
for(int i=0;i<count;i++)
sb.Append(value);
return sb.ToString();
}
}
Expected output:
+ - - - - - - - + | | | | | | | |+ - - - + | || | | || | | || | + - - - - - - - ++ - - - +
Current output:
+ - - - - - - - + | | | | | | | | | | | | | | + - - - - - - - ++ - - - + | | | | + - - - +
Upvotes: 2
Views: 1230
Reputation: 32515
Firstly, the StringMultiplier
extension is unnecessary because you can use System.String(Char, Int32)
to accomplish the same thing.
Here's the code you'll actually need:
// Assume the Tuples are <height, width>
string DrawRectangles(params Tuple<int, int>[] measurements)
{
var sb = new StringBuilder();
var maxHeight = measurements.Max(measurement => measurement.Item1);
for (var h = maxHeight; h > 0; h--)
{
foreach (var measurement in measurements)
{
// If you're on the top or bottom row of a rectangle...
if (h == 0 || measurement.Item1 == h)
{
sb.Append(String.Format("{0}{1}{0}", "+", new String('-', measurement.Item2 - 2)));
continue;
}
// If you're in the middle of a rectangle...
if (measurement.Item1 > h)
{
sb.Append(String.Format("{0}{1}{0}", "+", new String(' ', measurement.Item2 - 2)));
continue;
}
sb.Append(new String(' ', measurement.Item2));
}
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
Usage:
var output = DrawRectangles(new Tuple(8, 8), new Tuple(4, 3), etc...);
Upvotes: 3
Reputation: 32501
insted of this code
string first = "+" + " -".StringMultiplier(width-1)+ " + ";
you can simply use this pattern:
string first = string.Format("+{0}+", new string('-', width - 2));
Upvotes: 1