我的意思是:
给定输入数字集:
1,2,3,4,5变为"1-5".
1,2,3,5,7,9,10,11,12,14成为"1-3,5,7,9-12,14"
这是我设法提出的最好的:[C#]
对我来说这感觉有点草率,所以问题是,是否有某种更可读和/或更优雅的解决方案呢?
public static string[] FormatInts(int[] ints)
{
if (ints == null)
throw new ArgumentNullException("ints"); // hey what are you doing?
if (ints.Length == 0)
return new string[] { "" }; // nothing to process
if (ints.Length == 1)
return new string[] { ints[0].ToString() }; // nothing to process
Array.Sort<int>(ints); // need to sort these lil' babies
List<string> values = new List<string>();
int lastNumber = ints[0]; // start with the first number
int firstNumber = ints[0]; …Run Code Online (Sandbox Code Playgroud) 我正在研究一组数值.
我在PHP中有以下数值的数组
11,12,15,16,17,18,22,23,24
Run Code Online (Sandbox Code Playgroud)
而我正试图将其转换为范围,例如在上述情况下它将是:
11-12,15-18,22-24
Run Code Online (Sandbox Code Playgroud)
我不知道如何将其转换为范围.
我想在可读字符串中连接数字序列。连续数字应该像这样合并'1-4'。
我可以将具有所有数字的数组连接成一个完整的字符串,但是我无法合并/合并连续的数字。
我尝试使用几种条件将循环中的前一个和下一个值与当前值进行比较,if但是我似乎找不到合适的值来使其正常工作。
例子:
if(ar[i-1] === ar[i]-1){}
if(ar[i+1] === ar[i]+1){}
Run Code Online (Sandbox Code Playgroud)
我的代码如下所示:
if(ar[i-1] === ar[i]-1){}
if(ar[i+1] === ar[i]+1){}
Run Code Online (Sandbox Code Playgroud)
结果是: 1 - 2, 3, 4, 7, 8, 9, 13, 16, 17
最后,它应如下所示:1-4, 7-9, 13, 16-17。
编辑:我在@CMS'链接中为脚本使用了第一个答案。看起来很像@corschdi的代码段的较短版本:
var ar = [1,2,3,4,7,8,9,13,16,17];
var pages = ar[0];
var lastValue = ar[0];
for(i=1; i < ar.length; i++){
if(ar[i]-1 === lastValue){
pages = pages + ' - ' + ar[i];
}else{
pages = pages + ', ' + ar[i];
}
} …Run Code Online (Sandbox Code Playgroud)