Issue
Problem title: Binary Sort Ascending:
I have a task which consists of creating a function in JavaScript which orders an array that receives a list of unordered integers. The function must return an ordered array of integers according to the following criteria:
- The greater number of ones in the binary representation of the integer, the closer to the index 0 the element should be.
- In case two or more numbers have the same number of ones in their binary representation, the decimal number of lesser value will be closer to the beginning.
Example:
For the entry: [1, 15, 5, 7, 3]
The return should be: [15, 7, 3, 5, 1]
Explanation:
Decimal = Binary
- 1 = 1
- 15 = 1111
- 5 = 101
- 7 = 111
- 3 = 11
The decimal number whose binary representation contains plus ones is 15 (1111 in binary), so it will go first in the array (index = 0). Then go on the 7, with three (111) ones in its binary representation.
Then there are 2 numbers whose binary representation contains the same number of ones, these decimals are 5 (101) and 3 (11), both with 2 ones. In this case, it will go first (closer to index = 0) the 3, because it's decimal representation is smaller (3 < 5).
Solution:
Finally, I have found a way to solve this task:
const binaryOnes = integerArr => {
let binaryArray = integerArr.map(num => num.toString(2))
binaryArray.sort((a, b) => {
let regEx = /1/g
let A = a.match(regEx).length
let B = b.match(regEx).length
if (A < B) return 1
else if (A > B) return -1
else {
let binaryToIntegerA = parseInt(A, 2)
let binaryToIntegerB = parseInt(B, 2)
if (binaryToIntegerA < binaryToIntegerB) return -1
else return 1
}
})
return binaryArray.map(num => parseInt(num, 2))
}
binaryOnes([1,15,5,7,3]) // [ 15, 7, 3, 5, 1 ]
Please if anyone finds a better way to solve it, I will appreciate.
Also some feedback of this post (is my first question on StackOverflow)
Thanks!
Solution
You can convert a number into binary (string type) with something like
var binary = 134.toString(2);
Then, implement the comparison function between two numbers with
function binaryCompare(a, b) {
a = a.binary;
b = b.binary;
//...
}
After that, just call
[1,2,34,342]
.map( a => ({value:a, binary: a.toString(2))
.sort(binaryCompare)
.map( v => v.value );
As I don't understand your goal, I cannot implement the sort function. Hope it helps
Answered By - farvilain Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.