Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 110 题:编程题,请写一个函数,完成以下功能 #201

Open
flyfox11 opened this issue Jul 19, 2019 · 131 comments
Open

第 110 题:编程题,请写一个函数,完成以下功能 #201

flyfox11 opened this issue Jul 19, 2019 · 131 comments

Comments

@flyfox11
Copy link

输入
image
输出
image

@flyfox11
Copy link
Author

@lonycc 朋友,你明显理解错了,这道题的意思是:如果连续数字的话,就取连续的第一个数和最后一个数,中间用~隔开。如果不连续就用,隔开。

@lhyt
Copy link

lhyt commented Jul 20, 2019

function simplifyStr(str) {
  let pre = void 0;
  return `${str},`.replace(/ /, '').replace(/\d+,(?=(\d+|\B))/g, (current, next) => {
    const _current = +current.split(',')[0]
    pre = pre === undefined ? +_current : pre
    const res = +next === _current + 1 ? (
      pre + 1 === _current ? '' : _current
    ) : (
      pre + 1 === _current ? `~${_current}${next ? ',' : ''}` : current
    )
    pre = _current
    return res
  })
}

@Yxiuchao
Copy link

想看各位大佬的最佳操作,我就简陋的写了一下。

const nums1 = [1, 2, 3, 5, 7, 8, 10];
function simplifyStr(num) {
  var result = [];
  var temp = num[0]
  num.forEach((value, index) => {
    if (value + 1 !== num[index + 1]) {
      if (temp !== value) {
        result.push(`${temp}~${value}`)
      } else {
        result.push(`${value}`)
      }
      temp = num[index + 1]
    }
  })
  return result;
}
console.log(simplifyStr(nums1).join(','))

@flyfox11
Copy link
Author

我也来参与一下~

let arr =  [1, 2, 3, 5, 7, 8, 10];
function transStr(arr) {
  let result = arr.reduce((prev, next, index, array) => {
      if (index > 0) {
        if (next === array[index - 1] + 1) {
          return prev + '~' + next
        } else {
          return prev + ',' + next
        }
      } else {
        return next
      }
    }, '')
    return (result + '').split(',').map(item => item.replace(/(\d{1,})(~\d{1,})*(~\d{1,})/, '$1$3')).join(',')
}
console.log( transStr(arr))

@huzhifu
Copy link

huzhifu commented Jul 21, 2019

@lhyt 大佬,你的方法运行的结果,最后会多个逗号。。

@whyour
Copy link

whyour commented Jul 21, 2019

function transformStr(str) {
  const arr = str.split(',').map(x => parseInt(x));
  let result = [arr[0], arr[1]], i = 1, isContinuous = false;
  arr.forEach((value, index) => {
    if (index > 1) {
      if (value === result[i] + 1 && result[i] - result[i-1] === 1) {
        result[i] = value;
        isContinuous = true;
      } else {
        isContinuous = false;
        result.push(value);
        i++;
      }
      if(isContinuous || result[i] - result[i-1] === 1)result[i] = `~${result[i]}`;
    }
  })
  return result.toString().replace(/,(?=~)/g, '');
}

const str = '1,2,3,5,7,8,10,11';
console.log(transformStr(str));

@leemotive
Copy link

哈哈,还在疑惑呢,题目是啥意思,原来是markdown中两个~构成了删除线,要用\~来写~呢

@huajianduzhuo
Copy link

function getSerial(src) {
  let srcArray = src.split(',').map(num => +num)
  if (srcArray.length === 0) return ''
  let result = '' + srcArray[0]
  let serialCount = 0
  for (let i = 1; i < srcArray.length; i++) {
    if (srcArray[i] !== srcArray[i - 1] + 1) {
      result += (serialCount > 0 ? '~' + srcArray[i - 1] : '') + ',' + srcArray[i]
      serialCount = 0
    } else {
      serialCount++
      if (i === srcArray.length - 1) {
        result += '~' + srcArray[i]
      }
    }
  }
  return result
}

@huajianduzhuo
Copy link

@whyour 你这个方法在最后两位是连续的时候,结果不对。传入 '1,2,3,5,7,8' ,输出的是 1~3,5,7,8

@chenlong-io
Copy link

const str = '1,2,3,5,7,8,10;

