示例:
结果应包含
这是我要尝试的操作,将dec转换为Hex,然后找到相等的seq。他们有多少
let n = [1, 26, 221];
let arr = [];
let hex = '';
let maxSequence = 0;
let currentCounter = 0;
let sequences = 0;
arr.forEach(element => {
hex += element.toString(16).toLocaleUpperCase();
});
let newarr = [];
const hexSplit = [...hex];
hexSplit.forEach((element, x) => {
if (hexSplit[x + 1] === hexSplit[x]) {
currentCounter++;
newarr.push(hexSplit[x])
}
if (currentCounter > maxSequence) {
maxSequence = currentCounter;
sequences += 1;
} else if (maxSequence === 0) {
maxSequence = 1;
sequences = hexSplit.length;
}
});
console.log(maxSequence, sequences)
答案 0 :(得分:2)
您可以使用一个简单的正则表达式来获取等长字符序列的列表,按长度降序对其进行排序,并按首字符(最长)的长度进行过滤:
function getLongestSeqList(input) {
return input
.match(/(.)\1*/g)
.sort((a,b) => b.length - a.length)
.filter((a,i,arr) => a.length === arr[0].length)
}
console.log(getLongestSeqList('11ADD')); // ["11", "DD"]
console.log(getLongestSeqList('115222')); // ["222"]
console.log(getLongestSeqList('ABCDEF10')); // ["A", "B", "C", "D", "E", "F", "1", "0"]
答案 1 :(得分:1)
const getLongest = seq => seq.reduce(({
longest,
currentItem,
currentLength,
items
}, item) => {
const newCurrentLength = currentItem === item ? currentLength + 1 : 1;
if (newCurrentLength > longest) {
// we have a new longest sequence, assign new values
// to longest and items
return {
currentItem: item,
currentLength: newCurrentLength,
longest: newCurrentLength,
items: 1,
};
} else if (newCurrentLength === longest) {
// we match the previously longest,
// add the item to the sequence list
return {
currentItem: item,
currentLength: longest,
longest,
items: items + 1,
};
} else {
// this is still a shorter sequence,
// just update the local state
return {
currentItem: item,
currentLength: newCurrentLength,
longest,
items
}
}
return ;
}, {
longest: 0,
currentItem: undefined,
currentLength: 0,
items: 0
});
const values = ["11ADD", "115222", "ABCDEF10"];
const res = values.map(s => s.split("")).map(getLongest);
console.log(res);
请注意,通过该组织,您可以轻松地将数据添加到结果中,例如最长的序列是什么值,从何处开始等...
答案 2 :(得分:0)
此处的所有功劳归于此处的其他答案。 https://stackoverflow.com/a/52152057/125981我只是对其进行了修改,以针对一组值返回结果。请赞成/不接受。
var sequences = ['11ADD', '115222', 'ABCDEF10'];
function getLongestSeqList(input) {
return input
.match(/(.)\1*/g)
.sort((a, b) => b.length - a.length)
.filter((a, i, arr) => a.length === arr[0].length)
}
function getValues(s) {
let seq = getLongestSeqList(s);
return {
Count: seq.length,
Len: seq[0].length
};
}
sequences.forEach(function(s) {
console.log(getValues(s));
});