Created
May 23, 2016 00:47
-
-
Save alpham/65326d64a595ac13680787fe8ec9ede7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
function pack(arr){ | |
// prev_item is the first item | |
var prev_item = arr[0]; | |
// count of the first item is 1 at this stage | |
var count_items = [1]; | |
// first item is very new to unique_items so it is unique | |
var unique_items = [prev_item]; | |
// start from the second item. | |
for (var i = 1; i < arr.length; i++) { | |
// push new items only | |
if (unique_items.indexOf(arr[i]) == -1) { | |
unique_items.push(arr[i]); | |
} | |
// make count_items and unique_items equal in length | |
if (count_items.length < unique_items.length){ | |
count_items.push(1); | |
} | |
// if the current item == the prev item increase the count by 1 | |
if (prev_item == arr[i]) { | |
var target_item = unique_items.indexOf(prev_item); | |
count_items[target_item] = count_items[target_item] + 1; | |
} | |
prev_item = arr[i]; | |
} | |
if (count_items.length == unique_items.length) { | |
var res = []; | |
for (var i = 0; i < unique_items.length; i++) { | |
res.push(unique_items[i] + ":" + count_items[i]); | |
} | |
return res | |
} else { | |
throw "Error: number of items must equals number of their counts."; | |
} | |
} | |
console.log(pack([5,5,5,7,7,3,4,7])); | |
// [ '5:3', '7:2', '3:1', '4:1' ] | |
console.log(pack([5,5,5,7,7,3,4,7,8])); | |
// [ '5:3', '7:2', '3:1', '4:1', '8:1' ] | |
// and here is our the trick, which I don't know if it a bug or expected behaviour!! | |
console.log(pack([7,5,5,5,7,7,3,4,7,8])); | |
// [ '7:2', '5:3', '3:1', '4:1', '8:1' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment