Sort array on basis of Bit count in ascending order
Please tell me what changes shall i make to sort the array in ascending order, on count of bits
Consider an array of n decimal integers named elements. We want to rearrange elements according to the following rules:
Sort the integers in ascending order by the number of 1's in their binary representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1 in binary) would be ordered before 7 (which has triple 1's in binary).
Two or more integers having the same number of 1's in their binary representations are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both contain double 1's in their binary representation, so 5 would be ordered before 6 because it has the smaller decimal value.
Where am I wrong?
Input:
5
5
3
7
10
14
Ouput:
3
5
10
7
14
Code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Tester {
/**
* Complete the function below.
* DONOT MODIFY anything outside this function!
*/
static int rearrange(int elements) {
int aux= new int[elements.length];
int a;
for (int i=0; i<elements.length; i++){
int count = 0;
a=elements[i];
for(int k =0; k<32; k++){
if( (a&1) == 1) {
count++; }
a = a >>> 1;
}
aux[i]=count;
System.out.println(aux[i]);
// System.out.println(elements[i]);
}
//System.out.println(aux);
//System.out.println(elements);
for (int i = 1; i < (elements.length); i++)
{
//System.out.println(aux[i]);
//System.out.println(elements[i]);
// use 2 keys because we need to sort both
// arrays simultaneously
int key1 = aux[i];
int key2 = elements[i];
int j = i-1;
/* Move elements of arr[0..i-1] and aux[0..i-1],
such that elements of aux[0..i-1] are
greater than key1, to one position ahead
of their current position */
while (j >= 0 && aux[j] > key1)
{
aux[j+1] = aux[j];
elements[j+1] = elements[j];
j = j-1;
}
aux[j+1] = key1;
elements[j+1] = key2;
}
//System.out.println(aux);
return elements;
}
/**
* DO NOT MODIFY THIS METHOD!
*/
public static void main(String args) throws IOException {
Scanner in = new Scanner(System.in);
int n = 0;
n = Integer.parseInt(in.nextLine().trim());
int elements = new int[n];
int element;
for (int i = 0; i < n; i++) {
element = Integer.parseInt(in.nextLine().trim());
elements[i] = element;
}
// call rearrange function
int results =rearrange(elements);
for (int i = 0; i < results.length; i++) {
System.out.println(String.valueOf(results[i]));
}
}
}
java
add a comment |
Please tell me what changes shall i make to sort the array in ascending order, on count of bits
Consider an array of n decimal integers named elements. We want to rearrange elements according to the following rules:
Sort the integers in ascending order by the number of 1's in their binary representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1 in binary) would be ordered before 7 (which has triple 1's in binary).
Two or more integers having the same number of 1's in their binary representations are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both contain double 1's in their binary representation, so 5 would be ordered before 6 because it has the smaller decimal value.
Where am I wrong?
Input:
5
5
3
7
10
14
Ouput:
3
5
10
7
14
Code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Tester {
/**
* Complete the function below.
* DONOT MODIFY anything outside this function!
*/
static int rearrange(int elements) {
int aux= new int[elements.length];
int a;
for (int i=0; i<elements.length; i++){
int count = 0;
a=elements[i];
for(int k =0; k<32; k++){
if( (a&1) == 1) {
count++; }
a = a >>> 1;
}
aux[i]=count;
System.out.println(aux[i]);
// System.out.println(elements[i]);
}
//System.out.println(aux);
//System.out.println(elements);
for (int i = 1; i < (elements.length); i++)
{
//System.out.println(aux[i]);
//System.out.println(elements[i]);
// use 2 keys because we need to sort both
// arrays simultaneously
int key1 = aux[i];
int key2 = elements[i];
int j = i-1;
/* Move elements of arr[0..i-1] and aux[0..i-1],
such that elements of aux[0..i-1] are
greater than key1, to one position ahead
of their current position */
while (j >= 0 && aux[j] > key1)
{
aux[j+1] = aux[j];
elements[j+1] = elements[j];
j = j-1;
}
aux[j+1] = key1;
elements[j+1] = key2;
}
//System.out.println(aux);
return elements;
}
/**
* DO NOT MODIFY THIS METHOD!
*/
public static void main(String args) throws IOException {
Scanner in = new Scanner(System.in);
int n = 0;
n = Integer.parseInt(in.nextLine().trim());
int elements = new int[n];
int element;
for (int i = 0; i < n; i++) {
element = Integer.parseInt(in.nextLine().trim());
elements[i] = element;
}
// call rearrange function
int results =rearrange(elements);
for (int i = 0; i < results.length; i++) {
System.out.println(String.valueOf(results[i]));
}
}
}
java
10002 or 1112 are not valid binary numbers
– Ayush Gupta
Feb 17 '18 at 16:55
4
Stick Java Bit Operation on Long - Counting Set and Unset bits and Using comparator to make custom sort together and there's your answer. Or, if you're specifically looking to figure out what's wrong with your code, or how to do this without letting library functions do the heavy lifting, I'd recommend some debugging.
– Dukeling
Feb 17 '18 at 16:59
@ayush inhave edited
– Deepanjan
Feb 17 '18 at 17:13
anyways it was not about debugging, i know how to debug and it was just only about the DS logic i wanted to look through. Thank you guys for ur help.
– Deepanjan
Feb 18 '18 at 6:54
add a comment |
Please tell me what changes shall i make to sort the array in ascending order, on count of bits
Consider an array of n decimal integers named elements. We want to rearrange elements according to the following rules:
Sort the integers in ascending order by the number of 1's in their binary representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1 in binary) would be ordered before 7 (which has triple 1's in binary).
Two or more integers having the same number of 1's in their binary representations are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both contain double 1's in their binary representation, so 5 would be ordered before 6 because it has the smaller decimal value.
Where am I wrong?
Input:
5
5
3
7
10
14
Ouput:
3
5
10
7
14
Code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Tester {
/**
* Complete the function below.
* DONOT MODIFY anything outside this function!
*/
static int rearrange(int elements) {
int aux= new int[elements.length];
int a;
for (int i=0; i<elements.length; i++){
int count = 0;
a=elements[i];
for(int k =0; k<32; k++){
if( (a&1) == 1) {
count++; }
a = a >>> 1;
}
aux[i]=count;
System.out.println(aux[i]);
// System.out.println(elements[i]);
}
//System.out.println(aux);
//System.out.println(elements);
for (int i = 1; i < (elements.length); i++)
{
//System.out.println(aux[i]);
//System.out.println(elements[i]);
// use 2 keys because we need to sort both
// arrays simultaneously
int key1 = aux[i];
int key2 = elements[i];
int j = i-1;
/* Move elements of arr[0..i-1] and aux[0..i-1],
such that elements of aux[0..i-1] are
greater than key1, to one position ahead
of their current position */
while (j >= 0 && aux[j] > key1)
{
aux[j+1] = aux[j];
elements[j+1] = elements[j];
j = j-1;
}
aux[j+1] = key1;
elements[j+1] = key2;
}
//System.out.println(aux);
return elements;
}
/**
* DO NOT MODIFY THIS METHOD!
*/
public static void main(String args) throws IOException {
Scanner in = new Scanner(System.in);
int n = 0;
n = Integer.parseInt(in.nextLine().trim());
int elements = new int[n];
int element;
for (int i = 0; i < n; i++) {
element = Integer.parseInt(in.nextLine().trim());
elements[i] = element;
}
// call rearrange function
int results =rearrange(elements);
for (int i = 0; i < results.length; i++) {
System.out.println(String.valueOf(results[i]));
}
}
}
java
Please tell me what changes shall i make to sort the array in ascending order, on count of bits
Consider an array of n decimal integers named elements. We want to rearrange elements according to the following rules:
Sort the integers in ascending order by the number of 1's in their binary representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1 in binary) would be ordered before 7 (which has triple 1's in binary).
Two or more integers having the same number of 1's in their binary representations are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both contain double 1's in their binary representation, so 5 would be ordered before 6 because it has the smaller decimal value.
Where am I wrong?
Input:
5
5
3
7
10
14
Ouput:
3
5
10
7
14
Code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Tester {
/**
* Complete the function below.
* DONOT MODIFY anything outside this function!
*/
static int rearrange(int elements) {
int aux= new int[elements.length];
int a;
for (int i=0; i<elements.length; i++){
int count = 0;
a=elements[i];
for(int k =0; k<32; k++){
if( (a&1) == 1) {
count++; }
a = a >>> 1;
}
aux[i]=count;
System.out.println(aux[i]);
// System.out.println(elements[i]);
}
//System.out.println(aux);
//System.out.println(elements);
for (int i = 1; i < (elements.length); i++)
{
//System.out.println(aux[i]);
//System.out.println(elements[i]);
// use 2 keys because we need to sort both
// arrays simultaneously
int key1 = aux[i];
int key2 = elements[i];
int j = i-1;
/* Move elements of arr[0..i-1] and aux[0..i-1],
such that elements of aux[0..i-1] are
greater than key1, to one position ahead
of their current position */
while (j >= 0 && aux[j] > key1)
{
aux[j+1] = aux[j];
elements[j+1] = elements[j];
j = j-1;
}
aux[j+1] = key1;
elements[j+1] = key2;
}
//System.out.println(aux);
return elements;
}
/**
* DO NOT MODIFY THIS METHOD!
*/
public static void main(String args) throws IOException {
Scanner in = new Scanner(System.in);
int n = 0;
n = Integer.parseInt(in.nextLine().trim());
int elements = new int[n];
int element;
for (int i = 0; i < n; i++) {
element = Integer.parseInt(in.nextLine().trim());
elements[i] = element;
}
// call rearrange function
int results =rearrange(elements);
for (int i = 0; i < results.length; i++) {
System.out.println(String.valueOf(results[i]));
}
}
}
java
java
edited Feb 17 '18 at 17:13
Deepanjan
asked Feb 17 '18 at 16:53
DeepanjanDeepanjan
629715
629715
10002 or 1112 are not valid binary numbers
– Ayush Gupta
Feb 17 '18 at 16:55
4
Stick Java Bit Operation on Long - Counting Set and Unset bits and Using comparator to make custom sort together and there's your answer. Or, if you're specifically looking to figure out what's wrong with your code, or how to do this without letting library functions do the heavy lifting, I'd recommend some debugging.
– Dukeling
Feb 17 '18 at 16:59
@ayush inhave edited
– Deepanjan
Feb 17 '18 at 17:13
anyways it was not about debugging, i know how to debug and it was just only about the DS logic i wanted to look through. Thank you guys for ur help.
– Deepanjan
Feb 18 '18 at 6:54
add a comment |
10002 or 1112 are not valid binary numbers
– Ayush Gupta
Feb 17 '18 at 16:55
4
Stick Java Bit Operation on Long - Counting Set and Unset bits and Using comparator to make custom sort together and there's your answer. Or, if you're specifically looking to figure out what's wrong with your code, or how to do this without letting library functions do the heavy lifting, I'd recommend some debugging.
– Dukeling
Feb 17 '18 at 16:59
@ayush inhave edited
– Deepanjan
Feb 17 '18 at 17:13
anyways it was not about debugging, i know how to debug and it was just only about the DS logic i wanted to look through. Thank you guys for ur help.
– Deepanjan
Feb 18 '18 at 6:54
10002 or 1112 are not valid binary numbers
– Ayush Gupta
Feb 17 '18 at 16:55
10002 or 1112 are not valid binary numbers
– Ayush Gupta
Feb 17 '18 at 16:55
4
4
Stick Java Bit Operation on Long - Counting Set and Unset bits and Using comparator to make custom sort together and there's your answer. Or, if you're specifically looking to figure out what's wrong with your code, or how to do this without letting library functions do the heavy lifting, I'd recommend some debugging.
– Dukeling
Feb 17 '18 at 16:59
Stick Java Bit Operation on Long - Counting Set and Unset bits and Using comparator to make custom sort together and there's your answer. Or, if you're specifically looking to figure out what's wrong with your code, or how to do this without letting library functions do the heavy lifting, I'd recommend some debugging.
– Dukeling
Feb 17 '18 at 16:59
@ayush inhave edited
– Deepanjan
Feb 17 '18 at 17:13
@ayush inhave edited
– Deepanjan
Feb 17 '18 at 17:13
anyways it was not about debugging, i know how to debug and it was just only about the DS logic i wanted to look through. Thank you guys for ur help.
– Deepanjan
Feb 18 '18 at 6:54
anyways it was not about debugging, i know how to debug and it was just only about the DS logic i wanted to look through. Thank you guys for ur help.
– Deepanjan
Feb 18 '18 at 6:54
add a comment |
3 Answers
3
active
oldest
votes
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* Sort the integers in ascending order by the number of 1's in their binary
* representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1
* in binary) would be ordered before 7 (which has triple 1's in binary). Two or
* more integers having the same number of 1's in their binary representations
* are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both
* contain double 1's in their binary representation, so 5 would be ordered
* before 6 because it has the smaller decimal value.
*/
public class Solution {
public static void main(String args) {
List<Integer> myList = new ArrayList<>();
myList.add(5);
myList.add(3);
myList.add(5);
myList.add(7);
myList.add(10);
myList.add(14);
myList.add(6);
Solution s1 = new Solution();
System.out.println("before: " + myList.toString());
/*
* for (Integer num : myList) { System.out.println("*** sNumber = " + num);
* System.out.println("Binary = " + Integer.toBinaryString(num));
* System.out.println("Number of one bits = " + Integer.bitCount(num)); }
*/
System.out.println("after: " + s1.rearrangeList(myList).toString());
}
public List<Integer> rearrangeList(List<Integer> theList) {
Collections.sort(theList, new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
/*
* a negative integer, zero, or a positive integer as the first argument
* is less
* than, equal to, or greater than the second.
*/
int result = 0;
if (num1 == num2) {
result = 0;
} else if (Integer.bitCount(num1) < Integer.bitCount(num2)) {// 5=101 and
// 7=111
result = -1;
} else if (Integer.bitCount(num1) > Integer.bitCount(num2)) {// 7=111 and
// 6=110
result = 1;
} else if (Integer.bitCount(num1) == Integer.bitCount(num2)) {// 5=101
// 10=1010
result = (num1 < num2) ? -1 : 1;// sort in natural order
}
return result;
}
});
return theList;
}
}
Could you give an explanation of why this is an answer?
– Dragonthoughts
Oct 9 '18 at 8:03
This is the best/efficient answer.
– Mr.India
Oct 28 '18 at 9:34
add a comment |
public static List<Integer> rearrange(List<Integer> elements){
if(elements == null) {
return null;
}
Collections.sort(elements, new sortByBinaryRep());
Set<Integer> set = new LinkedHashSet<>(elements);
return new LinkedList<>(set);
}
import java.util.Comparator;
public class sortByBinaryRep implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
String binaryRep1 = Integer.toBinaryString(num1);
String binaryRep2 = Integer.toBinaryString(num2);
int bits1 = countBits(binaryRep1);
int bits2 = countBits(binaryRep2);
if(bits1 == bits2) {
return num1 - num2;
}
else {
return bits1 - bits2;
}
}
private int countBits(String a){
int count = 0;
for(char c: a.toCharArray()) {
if(c == '1') {
count++;
}
}
return count;
}
}
It would help if you added a little explanation about how your code solves the OPs issue.
– SuperShoot
Nov 25 '18 at 8:22
add a comment |
This is the C# code for anyone interested:
using System;
namespace ConsoleApp1
{
class Program
{
static int rearrange(int elements)
{
Array.Sort(elements);
int countOfOnesFromElements = new int[elements.Length];
int currentElement;
for (int i = 0; i < elements.Length; i++)
{
int countTheNumberOfOnes = 0;
currentElement = elements[i];
for (int k = 0; k < 32; k++)
{
if ((currentElement & 1) == 1)
{
countTheNumberOfOnes++;
}
currentElement = currentElement >> 1;
}
countOfOnesFromElements[i] = countTheNumberOfOnes;
Console.WriteLine(countOfOnesFromElements[i]);
}
for (int i = 1; i < (elements.Length); i++)
{
int key1 = countOfOnesFromElements[i];
int key2 = elements[i];
int j = i - 1;
while (j >= 0 && countOfOnesFromElements[j] > key1)
{
countOfOnesFromElements[j + 1] = countOfOnesFromElements[j];
elements[j + 1] = elements[j];
j = j - 1;
}
countOfOnesFromElements[j + 1] = key1;
elements[j + 1] = key2;
}
return elements;
}
static void Main(string args)
{
int res;
int _elements_size = 0;
Console.WriteLine("Input the element size: ");
_elements_size = Convert.ToInt32(Console.ReadLine());
int _elements = new int[_elements_size];
int _elements_item;
for(int _elements_i = 0; _elements_i < _elements_size; _elements_i++)
{
Console.WriteLine("What is Element {0}? ", _elements_i);
_elements_item = Convert.ToInt32(Console.ReadLine());
_elements[_elements_i] = +_elements_item;
}
res = rearrange(_elements);
Console.WriteLine("rnAll elements in order of binary");
for(int res_i = 0; res_i < res.Length; res_i++)
{
Console.WriteLine(res[res_i]);
}
Console.ReadLine();
}
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f48843662%2fsort-array-on-basis-of-bit-count-in-ascending-order%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* Sort the integers in ascending order by the number of 1's in their binary
* representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1
* in binary) would be ordered before 7 (which has triple 1's in binary). Two or
* more integers having the same number of 1's in their binary representations
* are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both
* contain double 1's in their binary representation, so 5 would be ordered
* before 6 because it has the smaller decimal value.
*/
public class Solution {
public static void main(String args) {
List<Integer> myList = new ArrayList<>();
myList.add(5);
myList.add(3);
myList.add(5);
myList.add(7);
myList.add(10);
myList.add(14);
myList.add(6);
Solution s1 = new Solution();
System.out.println("before: " + myList.toString());
/*
* for (Integer num : myList) { System.out.println("*** sNumber = " + num);
* System.out.println("Binary = " + Integer.toBinaryString(num));
* System.out.println("Number of one bits = " + Integer.bitCount(num)); }
*/
System.out.println("after: " + s1.rearrangeList(myList).toString());
}
public List<Integer> rearrangeList(List<Integer> theList) {
Collections.sort(theList, new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
/*
* a negative integer, zero, or a positive integer as the first argument
* is less
* than, equal to, or greater than the second.
*/
int result = 0;
if (num1 == num2) {
result = 0;
} else if (Integer.bitCount(num1) < Integer.bitCount(num2)) {// 5=101 and
// 7=111
result = -1;
} else if (Integer.bitCount(num1) > Integer.bitCount(num2)) {// 7=111 and
// 6=110
result = 1;
} else if (Integer.bitCount(num1) == Integer.bitCount(num2)) {// 5=101
// 10=1010
result = (num1 < num2) ? -1 : 1;// sort in natural order
}
return result;
}
});
return theList;
}
}
Could you give an explanation of why this is an answer?
– Dragonthoughts
Oct 9 '18 at 8:03
This is the best/efficient answer.
– Mr.India
Oct 28 '18 at 9:34
add a comment |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* Sort the integers in ascending order by the number of 1's in their binary
* representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1
* in binary) would be ordered before 7 (which has triple 1's in binary). Two or
* more integers having the same number of 1's in their binary representations
* are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both
* contain double 1's in their binary representation, so 5 would be ordered
* before 6 because it has the smaller decimal value.
*/
public class Solution {
public static void main(String args) {
List<Integer> myList = new ArrayList<>();
myList.add(5);
myList.add(3);
myList.add(5);
myList.add(7);
myList.add(10);
myList.add(14);
myList.add(6);
Solution s1 = new Solution();
System.out.println("before: " + myList.toString());
/*
* for (Integer num : myList) { System.out.println("*** sNumber = " + num);
* System.out.println("Binary = " + Integer.toBinaryString(num));
* System.out.println("Number of one bits = " + Integer.bitCount(num)); }
*/
System.out.println("after: " + s1.rearrangeList(myList).toString());
}
public List<Integer> rearrangeList(List<Integer> theList) {
Collections.sort(theList, new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
/*
* a negative integer, zero, or a positive integer as the first argument
* is less
* than, equal to, or greater than the second.
*/
int result = 0;
if (num1 == num2) {
result = 0;
} else if (Integer.bitCount(num1) < Integer.bitCount(num2)) {// 5=101 and
// 7=111
result = -1;
} else if (Integer.bitCount(num1) > Integer.bitCount(num2)) {// 7=111 and
// 6=110
result = 1;
} else if (Integer.bitCount(num1) == Integer.bitCount(num2)) {// 5=101
// 10=1010
result = (num1 < num2) ? -1 : 1;// sort in natural order
}
return result;
}
});
return theList;
}
}
Could you give an explanation of why this is an answer?
– Dragonthoughts
Oct 9 '18 at 8:03
This is the best/efficient answer.
– Mr.India
Oct 28 '18 at 9:34
add a comment |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* Sort the integers in ascending order by the number of 1's in their binary
* representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1
* in binary) would be ordered before 7 (which has triple 1's in binary). Two or
* more integers having the same number of 1's in their binary representations
* are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both
* contain double 1's in their binary representation, so 5 would be ordered
* before 6 because it has the smaller decimal value.
*/
public class Solution {
public static void main(String args) {
List<Integer> myList = new ArrayList<>();
myList.add(5);
myList.add(3);
myList.add(5);
myList.add(7);
myList.add(10);
myList.add(14);
myList.add(6);
Solution s1 = new Solution();
System.out.println("before: " + myList.toString());
/*
* for (Integer num : myList) { System.out.println("*** sNumber = " + num);
* System.out.println("Binary = " + Integer.toBinaryString(num));
* System.out.println("Number of one bits = " + Integer.bitCount(num)); }
*/
System.out.println("after: " + s1.rearrangeList(myList).toString());
}
public List<Integer> rearrangeList(List<Integer> theList) {
Collections.sort(theList, new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
/*
* a negative integer, zero, or a positive integer as the first argument
* is less
* than, equal to, or greater than the second.
*/
int result = 0;
if (num1 == num2) {
result = 0;
} else if (Integer.bitCount(num1) < Integer.bitCount(num2)) {// 5=101 and
// 7=111
result = -1;
} else if (Integer.bitCount(num1) > Integer.bitCount(num2)) {// 7=111 and
// 6=110
result = 1;
} else if (Integer.bitCount(num1) == Integer.bitCount(num2)) {// 5=101
// 10=1010
result = (num1 < num2) ? -1 : 1;// sort in natural order
}
return result;
}
});
return theList;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* Sort the integers in ascending order by the number of 1's in their binary
* representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1
* in binary) would be ordered before 7 (which has triple 1's in binary). Two or
* more integers having the same number of 1's in their binary representations
* are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both
* contain double 1's in their binary representation, so 5 would be ordered
* before 6 because it has the smaller decimal value.
*/
public class Solution {
public static void main(String args) {
List<Integer> myList = new ArrayList<>();
myList.add(5);
myList.add(3);
myList.add(5);
myList.add(7);
myList.add(10);
myList.add(14);
myList.add(6);
Solution s1 = new Solution();
System.out.println("before: " + myList.toString());
/*
* for (Integer num : myList) { System.out.println("*** sNumber = " + num);
* System.out.println("Binary = " + Integer.toBinaryString(num));
* System.out.println("Number of one bits = " + Integer.bitCount(num)); }
*/
System.out.println("after: " + s1.rearrangeList(myList).toString());
}
public List<Integer> rearrangeList(List<Integer> theList) {
Collections.sort(theList, new Comparator<Integer>() {
@Override
public int compare(Integer num1, Integer num2) {
/*
* a negative integer, zero, or a positive integer as the first argument
* is less
* than, equal to, or greater than the second.
*/
int result = 0;
if (num1 == num2) {
result = 0;
} else if (Integer.bitCount(num1) < Integer.bitCount(num2)) {// 5=101 and
// 7=111
result = -1;
} else if (Integer.bitCount(num1) > Integer.bitCount(num2)) {// 7=111 and
// 6=110
result = 1;
} else if (Integer.bitCount(num1) == Integer.bitCount(num2)) {// 5=101
// 10=1010
result = (num1 < num2) ? -1 : 1;// sort in natural order
}
return result;
}
});
return theList;
}
}
answered Oct 9 '18 at 7:43
A. SchwarzA. Schwarz
212
212
Could you give an explanation of why this is an answer?
– Dragonthoughts
Oct 9 '18 at 8:03
This is the best/efficient answer.
– Mr.India
Oct 28 '18 at 9:34
add a comment |
Could you give an explanation of why this is an answer?
– Dragonthoughts
Oct 9 '18 at 8:03
This is the best/efficient answer.
– Mr.India
Oct 28 '18 at 9:34
Could you give an explanation of why this is an answer?
– Dragonthoughts
Oct 9 '18 at 8:03
Could you give an explanation of why this is an answer?
– Dragonthoughts
Oct 9 '18 at 8:03
This is the best/efficient answer.
– Mr.India
Oct 28 '18 at 9:34
This is the best/efficient answer.
– Mr.India
Oct 28 '18 at 9:34
add a comment |
public static List<Integer> rearrange(List<Integer> elements){
if(elements == null) {
return null;
}
Collections.sort(elements, new sortByBinaryRep());
Set<Integer> set = new LinkedHashSet<>(elements);
return new LinkedList<>(set);
}
import java.util.Comparator;
public class sortByBinaryRep implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
String binaryRep1 = Integer.toBinaryString(num1);
String binaryRep2 = Integer.toBinaryString(num2);
int bits1 = countBits(binaryRep1);
int bits2 = countBits(binaryRep2);
if(bits1 == bits2) {
return num1 - num2;
}
else {
return bits1 - bits2;
}
}
private int countBits(String a){
int count = 0;
for(char c: a.toCharArray()) {
if(c == '1') {
count++;
}
}
return count;
}
}
It would help if you added a little explanation about how your code solves the OPs issue.
– SuperShoot
Nov 25 '18 at 8:22
add a comment |
public static List<Integer> rearrange(List<Integer> elements){
if(elements == null) {
return null;
}
Collections.sort(elements, new sortByBinaryRep());
Set<Integer> set = new LinkedHashSet<>(elements);
return new LinkedList<>(set);
}
import java.util.Comparator;
public class sortByBinaryRep implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
String binaryRep1 = Integer.toBinaryString(num1);
String binaryRep2 = Integer.toBinaryString(num2);
int bits1 = countBits(binaryRep1);
int bits2 = countBits(binaryRep2);
if(bits1 == bits2) {
return num1 - num2;
}
else {
return bits1 - bits2;
}
}
private int countBits(String a){
int count = 0;
for(char c: a.toCharArray()) {
if(c == '1') {
count++;
}
}
return count;
}
}
It would help if you added a little explanation about how your code solves the OPs issue.
– SuperShoot
Nov 25 '18 at 8:22
add a comment |
public static List<Integer> rearrange(List<Integer> elements){
if(elements == null) {
return null;
}
Collections.sort(elements, new sortByBinaryRep());
Set<Integer> set = new LinkedHashSet<>(elements);
return new LinkedList<>(set);
}
import java.util.Comparator;
public class sortByBinaryRep implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
String binaryRep1 = Integer.toBinaryString(num1);
String binaryRep2 = Integer.toBinaryString(num2);
int bits1 = countBits(binaryRep1);
int bits2 = countBits(binaryRep2);
if(bits1 == bits2) {
return num1 - num2;
}
else {
return bits1 - bits2;
}
}
private int countBits(String a){
int count = 0;
for(char c: a.toCharArray()) {
if(c == '1') {
count++;
}
}
return count;
}
}
public static List<Integer> rearrange(List<Integer> elements){
if(elements == null) {
return null;
}
Collections.sort(elements, new sortByBinaryRep());
Set<Integer> set = new LinkedHashSet<>(elements);
return new LinkedList<>(set);
}
import java.util.Comparator;
public class sortByBinaryRep implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
String binaryRep1 = Integer.toBinaryString(num1);
String binaryRep2 = Integer.toBinaryString(num2);
int bits1 = countBits(binaryRep1);
int bits2 = countBits(binaryRep2);
if(bits1 == bits2) {
return num1 - num2;
}
else {
return bits1 - bits2;
}
}
private int countBits(String a){
int count = 0;
for(char c: a.toCharArray()) {
if(c == '1') {
count++;
}
}
return count;
}
}
answered Nov 25 '18 at 8:03
Sudharshan RaoSudharshan Rao
62
62
It would help if you added a little explanation about how your code solves the OPs issue.
– SuperShoot
Nov 25 '18 at 8:22
add a comment |
It would help if you added a little explanation about how your code solves the OPs issue.
– SuperShoot
Nov 25 '18 at 8:22
It would help if you added a little explanation about how your code solves the OPs issue.
– SuperShoot
Nov 25 '18 at 8:22
It would help if you added a little explanation about how your code solves the OPs issue.
– SuperShoot
Nov 25 '18 at 8:22
add a comment |
This is the C# code for anyone interested:
using System;
namespace ConsoleApp1
{
class Program
{
static int rearrange(int elements)
{
Array.Sort(elements);
int countOfOnesFromElements = new int[elements.Length];
int currentElement;
for (int i = 0; i < elements.Length; i++)
{
int countTheNumberOfOnes = 0;
currentElement = elements[i];
for (int k = 0; k < 32; k++)
{
if ((currentElement & 1) == 1)
{
countTheNumberOfOnes++;
}
currentElement = currentElement >> 1;
}
countOfOnesFromElements[i] = countTheNumberOfOnes;
Console.WriteLine(countOfOnesFromElements[i]);
}
for (int i = 1; i < (elements.Length); i++)
{
int key1 = countOfOnesFromElements[i];
int key2 = elements[i];
int j = i - 1;
while (j >= 0 && countOfOnesFromElements[j] > key1)
{
countOfOnesFromElements[j + 1] = countOfOnesFromElements[j];
elements[j + 1] = elements[j];
j = j - 1;
}
countOfOnesFromElements[j + 1] = key1;
elements[j + 1] = key2;
}
return elements;
}
static void Main(string args)
{
int res;
int _elements_size = 0;
Console.WriteLine("Input the element size: ");
_elements_size = Convert.ToInt32(Console.ReadLine());
int _elements = new int[_elements_size];
int _elements_item;
for(int _elements_i = 0; _elements_i < _elements_size; _elements_i++)
{
Console.WriteLine("What is Element {0}? ", _elements_i);
_elements_item = Convert.ToInt32(Console.ReadLine());
_elements[_elements_i] = +_elements_item;
}
res = rearrange(_elements);
Console.WriteLine("rnAll elements in order of binary");
for(int res_i = 0; res_i < res.Length; res_i++)
{
Console.WriteLine(res[res_i]);
}
Console.ReadLine();
}
}
}
add a comment |
This is the C# code for anyone interested:
using System;
namespace ConsoleApp1
{
class Program
{
static int rearrange(int elements)
{
Array.Sort(elements);
int countOfOnesFromElements = new int[elements.Length];
int currentElement;
for (int i = 0; i < elements.Length; i++)
{
int countTheNumberOfOnes = 0;
currentElement = elements[i];
for (int k = 0; k < 32; k++)
{
if ((currentElement & 1) == 1)
{
countTheNumberOfOnes++;
}
currentElement = currentElement >> 1;
}
countOfOnesFromElements[i] = countTheNumberOfOnes;
Console.WriteLine(countOfOnesFromElements[i]);
}
for (int i = 1; i < (elements.Length); i++)
{
int key1 = countOfOnesFromElements[i];
int key2 = elements[i];
int j = i - 1;
while (j >= 0 && countOfOnesFromElements[j] > key1)
{
countOfOnesFromElements[j + 1] = countOfOnesFromElements[j];
elements[j + 1] = elements[j];
j = j - 1;
}
countOfOnesFromElements[j + 1] = key1;
elements[j + 1] = key2;
}
return elements;
}
static void Main(string args)
{
int res;
int _elements_size = 0;
Console.WriteLine("Input the element size: ");
_elements_size = Convert.ToInt32(Console.ReadLine());
int _elements = new int[_elements_size];
int _elements_item;
for(int _elements_i = 0; _elements_i < _elements_size; _elements_i++)
{
Console.WriteLine("What is Element {0}? ", _elements_i);
_elements_item = Convert.ToInt32(Console.ReadLine());
_elements[_elements_i] = +_elements_item;
}
res = rearrange(_elements);
Console.WriteLine("rnAll elements in order of binary");
for(int res_i = 0; res_i < res.Length; res_i++)
{
Console.WriteLine(res[res_i]);
}
Console.ReadLine();
}
}
}
add a comment |
This is the C# code for anyone interested:
using System;
namespace ConsoleApp1
{
class Program
{
static int rearrange(int elements)
{
Array.Sort(elements);
int countOfOnesFromElements = new int[elements.Length];
int currentElement;
for (int i = 0; i < elements.Length; i++)
{
int countTheNumberOfOnes = 0;
currentElement = elements[i];
for (int k = 0; k < 32; k++)
{
if ((currentElement & 1) == 1)
{
countTheNumberOfOnes++;
}
currentElement = currentElement >> 1;
}
countOfOnesFromElements[i] = countTheNumberOfOnes;
Console.WriteLine(countOfOnesFromElements[i]);
}
for (int i = 1; i < (elements.Length); i++)
{
int key1 = countOfOnesFromElements[i];
int key2 = elements[i];
int j = i - 1;
while (j >= 0 && countOfOnesFromElements[j] > key1)
{
countOfOnesFromElements[j + 1] = countOfOnesFromElements[j];
elements[j + 1] = elements[j];
j = j - 1;
}
countOfOnesFromElements[j + 1] = key1;
elements[j + 1] = key2;
}
return elements;
}
static void Main(string args)
{
int res;
int _elements_size = 0;
Console.WriteLine("Input the element size: ");
_elements_size = Convert.ToInt32(Console.ReadLine());
int _elements = new int[_elements_size];
int _elements_item;
for(int _elements_i = 0; _elements_i < _elements_size; _elements_i++)
{
Console.WriteLine("What is Element {0}? ", _elements_i);
_elements_item = Convert.ToInt32(Console.ReadLine());
_elements[_elements_i] = +_elements_item;
}
res = rearrange(_elements);
Console.WriteLine("rnAll elements in order of binary");
for(int res_i = 0; res_i < res.Length; res_i++)
{
Console.WriteLine(res[res_i]);
}
Console.ReadLine();
}
}
}
This is the C# code for anyone interested:
using System;
namespace ConsoleApp1
{
class Program
{
static int rearrange(int elements)
{
Array.Sort(elements);
int countOfOnesFromElements = new int[elements.Length];
int currentElement;
for (int i = 0; i < elements.Length; i++)
{
int countTheNumberOfOnes = 0;
currentElement = elements[i];
for (int k = 0; k < 32; k++)
{
if ((currentElement & 1) == 1)
{
countTheNumberOfOnes++;
}
currentElement = currentElement >> 1;
}
countOfOnesFromElements[i] = countTheNumberOfOnes;
Console.WriteLine(countOfOnesFromElements[i]);
}
for (int i = 1; i < (elements.Length); i++)
{
int key1 = countOfOnesFromElements[i];
int key2 = elements[i];
int j = i - 1;
while (j >= 0 && countOfOnesFromElements[j] > key1)
{
countOfOnesFromElements[j + 1] = countOfOnesFromElements[j];
elements[j + 1] = elements[j];
j = j - 1;
}
countOfOnesFromElements[j + 1] = key1;
elements[j + 1] = key2;
}
return elements;
}
static void Main(string args)
{
int res;
int _elements_size = 0;
Console.WriteLine("Input the element size: ");
_elements_size = Convert.ToInt32(Console.ReadLine());
int _elements = new int[_elements_size];
int _elements_item;
for(int _elements_i = 0; _elements_i < _elements_size; _elements_i++)
{
Console.WriteLine("What is Element {0}? ", _elements_i);
_elements_item = Convert.ToInt32(Console.ReadLine());
_elements[_elements_i] = +_elements_item;
}
res = rearrange(_elements);
Console.WriteLine("rnAll elements in order of binary");
for(int res_i = 0; res_i < res.Length; res_i++)
{
Console.WriteLine(res[res_i]);
}
Console.ReadLine();
}
}
}
answered Apr 3 '18 at 23:59
SomangSomang
1
1
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f48843662%2fsort-array-on-basis-of-bit-count-in-ascending-order%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
10002 or 1112 are not valid binary numbers
– Ayush Gupta
Feb 17 '18 at 16:55
4
Stick Java Bit Operation on Long - Counting Set and Unset bits and Using comparator to make custom sort together and there's your answer. Or, if you're specifically looking to figure out what's wrong with your code, or how to do this without letting library functions do the heavy lifting, I'd recommend some debugging.
– Dukeling
Feb 17 '18 at 16:59
@ayush inhave edited
– Deepanjan
Feb 17 '18 at 17:13
anyways it was not about debugging, i know how to debug and it was just only about the DS logic i wanted to look through. Thank you guys for ur help.
– Deepanjan
Feb 18 '18 at 6:54