const transformStr = ( str ) => '1~3,5,7~8,10';

😈😈😈😈😈😈😈

@lml28043
Copy link

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String numsStr = scan.next();
String[] numsStrs = numsStr.split(",");
// methodOne(numsStrs);
methodTwo(numsStrs);
}

private static void methodTwo(String[] numsStrs) {
	int numsStrsLen = numsStrs.length;
	if(numsStrs!=null && numsStrs.length>0){
		System.out.print(numsStrs[0]);
	}
	boolean beforeFlag = false;
	boolean flag = false;
	for(int i=1; i<numsStrsLen; i++){
		if(((Integer.valueOf(numsStrs[i-1])+1)+"").equals(numsStrs[i])){  // 说明连续
			flag = true;
		} else {
			flag = false;
		}
		if(!flag && beforeFlag){
			System.out.print("~"+numsStrs[i-1]+","+numsStrs[i]);
		} else if(!flag && !beforeFlag){
			System.out.print(","+numsStrs[i]);
		}
		beforeFlag = flag;
	}
}

private static void methodOne(String[] numsStrs) {
	int numsStrsLen = numsStrs.length;
	boolean isEquals = Integer.valueOf(numsStrs[0])+Integer.valueOf(numsStrs[1])-1-2==0 ? true : false;
	int beforeSub = Integer.valueOf(numsStrs[0]) - 1;  // 之前的差值
	int nowSub = 0;
	String result = numsStrs[0];
	for(int i=1; i<numsStrsLen; i++){
		nowSub = Integer.valueOf(numsStrs[i]) - (i+1);
		if(nowSub!=beforeSub && isEquals){  // 该值不相等但前一个相等
			result += "~"+numsStrs[i-1]+","+numsStrs[i];
			isEquals = false;
		} else if(nowSub==beforeSub){
			isEquals = true;
		} else{
			result += ","+numsStrs[i];
			isEquals = false;
		}
		beforeSub = nowSub;
	}
	System.out.println("结果:"+result);

@xiaohei007
Copy link

function classification(data){
if(!data)return data; let group = []; let result = data.split(','); let str = ''; for(let i = 0;i<result.length;i++){ if(i>0){ if(result[i]-1 == result[i-1]){ group[group.length-1].push(result[i]); }else{ group[group.length] = [result[i]]; } }else{ group[0] = [result[i]]; } } group.forEach(function(item,index){ if(item.length>1){ str += item[0] +'~' +item[item.length-1]; }else { str += item[0]; } if(index!==group.length-1){ str += ','; } });
console.log(str); return str;}

@k-0311
Copy link

k-0311 commented Jul 22, 2019

let str = '1,2,3,5,7,8,10,12,13,14,100,101,102';

  const strGroup = (arr) =>
    arr.reduce((acc, item) => {
      let lastArr = acc.slice().pop() || []
      let lastNum = lastArr.slice().pop()
      if (lastNum == item - 1 || (lastNum && lastNum.match(/(\w*)(\w)/g)[1] == item - 1)) {
        lastArr.pop()
        let curStr = /\~.*/.test(lastNum)
          ? lastNum.replace(/\~.*/, `~${item}`)
          : `${lastNum}~${item}`
        lastArr.push(curStr)
      } else {
        acc.push([item])
      }
      return acc
    }, []).join(',')

  strGroup(str.split(',')) // 1~3,5,7~8,10,12~14,100~102

灵感来源 67题 ,来自 @benzhemin的求连续版本
#113 (comment)

@HupuJrs001 HupuJrs001 mentioned this issue Jul 22, 2019
@cisen
Copy link

cisen commented Jul 22, 2019

这种好像用bitmap也很好处理

@rocketsbigfan
Copy link

rocketsbigfan commented Jul 22, 2019

const transformString = function(string) {
    let first = null;
    let tempArr = []
    let arr = string.split(',').map(item => Number(item))
    arr.forEach((current, index) => {
        if(index === 0) {
	    first = current
        } else {
	    let prev = arr[index - 1]
	    if(current !==  prev + 1) {
	        first === prev ? tempArr.push(`${first}`) : tempArr.push(`${first}~${prev}`);
	        first = current
            }

           arr.length - 1 === index && (first === current ? tempArr.push(`${first}`) : tempArr.push(`${first}~${current}`))
       }


   })

   return tempArr.join(',')

}
console.log(transformString('1,2,3,5,7,8,10,12,13,14,100,101,102'))

@harryliuy
Copy link

let str = "1, 2, 3, 5, 7, 8, 10";
    function computed(str) {
      let arr = str.split(",");
      let pos = 0, index = 0, flag = true;
      for (let i = 0; i <= arr.length; i++) {
        if (Number(arr[i - 1]) + 1 == arr[i]) {
          if (flag) {
            pos = i;
          }
          index++;
          flag = false;
        } else {
          if (!flag) {
            arr.splice(pos, index - 1, "~");
          }
          flag = true;
          i = i - index;
          index = 0;
        }
      }
      return arr.join(",").replace(/\,~\,/g, "~");
    }
    console.log(computed(str));

@suguoyao
Copy link

const numRange = function (arr) {
  arr = arr.split(',')
  let result = []
  let map = {}
  let count = 0
  for (let i = 0; i < arr.length; i++) {
    if (i === 0) {
      map[count] = [arr[i]]
      continue
    }

    if (+arr[i] - 1 === +arr[i - 1]) {
      map[count].push(arr[i])
    } else {
      count++
      map[count] = [arr[i]]
    }
  }

  for (const key in map) {
    if (map.hasOwnProperty(key)) {
      const range = map[key]
      if (range.length > 1) {
        result[key] = [range[0], range[range.length - 1]].join('~')
      } else {
        result[key] = range.join('')
      }
    }
  }

  return result.join(',')
}

numRange('1,3,4,5,6,8,9,20') // => "1,3~6,8~9,20"

@lvwxx
Copy link

lvwxx commented Jul 22, 2019

function f(params) {
  const arr = params.split(',')
  const res = []
  let first = arr[0]
  let next = 0

  
  for (let i = 0; i < arr.length; i++) {
    if (+arr[i]+1 === +arr[i+1]) {
      next = arr[i + 1]
    } else {
      if (next !== 0) {
        res.push(`${first}~${next}`)
      } else {
        res.push(arr[i])
      }
      first = arr[i + 1]
      next = 0
    }
  }
  return res.join(',')
}

@ghost2113
Copy link

// output '1~3,5,7~9,11~12'
var str = '1,2,3,5,7,8,9,11,12';
function simplifyStr(str) {
    var arr = str.split(',').map(item => parseInt(item));
    let result = arr.map((current, index) => {
        var next = arr[index + 1] - 1;
        var prev = arr[index - 1] + 1;
        if (next == current && prev == current) {
            return '';
        } else if (next != current && prev == current) {
            return '~' + current;
        } else {
            return current;
        }
    });
    return result.filter((item)=>item).join(',').replace(/(,~)*/g,'~');
}
simplifyStr(str);

@Sean-lxy
Copy link

Sean-lxy commented Jul 22, 2019

function reSort(arr) {
    var current = 0;
    var len = 0;

    for(let i=1; i<arr.length; i++) {

        if(arr[i] - arr[i-1] !== 1) {
            if(!len) continue;

            arr.splice(current , len - 1, '~');

            i = i - len + 2;
            current = 0;
            len = 0;
        }else{
            current = current || i;
            len++;

            if(i === arr.length - 1) {
                arr.splice(current , len - 1, '~');
            }
        }
    }

    return arr.join(',').replace(/,~,/g, '~');
}

var str = "1,2,3,4,6,7,9,10,11";

console.log(reSort(str.split(',')));

求大佬们点评

@zwmmm
Copy link

zwmmm commented Jul 22, 2019

测试通过

function transformStr(str) {
    let arr = str.split(',')
    let i = 0
    let ret = []
    for (let j = 1; j <= arr.length; j++) {
        if (arr[j] - arr[j - 1] !== 1) {
            ret.push(j - i === 1 ? arr[i] : `${arr[i]}~${arr[j - 1]}`)
            i = j
        }
    }
    return ret.join(',')
}

@MoveZZG
Copy link

MoveZZG commented Jul 22, 2019

一行代码(嘿嘿)

修改了重名变量,方便理解

function transArr(str) {
  return str.split(",").map((item, key, arr) => (arr[key + 1] != +item + 1 || key === 0 || arr[key - 1] != item - 1) ? item == +arr[key - 1] + 1 ? `,${item}` : item : ",").toString().replace(/(,)\1+/g, '~')
}

@weiweixuan
Copy link


      function change(str) {
        let arr = str.split(','),
          content = [],
          lsArr = []
        arr.forEach(element => {
          if (lsArr.length > 0) {
            if (element - lsArr.slice(-1) == 1) {
              lsArr.push(element)
            } else {
              //  判断lsArr是否为一个值
              if (lsArr.length > 1) {
                content.push(lsArr.shift() + '~' + lsArr.pop())
              } else {
                content.push(lsArr[0])
              }
              lsArr = [element]
            }
          } else {
            lsArr.push(element)
          }
        })
        //  循环结束
        if (lsArr.length > 1) {
          content.push(lsArr.shift() + '~' + lsArr.pop())
        } else {
          content.push(lsArr[0])
        }
        return content.join(',')
      }
      let res = change(str)
      console.log(res)  //1~3,5,7~8,10

@kaykie
Copy link

kaykie commented Jul 22, 2019

const nums1 = [ 1, 2, 3, 4, 5, 7, 8, 10, 13, 22, 122 ];
const returnArray: string[] = [];
let num = nums1[ 0 ];
nums1.forEach((item, index) => {
if (item + 1 !== nums1[ index + 1 ]) {
if (item - 1 === nums1[ index - 1 ]) {
returnArray.push(${num}-${item})
} else {
returnArray.push(item + '')
}
num = nums1[ index + 1 ];
}
});
console.log(returnArray)

@hlubing
Copy link

hlubing commented Jul 22, 2019

    var str110 = '1,2,3,5,7,8,10'
var array110 = str110.split(',')
let arrResult = []
let tmp = 1
for (let i in array110) {
	let item = parseInt(array110[i])
	let item1 = parseInt(array110[parseInt(i) + 1])
	if (item1 - 1 !== item) {
		
	        if (tmp !== item) {
			tmp = tmp + '~' + item
		}

		arrResult.push(tmp)
		tmp = item1
	}
}
console.log(arrResult.join())

@maosm
Copy link

maosm commented Jul 22, 2019

function transStr() {

let args = arguments[0].split(',').map((num) => parseInt(num)) 
let [str1, temp, num, flag] = ['', args[0], 0, true]
for(let n of args) {
    if(flag) {
        flag = !flag     
    } else {
        if ((n-1) !== temp) {
            str1 += `${temp},`
            temp = n
            num = 0
        } else {
            if (num === 0) {
                str1 += `${temp}~`
            }
            num++
            temp = n 
        }
    }        
}
str1 += temp
console.log(str1)

}
transStr('1,2,3,5,7,8,10')

@hhhluke
Copy link

hhhluke commented Jul 22, 2019

function getSeries(arr){
  let temp = arr[0]
  return arr.reduce((acc,cur,index)=>{
    if(cur + 1 !== arr[index + 1]) {
      if(temp !== cur) {
        acc.push(`${temp}~${cur}`)
      } else {
        acc.push(cur)
      }
      temp = arr[index + 1]
    }
    return acc
  },[]).join(',')
}

@J-DuYa
Copy link

J-DuYa commented Jul 22, 2019

export function intervalNum (list) {
  let result = [] // 分隔连续数字的区间标记
  let prewVal = null
  let initVal = null

  if (list === '') {
    return ''
  }

  list = list.split(',')
  // mark记录非连续数字的第一个值
  list.forEach((item, index) => {
    if (prewVal && Number(prewVal) === (Number(item) - 1)) {
      result.push(initVal + '->' + index + '~' + item)
      // (marks[marks.length - 1] - mark[marks.length - 2] === 1) ? marks.splice(marks.length - 2, 1) : () => {}
      if (result[result.length - 1].indexOf(initVal + '->') > -1) {
        result.splice(result.length - 2, 1)
      }

    } else if (!prewVal) {
      initVal = item
      result.push(item + '->')
    } else {
      initVal = item
      result.push(item + '->')
    }
    prewVal = item
  })

  result = result.map(item => {
    return item.split('->')[0] + (item.split('->')[1].split('~ ')[1] ? item.split('->')[1].split('~ ')[1] : '')
  })
  return result.join(',')
}

@Txllmz
Copy link

Txllmz commented Jul 22, 2019

var continueNum=function(str){
    var numarr=str.split(",");
    var result=[];var queue=[];
    for(let i=0;i<numarr.length;i++)
    {
      if((numarr[i+1]-numarr[i])==1)
      {
          queue.push(numarr[i]);
      }
      else
      {
          queue.push(numarr[i]);
          if(queue.length!=1)
          {result.push(queue[0]+"~"+queue[queue.length-1]);queue.length=0}
          else
          {result.push(queue[0]);queue.length=0}
      }
    }

    return result.join(",");
}

@kgnbale
Copy link

kgnbale commented Aug 1, 2020

   function simplifyStr(str) {
    if (!str || str.length === 1) return
    let lockFlag = false;
    let arr = str.split(',')
    let startItem = arr[0],
      endItem = arr[1],
      res = []
    for (let i = 1; i < arr.length; i++) {
      if ((arr[i] - arr[i - 1]) !== 1) {
        lockFlag = true;
        endItem = arr[i - 1];
        startItem === endItem && res.push(`${endItem}`);
        startItem !== endItem && res.push(`${startItem}~${endItem}`);
        startItem = arr[i];
        if (i === arr.length - 1) {
          res.push(`${arr[i]}`)
        }
      } else {
        endItem = arr[i]
      }
    }
    if (!lockFlag) {
      res.push(`${startItem}~${endItem}`)
    }
    return res.join(',')
  }

@Jian-Yin
Copy link

Jian-Yin commented Sep 1, 2020

function test(str) {
  return str.split(',').reduce((acc, cur, curIndex, arr) => {
    if (!curIndex) return cur
    const pre = arr[curIndex - 1]
    if (+pre === +cur - 1) {
      const reg = new RegExp(`~${pre}$`)
      acc = reg.test(acc) ? acc.replace(reg, `~${cur}`) : (acc + `~${cur}`)
    } else {
      acc += `,${cur}`
    }
    return acc
  }, '')
}
test('1,2,3,5,7,8,10')

@wabRul
Copy link

wabRul commented Sep 3, 2020

function simplifyStr(str) {
  let arr = str.split(',').map(v => +v)
  let len = arr.length
  if (!len) {
    return ''
  }
  let list = []
  let pre = arr[0]
  for (let i = 1; i < len; i++) {
    if (arr[i] !== arr[i - 1] + 1) {
      list.push(pre === arr[i - 1] ? pre : `${pre}~${arr[i - 1]}`)
      pre = arr[i]
    }
  }
  list.push(pre === arr[len - 1] ? pre : `${pre}~${arr[len - 1]}`)
  return list.join(',')
}

@XuedaoYuan
Copy link

XuedaoYuan commented Sep 24, 2020

参与一下

var str = '1,2,3,5,7,8,9,12'
function format(str) {
	let arr = str.split(',').map((_) => _ - 0) // [1, 2, 3, 5,7,8,10]
	const result = []
	for (let i = 0, len = arr.length - 1; i < len; i++) {
		if (arr[i + 1] - arr[i] === 1) {
			const theLast = result[result.length - 1]
			if (!(theLast === '~')) {
				result.push(arr[i])
				result.push('~')
			}
		} else {
			result.push(arr[i])
		}
	}
	result.push(arr.pop())
	return result.join(',').replace(/,~,/g, '~')
}
console.log(format(str))

@rudyxu1102
Copy link

const arr = [1, 2, 3, 5, 7, 8, 10]

const solution = (arr) => {
    let res = []    
    let start = arr[0]
    let end = arr[0]
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] + 1 === arr[i + 1]) {
            end = arr[i + 1]
        } else {
            res.push(start === end ? start : `${start}~${end}`)
            start = arr[i + 1]
            end = arr[i + 1]
        }
    }
    return res
}
console.log(solution(arr))

