首页 > 解决方案 > char 二维数组压缩

问题描述

有一个 .txt 文件,我必须阅读压缩并为压缩的 txt制作输出txt。谁能告诉我应该在我的代码中修复什么?

我的代码:

namespace Tomorites
{
    class Compression
    {
        public void Compress(char[,] source)
        {
            for (int i = 0; i < source.GetLength(0); i++)
            {
                int white = 0;                           
                int red = 0;
                for (int j = 0; j < source.GetLength(1); j++)
                {
                    if (source[i, j] == 'P')
                    { 
                        if (source[i, j] > 0)
                        {
                            red++;
                            Console.Write(red + " P ");
                        }                                              
                    }                    
                    else if(source[i,j]=='F')
                    {
                        if (source[i, j] > 0)
                        {
                            white++;
                            Console.Write(white + " F ");
                        }                                            
                    }                                       
                }               
                Console.WriteLine();
            }
        }
    }
}

我的控制台输出

源txt文件

压缩的txt文件必须是

标签: c#

解决方案


你可以尝试这样的事情(你可以摆弄代码):

public static string Compress(char[,] source) {
  if (null == source || source.GetLength(0) <= 0 || source.GetLength(1) <= 0)
    return "";

  StringBuilder sb = new StringBuilder();

  for (int row = 0; row < source.GetLength(0); ++row) {
    if (sb.Length > 0)
      sb.AppendLine(); 

    int count = 0;
    char prior = '\0'; 
    bool left = true;

    for (int col = 0; col < source.GetLength(1); ++col) {
      if (count == 0 || prior == source[row, col]) 
        count += 1;
      else {
        if (!left)
          sb.Append(' ');

        left = false;
        sb.Append($"{count} {prior}");
        count = 1; 
      }
      
      prior = source[row, col];     
    }

    if (!left)
      sb.Append(' ');

    sb.Append($"{count} {prior}");     
  }  

  return sb.ToString();
}

演示:

    char[,] test = new char[,] {
        {'a', 'a', 'a', 'a'},
        {'a', 'b', 'c', 'c'},
    };
    
    Console.WriteLine(Compress(test));

结果:

4 a
1 a 1 b 2 c

推荐阅读