R, 132 96 94 88 84 75 73 53 51 bytes
-20 thanks to J.Doe's implementation
-2 more thanks to Giuseppe
function(x)x[order(colSums(sapply(x,intToBits)<1))]
My original post:
pryr::f(rev(x[order(sapply(x,function(y)sum(as.double(intToBits(y)))))]))
Try it online!
I tried several different methods before I got down to this result.
Matrix Method: Created a two column matrix, one column with the input vector, one of the sum of the binary representation, then I sorted on the sum of binary.
function(x){m=matrix(c(x,colSums(sapply(x,function(y){as.integer(intToBits(y))}))),nc=2,nr=length(x));m[order(m[,2],decreasing=T),]}
Non-Matrix: Realized I could toss out the matrix function and instead create a vector of binary values, sum them, order them, then use the ordered values to reorder the input vector.
function(x){m=colSums(sapply(x,function(y){as.integer(intToBits(y))}));x[order(m,decreasing=T)]}
Minor Changes
function(x){m=colSums(sapply(x,function(y)as.double(intToBits(y))));x[order(m,decreasing=T)]}
More Minor Changes Converting entire thing to one line of code instead of two separated by a semicolon.
function(x)x[order(colSums(sapply(x,function(y)as.double(intToBits(y)))),decreasing=T)]
Sum Method Instead of adding the columns with colSums
of the binary matrix created by sapply
, I added the elements in the column before sapply
"finished."
function(x)x[order(sapply(x,function(y)sum(as.double(intToBits(y)))),decreasing=T)]
Decreasing to Rev I really wanted to shorten decreasing, but R squawks at me if I try to shorten decreasing
in the order
function, which was necessary to get the order desired as order
defaults to increasing, then I remembered the rev
function to reverse a vector. EUREKA!!! The last change in the final solution was function
to pryr::f
to save 2 more bytes
function(x)rev(x[order(sapply(x,function(y)sum(as.double(intToBits(y)))))])