@m7yue
Copy link

m7yue commented Oct 15, 2020

const getArea = (str) => {
  const arr = str.split(',')
  let res = ''
  let start = arr[0], end = ''
  
  for(let i=1; i<arr.length; i++){
    if(arr[i] - arr[i-1] == 1){
      end = arr[i]
    }else {
      let t = start + (end ? '~' + end : '')
      res += res ? ',' + t : t
      start = arr[i]
      end = ''
    }
  }
  let t = start + (end ? '~' + end : '')
  res += res ? ',' + t : t
  return res
}
getArea('1, 2, 3, 5, 7, 8, 10')

@mocayo
Copy link

mocayo commented Nov 5, 2020

const convert = function (arr) {
    const ans = [];
    const n = arr.length;

    for (let i = 0; i < n; i++) {
        const start = arr[i];
        let end = arr[i];

        while (i + 1 < n && arr[i + 1] === end + 1) {
            end = arr[i + 1];
            i++;
        }

        ans.push(end === start ? start : `${start}~${end}`);
    }

    return ans;
};

console.log(convert([1, 2, 3, 5, 7, 8, 10])); // ['1~3', 5, '7~8', 10]

@auyo18
Copy link

auyo18 commented Nov 11, 2020

// 双指针/滑动窗口
const fn = str => {
  let ary = str.split(','),
    res = [],
    i = 0,
    j = 0
  let length = ary.length
  while (j < length) {
    if (ary[j + 1] - ary[j] !== 1) {
      if (j - i > 0) {
        res.push(`${ary[i]}~${ary[j]}`)
      } else {
        res.push(ary[j])
      }
      i = j + 1
    }
    j++
  }
  return res.toString()
}

