'Changes to make for the function which takes as argument a sequence and returns a list of items without any elements with the same value
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example:
uniqueInOrder('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
var uniqueInOrder = function(it) {
let n = 0;
let arr = [];
let i = 0;
let m = 0;
length = it.length;
if (length == 0) {
return arr
} else {
if (n == 0) {
arr.push(it[0]);
n += 1;
}
while (n < length) {
if (arr[i] != it[m + 1]) {
arr.push(it[m + 1])
i += 1;
n += 1
} else {
m += 1
n += 1
}
}
return arr
}
}
console.log(uniqueInOrder('AAAABBBCCDAABBB'));
should reduce duplicates:
Expected: '[\'A\', \'B\', \'C\', \'D\', \'A\', \'B\']'
instead got: '[\'A\', \'B\', \'C\', \'D\', \'A\']'
should treat lowercase as different from uppercase:
Expected: '[\'A\', \'B\', \'C\', \'c\', \'A\', \'D\']'
instead got: '[\'A\', \'B\', \'C\', \'c\']'
Solution 1:[1]
You need to increase m at each iteration not just when a match is not found. The same goes for n
var uniqueInOrder = function(it) {
let n = 0;
let arr = [];
let i = 0;
let m = 0;
length = it.length;
if (length == 0) {
return arr
} else {
if (n == 0) {
arr.push(it[0]);
n += 1;
}
while (n < length) {
if (arr[i] != it[m + 1]) {
arr.push(it[m + 1])
i += 1;
n += 1
}
m += 1
n += 1
}
return arr
}
}
console.log(uniqueInOrder('AAAABBBCCDAABBB'));
Solution 2:[2]
The Solution can be implemented using
- Using rest & spread operator
- Checking if the input is a string or an array
Below is the working code
var uniqueInOrder=function(iterable){
if (typeof iterable === 'string') {
let newArray = [];
const [...arr] = [...iterable];
for (let i = 0; i < arr.length; i++) {
if (arr[i] != arr[i + 1]) {
newArray.push(arr[i])
}
}
return newArray;
}
else{
let newArray = [];
for (let i = 0; i < iterable.length; i++) {
if (iterable[i] != iterable[i + 1]) {
newArray.push(arr[i])
}
}
return newArray;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Titus |
| Solution 2 | Ali Tauseef Reza |
