判断一串数字是否连续,连续合并数字

ice_pp 2017-07-26 04:57:19
现有一串数字,例如:
69-78,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243
需要转变为以下结果:
69-104,131-153,190,242-243

需要如何处理呢?

初步想通过数组实现,先用split分组,得到各个数字组合,然后再判断前后2个数字,
但是循环判断时老是出错,得不到正确结果,请各位帮帮忙,谢谢!
...全文
747 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
string txt = "69,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243";
var tmp = txt.Split(',').Select(str => str.Split('-').Select(s => int.Parse(s)).ToArray()).ToArray();
Func<int[], int> func = ta =>
{
    return ta.Length > 1 ? ta[1] : ta[0];
};

int? sNum = null;
int? eNum =null;
List<string> result = new List<string>();
Action act = () =>
{
    if (sNum != eNum)
    {
        result.Add(string.Format("{0}-{1}", sNum, eNum));
    }
    else
    {
        result.Add(sNum.ToString());
    }
};
for (var i = 0; i < tmp.Length; i++)
{
    var arr = tmp[i];
    if (sNum.HasValue)
    {
        if (eNum + 1 == arr[0])
        {
            eNum = func(arr);
            continue;
        }
        else
        {
            act();
        }
    }
    sNum = arr[0];
    eNum = func(arr);
}
act();

Console.WriteLine(string.Join(",", result));
良朋 2017-07-27
  • 打赏
  • 举报
回复
5楼大牛人!
q107770540 2017-07-27
  • 打赏
  • 举报
回复
void Main()
{
	string str="69-78,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243";
	string[] array= str.Split(',');
	if(!array.Any()) return;
	string result = array.First().Split('-')[0] + "-";
	array.Aggregate((x,y)=>{
	   string s = CheckItem(x,y);
	   if(s.Contains("error"))
	   {
	     if(!x.Contains("-"))
		 {
		    if(result.Split(',').LastOrDefault() != x + "-")
			{
				result = result+ x + ","; 
				result = result+ y.Split('-')[0] + "-"; 
			}
			else
			{
			  	result = result.TrimEnd('-')+ ","; 
				result = result+ y.Split('-')[0] + "-"; 
			}
		 }
	    else
		{ 
		    result = result+ x.Split('-')[1] + ","; 
		    result = result+ y.Split('-')[0] + "-"; 
		} 
	   }  
	   return y;
	});
	
    result += array.Last().Split('-')[1];
	
	Console.WriteLine(result); //69-104,131-153,190,242-243

}

string CheckItem(string x, string y)
{
  string result = "";
  if(x.Contains("-") && y.Contains("-"))
  {
  	string[] firstItem = x.Split('-');
	string[] lastItem = y.Split('-');
	if(int.Parse(firstItem[1]) == int.Parse(lastItem[0])-1)
	result =  lastItem[1];
	else result =  "error-"+lastItem[1]; 
  }
  else if(!x.Contains("-") && y.Contains("-"))
  { 
	string[] lastItem = y.Split('-');
	if(int.Parse(x) == int.Parse(lastItem[0])-1)
	result =  lastItem[1];
	else result =  "error-"+lastItem[1]; 
  }
  else if(x.Contains("-") && !y.Contains("-"))
  {
    string[] firstItem = x.Split('-');
	if(int.Parse(firstItem[1]) == int.Parse(y)-1)
	result =   y;
	else result =  "error-"+ y; 
  }
  else
  {
    if(int.Parse(x) == int.Parse(y) -1) result =  y;
		else result =  "error-"+ y; 
  } 
  return result;
}
ice_pp 2017-07-27
  • 打赏
  • 举报
回复
引用 7 楼 starfd 的回复:
string txt = "69,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243";
var tmp = txt.Split(',').Select(str => str.Split('-').Select(s => int.Parse(s)).ToArray()).ToArray();
Func<int[], int> func = ta =>
{
    return ta.Length > 1 ? ta[1] : ta[0];
};

int? sNum = null;
int? eNum =null;
List<string> result = new List<string>();
Action act = () =>
{
    if (sNum != eNum)
    {
        result.Add(string.Format("{0}-{1}", sNum, eNum));
    }
    else
    {
        result.Add(sNum.ToString());
    }
};
for (var i = 0; i < tmp.Length; i++)
{
    var arr = tmp[i];
    if (sNum.HasValue)
    {
        if (eNum + 1 == arr[0])
        {
            eNum = func(arr);
            continue;
        }
        else
        {
            act();
        }
    }
    sNum = arr[0];
    eNum = func(arr);
}
act();

Console.WriteLine(string.Join(",", result));
谢谢!问题解决,待有时间再验证一下
ice_pp 2017-07-27
  • 打赏
  • 举报