@coveyz
Copy link

coveyz commented Nov 19, 2020

写完之后看看 大佬的
哭了
感觉自己写了托💩

const magic = (arr) => {
	let resultArr = [];
	let cacheArr = [];

	for (let index = 0; index < arr.length; index++) {
		const element = arr[index];
		if (index === 0) {
			cacheArr.push(element);
		} else {
			const qqLastItem = cacheArr[cacheArr.length - 1];
			if (element - 1 === qqLastItem) {
				cacheArr.push(element);
			} else {
				resultArr.push(cacheArr);
				cacheArr = [];
				cacheArr.push(element);
			}
		}
	}

	return resultArr.reduce((acc, cur) => {
		if (cur.length > 1) {
			acc.push(`${cur[0]}~${cur[cur.length - 1]}`);
		} else {
			acc.push(cur[0]);
		}

		return acc;
	}, []);
};

console.log(magic([1, 2, 3, 5, 7, 8, 10])); // [ '1~3', 5, '7~8' ]

@tryingpzm
Copy link

图片凉了,看不到题目了

@yokots
Copy link

yokots commented Jan 3, 2021

/**
 * 输入 1,2,3,5,7,8,10, 输出 1~3,5,7~8,10
 * 如果连续数字的话,就取连续的第一个数和最后一个数,中间用 "~" 隔开。如果不连续就用 "," 隔开。
 */

