Извините, насчет другого ответа.Я был быстр.
// Ask the original sequence as parameter
function uniqueSequence(originalSequence){
return
originalSequence
.map(function(value, index){ // Get difference between each number.
return value - originalSequence[index - 1]; // Somthing like [1,2,3,2,1] => [NaN, 1,1,-1,-1]
})
.toString() // Parse that result to string format => "NaN,1,1,-1,-1"
.match(/N((,[0-9-]+)*?)\1*$/)[1] // we look for the shortest pattern of comma-separated integers
// (,\d+) starting right after "NaN" and repeating till
// the end of the string. Result in something like => ",1,1,-1,-1"
.substring(1) // Remove the first comma => "1,1,-1,-1"
.split(',') // Convert to array ["1","1","-1","-1"]
.map(function(value){
return parseInt(value); // Parse each element to integer [1,1,-1,-1]
});
}
В кратчайшем коде (ES6)
f=_=>_.map((a,i)=>a-_[i-1]).toString().match(/N((,[0-9-]+)*?)\1*$/)[1].substring(1).split`,`.map(a=>~~a)
f=_=>_.map((a,i)=>a-_[i-1]).toString().match(/N((,[0-9-]+)*?)\1*$/)[1].substring(1).split`,`.map(a=>~~a)
// Ask the original sequence as parameter
function uniqueSequence(originalSequence){
return originalSequence
.map(function(value, index){ // Get difference between each number.
return value - originalSequence[index - 1]; // Somthing like [1,2,3,2,1] => [NaN, 1,1,-1,-1]
})
.toString() // Parse that result to string format => "NaN,1,1,-1,-1"
.match(/N((,[0-9-]+)*?)\1*$/)[1] // we look for the shortest pattern of comma-separated integers
// (,\d+) starting right after "NaN" and repeating till
// the end of the string. Result in something like => ",1,1,-1,-1"
.substring(1) // Remove the first comma => "1,1,-1,-1"
.split(',') // Convert to array ["1","1","-1","-1"]
.map(function(value){
return parseInt(value); // Parse each element to integer [1,1,-1,-1]
});
}
console.log(f([1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]))
console.log(uniqueSequence([1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]))