2013-01-18 21 views
2

我的目标是绘制彼此相邻的两个矩形。我编写了绘制矩形的代码,但是我无法绘制2个相邻的矩形。我看到问题出在哪里,但我不知道如何解决问题。非常感谢帮助。使用ASCII字符绘制2个相邻的矩形

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(); 
    }  
} 

预期输出

+ - - - - - - - + 
|    | 
|    | 
|    | 
|    |+ - - - + 
|    ||  | 
|    ||  | 
|    ||  | 
+ - - - - - - - ++ - - - + 

电流输出

 
+ - - - - - - - + 
|    | 
|    | 
|    | 
|    | 
|    | 
|    | 
|    | 
+ - - - - - - - ++ - - - + 
|  | 
|  | 
+ - - - + 
+0

你一定要明白你在做字符串连接,当你做'DrawRectangle的(8,8)+的DrawRectangle (4,3)'...... –

+0

是的..我知道问题在哪里,它有多愚蠢,但我用完了想法。任何不同的观点来实现同样也是赞赏。 –

+0

此外,这似乎是功课...如果是这样,你应该这样标记... –

回答

3

首先,StringMultiplier扩展名是不必要的,因为你可以使用System.String(Char, Int32)来完成同样的事情。

这里是你真正需要的代码:

// 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(); 
} 

用法:

var output = DrawRectangles(new Tuple(8, 8), new Tuple(4, 3), etc...); 
+0

这是一个很好的答案,但代码不会以这种方式工作,除非进行编辑。你的'break'应该是'continue',并且在每次高度迭代结束时都应该有一个CR。 –

+0

@AntonyThomas:全部修复。 –

+0

在另一个说明中,你是否知道类似'new String(' - ',measurement)'的语法,但接受'string'而不是'char'作为param1。我写'StringMultiplier()'的原因是为了解决这个问题,尽管它在SO中发布的子问题中听起来多余。 –

1

insted的这个代码

string first = "+" + " -".StringMultiplier(width-1)+ " + "; 

,你可以简单地使用此模式:

string first = string.Format("+{0}+", new string('-', width - 2)); 
+0

这似乎并没有回答我的问题。 –