const str = '1,2,3,5,7,8,10,12,13,14,15,20';

const result = str.split(',').map(Number).reduce((pre, cur, index, arr) => {
  if (index === 0) {
    pre = `${cur}`;
    return pre;
  }

  if (arr[index - 1] === cur - 1) {
    pre += `~${cur}`;
  } else {
    pre +=`,${cur}`
  }

  return pre;
}, '').replace(/(~\d+)+~/g, '~');

console.log(result);

@negativeentropy9
Copy link

function format(str) {
    const arr = str.split(',')
    const result = []
    let start

    for (let i = 0; i < arr.length; i++) {
        start = arr[i]

        while (arr[i + 1] - arr[i] === 1 && i + 1 < arr.length) {
            i++
        }

        if (arr[i] !== start) {
            result.push(`${start}~${arr[i]}`)
        } else {
            result.push(start)
        }
    }

    return result.join(',')
}

console.log(format('1,2,3,5,7,8,10'));

@zhelingwang
Copy link

const str = '1, 2, 3, 5, 7, 8, 10';
function parseNum(str) {
  const _arr = str.split(',');
  const _result = [];
  let _temp = [];
  while (_arr.length > 0) {
    const last = +_arr.shift();
    if (_temp.length === 0) {
      _temp.push(last);
      continue;
    }
    if (last - _temp[_temp.length - 1] < 2) {
      _temp.push(last);
    } else {
      _result.push(_temp.length === 1 ? _temp[0] : `${_temp[0]}~${_temp[_temp.length - 1]}`);
      _temp = [last];
    }
  }
  if (_temp.length > 0) _result.push(_temp.length === 1 ? _temp[0] : `${_temp[0]}~${_temp[_temp.length - 1]}`);
  return _result.join(',');
}