回复
引用 5 楼 q107770540 的回复:
void Main()
{
	string str="69-78,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243";
	string[] array= str.Split(',');
	if(!array.Any()) return;
	string result = array.First().Split('-')[0] + "-";
	array.Aggregate((x,y)=>{
	   string s = CheckItem(x,y);
	   if(s.Contains("error"))
	   {
	     if(!x.Contains("-"))
		 {
		    if(result.Split(',').LastOrDefault() != x + "-")
			{
				result = result+ x + ","; 
				result = result+ y.Split('-')[0] + "-"; 
			}
			else
			{
			  	result = result.TrimEnd('-')+ ","; 
				result = result+ y.Split('-')[0] + "-"; 
			}
		 }
	    else
		{ 
		    result = result+ x.Split('-')[1] + ","; 
		    result = result+ y.Split('-')[0] + "-"; 
		} 
	   }  
	   return y;
	});
	
    result += array.Last().Split('-')[1];
	
	Console.WriteLine(result); //69-104,131-153,190,242-243

}

string CheckItem(string x, string y)
{
  string result = "";
  if(x.Contains("-") && y.Contains("-"))
  {
  	string[] firstItem = x.Split('-');
	string[] lastItem = y.Split('-');
	if(int.Parse(firstItem[1]) == int.Parse(lastItem[0])-1)
	result =  lastItem[1];
	else result =  "error-"+lastItem[1]; 
  }
  else if(!x.Contains("-") && y.Contains("-"))
  { 
	string[] lastItem = y.Split('-');
	if(int.Parse(x) == int.Parse(lastItem[0])-1)
	result =  lastItem[1];
	else result =  "error-"+lastItem[1]; 
  }
  else if(x.Contains("-") && !y.Contains("-"))
  {
    string[] firstItem = x.Split('-');
	if(int.Parse(firstItem[1]) == int.Parse(y)-1)
	result =   y;
	else result =  "error-"+ y; 
  }
  else
  {
    if(int.Parse(x) == int.Parse(y) -1) result =  y;
		else result =  "error-"+ y; 
  } 
  return result;
}
谢谢q107770540,我将代码修改一点点,以便适应多几种情况,1)单个数字;2)有可能结尾不包含“-”的; //strResult 就是需要处理的字符串 If Not strResult.Contains(",") Then Return strResult End If Dim strArray As String() = strResult.Split(","c) If Not strArray.Any() Then Return strResult End If Dim result As String = strArray.First().Split("-"c)(0) + "-" strArray.Aggregate(Function(x, y) Dim s As String = CheckItem(x, y) If s.Contains("error") Then If Not x.Contains("-") Then If result.Split(","c).LastOrDefault() <> x + "-" Then result = (result & Convert.ToString(x)) + "," result = result + y.Split("-"c)(0) & Convert.ToString("-") Else result = result.TrimEnd("-"c) + "," result = result + y.Split("-"c)(0) & Convert.ToString("-") End If Else result = result + x.Split("-"c)(1) & Convert.ToString(",") result = result + y.Split("-"c)(0) & Convert.ToString("-") End If End If Return y End Function) If strArray.Last.Contains("-") Then result += strArray.Last.Split("-"c)(1) End If If result.EndsWith("-") Then result = result.TrimEnd("-") End If 'Console.WriteLine(result) '69-104,131-153,190,242-243 Return result
  • 打赏
  • 举报
回复
比如说写
public class Item
{
    public int Num;

    public bool 判断是否能合并(Item a, Item2)
    {
        //.....
    }
}

public class Item2: Item
{
    public int Num2;
}
你再来写“判断.....”的算法,以至于List<Item> 顺序地用相邻的两个元素替换的算法。这个你完全可以自己设计,前提是要写出一个真正的自定义的数据结构。
  • 打赏
  • 举报
回复
引用 2 楼 ice_pp 的回复:
[quote=引用 1 楼 sp1234 的回复:] [quote=引用 楼主 ice_pp 的回复:] 现有一串数字,例如: 69-78,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243
这是一串数字吗?你先用代码写一下这“一串数字”看看。[/quote] 不好意思,表述错误,应该是字符串![/quote] 那就说明你的问题很可能就是出在最初的数据结构建模上。一开始精力没有放在起步时的数据模型设计上,所以后边的都是在耗费精力反复乱试。这一串字符串如果按照你说的“split分组”得到的结果也不足以表示原始的意思,可见你始终丢了关键信息。把数据建模清楚,就能很好地写那么4、5行算法。离开了清楚地数据结构,代码算法就是不可能的事情。
ice_pp 2017-07-26
  • 打赏
  • 举报
回复
引用 1 楼 sp1234 的回复:
[quote=引用 楼主 ice_pp 的回复:] 现有一串数字,例如: 69-78,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243
这是一串数字吗?你先用代码写一下这“一串数字”看看。[/quote] 不好意思,表述错误,应该是字符串!
  • 打赏
  • 举报
回复
引用 楼主 ice_pp 的回复:
现有一串数字,例如: 69-78,79-88,89-95,96-102,103,104,131-134,135-149,150-153,190,242-243
这是一串数字吗?你先用代码写一下这“一串数字”看看。

16,554

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