console.log(parseNum(str));

@EdivenH
Copy link

EdivenH commented Jul 28, 2021

function convert(str = '') {
  const arr = str.split(',')
  let i = 0, j = i + 1
  const res = []
  let resStr = [arr[0]]
  while(true) {
    if(i === arr.length) break
    let cur = arr[i]
    let next = arr[j]
    if(next - cur === 1) {
      resStr.push(next)
    } else {
      resStr.length === 1 ? res.push(resStr[0].trim()) : res.push(`${resStr[0].trim()}~${resStr[resStr.length - 1].trim()}`)
      resStr = [arr[j]]
    }
    i = j
    j ++
  }
  return res.join(',')
}

@tbapman
Copy link

tbapman commented Sep 13, 2021

题意为连续数字用~连接然后成为一部分,非连续数字自成一部分
说明:用双指针的方法解决该题,l为慢指针,r为快指针,
如果parseInt(arr[r + 1]) - parseInt(arr[r])===1说明连续,r加1
反之当不连续时,需要判断不连续的区间是否加~

当r-l>=1,说明左右两端都有数字,需加~
反之当r-l===0时,说明该数字自成一部分,无需加~

function solution(str) {
    let arr = str.split(', ');
    let l = 0, r = 0, n = arr.length;
    let res = []
    while (l < n) {
        const diff = parseInt(arr[r + 1]) - parseInt(arr[r])
        const interval = r - l
        if (diff === 1) {
            r++
        } else if (interval >= 1) {
            res.push(`${arr[l]}~${arr[r++]}`)
            l = r
        } else {
            res.push(arr[l++])
            r++
        }

    }
    return res.join(',')

}

// let str = '1, 2, 3, 5, 7, 8, 10';
let str = '1, 2, 3, 4, 7, 8, 10, 13, 15';

console.log(solution(str))

@523451928
Copy link

function summaryRanges(str) {
    const nums = str.split(",").map(item => Number(item));
    const res = [];
    let i = 0;
    const n = nums.length;
    while (i < n) {
        const low = i;
        i++;
        while (i < n && nums[i - 1] + 1 === nums[i]) {
            i++;
        }
        const high = i - 1;
        const temp = ["" + nums[low]];
        if (low < high) {
            temp.push("~");
            temp.push("" + nums[high]);
        }
        res.push(temp.join(""))
    }
    return res.join(",")
}
summaryRanges("1, 2, 3, 5, 7, 8, 10");

@yaoocheng
Copy link


        let arr1 = [1, 2, 3, 5, 7, 8, 10];

        function test(arr) {
            let a = 0;
            let res = [];
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] + 1 !== arr[i + 1]) {
                    if (arr.slice(a, i + 1).length > 1) {
                        res.push(`${arr[a]}~${arr[i]}`)
                    } else {
                        res.push(`${arr[a]}`)
                    }
                    a = i + 1;
                }
            }
            console.log(res.join());
            return res.join();
        }

@a90100
Copy link

a90100 commented May 8, 2022

個人解法:

function output(str) {
  const nums = str.split(',').map(e => +e);
  let result = '', continuous = [];
  
  for(let i = 0; i < nums.length; i++) {
    if (nums[i] + 1 === nums[i + 1]) {
      continuous.push(nums[i]);
    } else if (nums[i] + 1 !== nums[i + 1] && continuous.length > 0) {
      continuous.push(nums[i]);
      result += `,${continuous[0]}~${continuous[continuous.length - 1]}`
      continuous = [];
    } else {
      result += `,${nums[i]}`
    }
  }
  return result.substring(1);
}

console.log(output('1,2,3,5,7,8,10'));

@Vera1128
Copy link

Vera1128 commented May 8, 2022 via email

@xuhen
Copy link

xuhen commented Nov 30, 2022

function convert(s) {
    const arr = s.split(/,\s*/);
    const len = arr.length;
    let temp = '';
    const result = [];
    for (let i = 0; i < len; i++) {
        if (i > 0 && arr[i] - arr[i - 1] === 1) {
            continue;
        }
        if (i > 0) {
            if (temp === arr[i - 1]) {
                result.push(temp);
            } else {
                result.push(`${temp}~${arr[i - 1]}`);
            }
        }
        temp = arr[i];
    }

    if (arr[len - 1] === temp) {
        result.push(temp);
    } else {
        result.push(`${temp}~${arr[len - 1]}`);
    }

    return result.join(',');


}

@caroundsky
Copy link

function transform(arr) {
    arr = arr.split(',').map(i => +i)
    let result = []
    let index = 0
    while(arr.length) {
        let target = arr.shift()
        result[index] ? result[index].push(target) : (result[index] = [target])
        if (target !== arr[0] - 1) index++
    }
    result = result.map(item => {
        if (item.length >= 2) {
            item = [item[0], '~', item[item.length - 1]]
        }
        item = item.join('')
        return item
    })
    
    return result.join(',')
}

@Vera1128
Copy link

Vera1128 commented Dec 23, 2022 via email

@LoveSleepMouse
Copy link

function simplifyStr(arr) {
        const res = [];
        const list = [...arr, 0];
        let pre = 0;
        let isContinue = false;
        for (let index = 1; index < list.length; index++) {
          const element = list[index];
          if (list[index] - list[pre] !== index - pre) {
            if (isContinue) {
              res.push(`${list[pre]}~${list[index - 1]}`);
            } else {
              res.push(list[pre]);
            }
            pre = index;
            isContinue = false;
          } else {
            isContinue = true;
          }
        }
        return res;
      }

@Vera1128
Copy link

Vera1128 commented Feb 7, 2023 via email

@benzhemin
Copy link

benzhemin commented Feb 19, 2023

const collectContinuous = (rawString) => {
  const numList = rawString.split(',').map((elem) => Number(elem));

  const recordArr = [];
  let start, prev;
  const end = numList.length - 1;

  for (let i = 0; i <= end; i++) {
    start = prev = numList[i];
    for (let cursor = i+1; cursor<= end && prev+1 === numList[cursor]; cursor++) {
      prev = numList[cursor];
      i = cursor;
    }

    start === prev ? recordArr.push(`${start}`) : recordArr.push(`${start}~${prev}`);
  }

  console.log(recordArr.join(','))
};

const input = "1,2,3,5,7,8,10";
collectContinuous(input);

@Vera1128
Copy link

Vera1128 commented Aug 18, 2023 via email

@adele-ty
Copy link

adele-ty commented Aug 18, 2023

const arr = [1, 2, 3, 5, 7, 8, 10];
let i = 0, j = i + 1, res = [];
while (i < arr.length) {
       if (arr[j] - arr[j - 1] === 1) {
           j++;
        } else {
          if (j - i > 1) res.push(`${arr[i]}-${arr[j - 1]}`);
          else res.push(arr[i]);
          i = j;
          j = i + 1;
       }
 }
console.log(res)

@Dylan0916
Copy link

Dylan0916 commented Aug 26, 2023

function foo(input) {
  const ary = input.split(',').map(Number);
  let temp = ary[0];
  const result = ary.reduce((acc, cur, index, theAry) => {
    if (cur + 1 === theAry[index + 1]) return acc;

    acc.push(cur === temp ? cur : `${temp}~${cur}`);
    temp = theAry[index + 1];

    return acc;
  }, []);

  return result.toString();
}

console.log(foo('1,2,3,5,7,8,10'));

@negativeentropy9
Copy link

function groupNums(nums) {
    const len = nums.length;
    const SEPARATOR = '~';
    const result = [];
    
    if(!len) {
        return '';
    }

    nums.sort((a, b) => a - b);

    let from = nums[0];

    for(let i = 1; i < nums.length; i++) {
        if(nums[i] - nums[i - 1] !== 1) {
            result.push(from === nums[i - 1] ? from : `${from}${SEPARATOR}${nums[i - 1]}`);
            from = nums[i];
        }
    }

    result.push(from === nums[len - 1] ? from : `${from}${SEPARATOR}${nums[len - 1]}`);

    return result.join(',');
}

console.log(groupNums([1, 2, 3, 5, 7, 8, 10]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests