Finding matching numbers in two arrays - java

Hey I'm trying to write a method that compares two arrays and returns the number of values they have in common.
For example, if there are two arrays:
arr{0,4,2,5}
arr1{0,7,4,4}
Then the method would return 2.
This is what I have so far:
public int numDigitsCorrect(Permutation other) {
int c=0;
for(int i=0; i<nums.length; i++) {
for(int x=0; x<nums.length;x++) {
if(nums[i]==other.nums[x]) {
System.out.println(nums[i] + " " + other.nums[x] + " ");
c++;
}
}
}
return c;
}

You need to change in current function as mention below :
public int numDigitsCorrect(Permutation other)
{
int c=0;
for(int i=0; i<nums.length; i++) {
for(int x=0; x<other.length;x++) {
if(nums[i]==other[x]) {
System.out.println(nums[i] + " " + other[x] + " ");
c++;
}
}
}
return c;
}
I assume that nums and other are your int arrays as shown below
int[] nums = {0,4,2,5};
int[] other = {0,7,4,4};

If you use Set, it will be much more cleaner and readable. Also this will reduce the complexity of your code.
Like:
import java.util.HashSet;
import java.util.Set;
public class NumberMatch {
public static void main(String[] args) {
int[] arrOne = { 0, 4, 2, 5 };
int[] arrTwo = { 0, 7, 4, 4 };
System.out.println(numDigitsCorrect(arrOne, arrTwo));
System.out.println(numDigitsCorrect(arrTwo, arrOne));
System.out.println(numDigitsCorrect(arrOne, arrOne));
System.out.println(numDigitsCorrect(arrTwo, arrTwo));
}
public static int numDigitsCorrect(int[] arrOne, int[] arrTwo) {
Set<Integer> setOne = arrayToSet(arrOne);
Set<Integer> setTwo = arrayToSet(arrTwo);
setOne.retainAll(setTwo);
return setOne.size();
}
private static Set<Integer> arrayToSet(int[] array) {
Set<Integer> retSet = new HashSet<Integer>();
for (int i : array) {
retSet.add(i);
}
return retSet;
}
}
Output:
2
2
4
3

Related

Index 4 out of bounds for length 3. For Union Array

//Whenever I run the code, it keeps giving me the same error. I don't understand why. The union array function's loop also isn't looping completely, likely a problem with the string index out of bound.
//I've tried to change the original function isNumberInArray, but still doesn't work.
package HW;
public class HW_5 {
public static boolean isNumberInArray(int number_check, int array[]) {
for (int value : array) {
value -= 1;
if (number_check == array[value]) {
return true;
}
}
return false;
}
public static int highestlength(int array_1[]) {
int max = array_1[0];
for (int counter = 1; counter < array_1.length; counter++) {
if (array_1[counter] > max) {
max = array_1[counter];
}
}
return max;
}
public static int [] unionArrays(int [] array_1, int [] array_2) {
int array_index_counter = 0;
int highest_1 = highestlength(array_1);
int highest_2 = highestlength(array_2);
int[] union_array = new int[array_1.length + array_2.length];
if (highest_1 > highest_2) {
for (int value_1 : array_1) {
if (isNumberInArray(value_1, array_1) && isNumberInArray(value_1, array_2)) {
union_array[array_index_counter] = value_1;
array_index_counter += 1;
} else {
for (int value_2 : array_2) {
if (isNumberInArray(value_2, array_1) && isNumberInArray(value_2, array_2)) {
union_array[array_index_counter] = value_2;
array_index_counter += 1;
}
}
}
}
}
printArray(union_array);
return union_array;
}
public static void printArray(int array[]) {
for (int value : array) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] Args) {
int list_1[] = {1, 2, 3};
int list_2[] = {1, 3, 5};
System.out.println(isNumberInArray(0, list_1));
System.out.println(unionArrays(list_1, list_2));
}
}
I expected the output to be 1 2 3 5, but the actual output is 0 0 0 0.
For a start the looping in isNumberInArray is strange, try
public static boolean isNumberInArray(int number_check, int array[]) {
for (int value : array) {
if (number_check == value) {
return true;
}
}
return false;
}
Probably because of this your if statements in unionArrays are always false

Constraining all combinations of an array-list

I know similar questions have been asked before but I have found the answers confusing. I am trying to make a program that will find every combination of an array-list with no repetitions and only of the maximum size. If the list has 4 items it should print out only the combinations with all 4 items present. This is what I have so far:
public main(){
UI.initialise();
UI.addButton("Test", this::testCreate);
UI.addButton("Quit", UI::quit);
}
public void createCombinations(ArrayList<String> list, String s, int depth) {
if (depth == 0) {
return;
}
depth --;
for (int i = 0; i < list.size(); i++) {
if (this.constrain(s + "_" + list.get(i), list.size())) {
UI.println(s + "_" + list.get(i));
}
createCombinations(list, s + "_" + list.get(i), depth);
}
}
public void testCreate() {
ArrayList<String> n = new ArrayList<String>();
n.add("A"); n.add("B"); n.add("C"); n.add("D");
this.createCombinations(n , "", n.size());
}
public boolean constrain(String s, int size) {
// Constrain to only the maximum length
if ((s.length() != size*2)) {
return false;
}
// Constrain to only combinations without repeats
Scanner scan = new Scanner(s).useDelimiter("_");
ArrayList<String> usedTokens = new ArrayList<String>();
String token;
while (scan.hasNext()) {
token = scan.next();
if (usedTokens.contains(token)) {
return false;
} else {
usedTokens.add(token);
}
}
// If we fully iterate over the loop then there are no repitions
return true;
}
public static void main(String[] args){
main obj = new main();
}
This prints out the following which is correct:
_A_B_C_D
_A_B_D_C
_A_C_B_D
_A_C_D_B
_A_D_B_C
_A_D_C_B
_B_A_C_D
_B_A_D_C
_B_C_A_D
_B_C_D_A
_B_D_A_C
_B_D_C_A
_C_A_B_D
_C_A_D_B
_C_B_A_D
_C_B_D_A
_C_D_A_B
_C_D_B_A
_D_A_B_C
_D_A_C_B
_D_B_A_C
_D_B_C_A
_D_C_A_B
_D_C_B_A
This works for small lists but is very inefficient for larger ones. I am aware that what I have done is completely wrong but I want to learn the correct way. Any help is really appreciated. Thanks in advance.
P.S. This is not homework, just for interest although I am a new CS student (if it wasn't obvious).
Implementing Heap's algorithm in Java:
import java.util.Arrays;
public class Main {
public static void swap(final Object[] array, final int index1, final int index2) {
final Object tmp = array[index1];
array[index1] = array[index2];
array[index2] = tmp;
}
public static void printPermutations_HeapsAlgorithm(final int n, final Object[] array) {
final int[] c = new int[n];
for (int i = 0; i < c.length; ++i)
c[i] = 0;
System.out.println(Arrays.toString(array)); //Consume first permutation.
int i=0;
while (i < n) {
if (c[i] < i) {
if ((i & 1) == 0)
swap(array, 0, i);
else
swap(array, c[i], i);
System.out.println(Arrays.toString(array)); //Consume permutation.
++c[i];
i=0;
}
else
c[i++] = 0;
}
}
public static void main(final String[] args) {
printPermutations_HeapsAlgorithm(4, new Character[]{'A', 'B', 'C', 'D'});
}
}
Possible duplicate of this.

recursive method not properly executing

I have a programming assignment for an introductory level Java class (the subset sum problem) - for some reason, my recursive method isn't executing properly (it just goes straight to the end of the method and prints out the sorted list). Any help would be appreciated - I'm a newbie and recursive functions are really confusing to me.
package programmingassignment3;
import java.io.*;
import java.util.*;
public class ProgrammingAssignment3 {
static int TARGET = 10;
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
public static void main(String[] args) {
populateSortSet();
sumInt(list);
recursiveSS(list);
}//main
public static void populateSortSet() {
try {
File f = new File("set0.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !list.contains(ele)) {
list.add(ele);
}//if
}//while
Collections.sort(list);
}//try
catch (IOException e) {
e.printStackTrace();
}//catch
}//populateSet
public static void recursiveSS(ArrayList<Integer> Alist) {
if (Alist.size() == SIZE) {
if (sumInt(Alist) == TARGET) {
System.out.println("The integers that equal " + TARGET + "are: " + Alist);
} //if==TARGET
}//if==SIZE
else {
for (int i = 0; i < SIZE; i++) {
ArrayList<Integer> list1 = new ArrayList<>(Alist);
ArrayList<Integer> list0 = new ArrayList<>(Alist);
list1.add(1);
list0.add(0);
if (sumInt(list0) < TARGET) {
recursiveSS(list0);
}//if
if (sumInt(list1) < TARGET) {
recursiveSS(list1);
}//if
}//for
}//else
System.out.println("echo" + Alist);
}//recursiveSS
public static int sumInt(ArrayList<Integer> Alist) {
int sum = 0;
for (int i = 0; i < SIZE - 1; i++) {
sum += Alist.get(i);
}//for
if (Alist.size() == TARGET) {
sum += Alist.get(Alist.size() - 1);
}//if
return sum;
}//sumInt
}//class
This thing that you do at class level:
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
means that SIZE will be initiated to 0, and stay 0 (even if you add elements to the list.)
This means that the code inside the for-loop will be executed 0 times.
Try something like:
public class ProgrammingAssignment3 {
private static int initialSize;
//...
public static void populateSortSet() {
//populate the list
initialSize = list.size();
}
So you don't set the value of the size variable until the list is actually populated.
That being said, there a quite a few other strange things in your code, so I think you need to specify exactly what you are trying to solve here.
Here's how I'd do it. I hope it clarifies the stopping condition and the recursion. As you can see, static methods are not an issue:
import java.util.ArrayList;
import java.util.List;
/**
* Demo of recursion
* User: mduffy
* Date: 10/3/2014
* Time: 10:56 AM
* #link http://stackoverflow.com/questions/26179574/recursive-method-not-properly-executing?noredirect=1#comment41047653_26179574
*/
public class RecursionDemo {
public static void main(String[] args) {
List<Integer> values = new ArrayList<Integer>();
for (String arg : args) {
values.add(Integer.valueOf(arg));
}
System.out.println(String.format("input values : %s", values));
System.out.println(String.format("iterative sum: %d", getSumUsingIteration(values)));
System.out.println(String.format("recursive sum: %d", getSumUsingRecursion(values)));
}
public static int getSumUsingIteration(List<Integer> values) {
int sum = 0;
if (values != null) {
for (int value : values) {
sum += value;
}
}
return sum;
}
public static int getSumUsingRecursion(List<Integer> values) {
if ((values == null) || (values.size() == 0)) {
return 0;
} else {
if (values.size() == 1) { // This is the stopping condition
return values.get(0);
} else {
return values.get(0) + getSumUsingRecursion(values.subList(1, values.size())); // Here is recursion
}
}
}
}
Here is the case I used to test it:
input values : [1, 2, 3, 4, 5, 6]
iterative sum: 21
recursive sum: 21
Process finished with exit code 0
Thanks everyone. I really appreciate the help. I did figure out the problem and the solution is as follows (closing brace comments removed for the reading pleasure of #duffymo ):
public class ProgrammingAssignment3 {
static int TARGET = 6233;
static ArrayList<Integer> set = new ArrayList<>();
static int SIZE;
static int count = 0;
public static void populateSortSet() {
try {
File f = new File("set3.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !set.contains(ele)) {
set.add(ele);
}
}
Collections.sort(set);
SIZE = set.size();
System.out.println("The original sorted set: " + set + "\t subset sum = " + TARGET);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void recursiveSS(ArrayList<Integer> list) {
if (list.size() == SIZE) {
if (sumInt(list) == TARGET) {
System.out.print("The Bit subset is: " + list + "\t");
System.out.println("The subset is: " + getSubset(list));
count++;
}
}
else {
ArrayList<Integer> list1 = new ArrayList<>(list);//instantiate list1
ArrayList<Integer> list0 = new ArrayList<>(list);//instantiate list0
list1.add(1);
list0.add(0);
if (sumInt(list0) <= TARGET) {
recursiveSS(list0);
}
if (sumInt(list1) <= TARGET) {
recursiveSS(list1);
}
}
}
public static int sumInt(ArrayList<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
sum += set.get(i);
}
}
return sum;
}
public static ArrayList<Integer> getSubset(ArrayList<Integer> list) {
ArrayList<Integer> l = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
l.add(set.get(i));
}
}
return l;
}
}

Issues with adding a random numbers to an array

I am trying to add random numbers to an empty array 20 numbers 0-99. When I run the code below it prints out 51 numbers and they are all 0.
Can someone please help me figure out what I am doing wrong here.
import java.util.Random;
public class SortedArray
{
int randomValues;
int[] value;
public SortedArray()
{
}
public int getRandom()
{
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues = random.nextInt(100);
}
return randomValues;
}
public int getArray()
{
int result = 0;
value = new int[randomValues];
for(int item : value)
{
System.out.println("The array contains " + item);
}
return result;
}
}
Here is my main method
public class ReturnSortedArray
{
public static void main(String[] args)
{
SortedArray newArray = new SortedArray();
int random = newArray.getRandom();
int array = newArray.getArray();
System.out.println(array);
}
}
In your method getArray
the code
value = new int[randomValues];
is simply creating a new empty int array of size ramdomValues.
As the default value of an int is 0, that is what you are getting
Also in your method getRandom you are setting the same value time and time again
for (...)
randomValues = random.nextInt(100);
try
public int[] getRandomArr()
{
int randomValues [] = new int [20];
Random random = new Random();
for(int j=0; j<20; j++)
{
randomValues[j] = random.nextInt(100);
}
return randomValues;
}
I see a few issues, you should probably set the values in your constructor. You could also call it a set method (since it's not actually a get). Also, your getArray() doesn't return an array. So, I think you really wanted something like this,
public class SortedArray {
private Random random = new Random();
private int[] value = new int[20];
public SortedArray() {
super();
setRandomValues();
}
public void setRandomValues() {
for (int j = 0; j < value.length; j++) {
value[j] = random.nextInt(100);
}
}
public int[] getArray() {
return value;
}
}
And then your main method, should be updated like
public static void main(String[] args) {
SortedArray newArray = new SortedArray();
int[] array = newArray.getArray();
System.out.println(Arrays.toString(array));
}

Sort array based on count of occurrences in ascending order

How can I arrange the elements in an array based on the number of occurrences of that value in ascending order in java.
This is what I've tried:
int a[]={0,0,0,1,3,3,2,1,3,5,6,0};
int b=a.length;
for(int i=0;i<b;i++) {
for(int j=0;j<i;j++) {
int temp;
if( a[j]>a[i]) {
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int r=0;r<a.length;r++) {
System.out.println(a[r]);
}
Here is an efficient way to do it using TreeMap.
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class FrequencySort {
public static void main(String[] args) {
int[] ar = new int[] {5,2,8,8,5,5,8,1,9,0,1,1,0,1};
Map<Integer,Integer> numbers = new HashMap<>();
for(int number : ar) {
if(numbers.containsKey(number)) {
Integer count = numbers.get(number);
numbers.put(number, ++count);
} else {
numbers.put(number,1);
}
}
final class FrequencyComparator implements Comparator<Integer> {
Map<Integer,Integer> refMap;
public FrequencyComparator(Map<Integer,Integer> base) {
this.refMap = base;
}
#Override
public int compare(Integer k1, Integer k2) {
Integer val1 = refMap.get(k1);
Integer val2 = refMap.get(k2);
int num = val1.compareTo(val2) ;
// if frequencies are same then compare number itself
return num == 0 ? k1.compareTo(k2) : num;
}
}
FrequencyComparator comp = new FrequencyComparator(numbers);
TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(comp);
sortedMap.putAll(numbers);
for(Integer i : sortedMap.keySet()) {
int frequencey = sortedMap.get(i);
for(int count = 1 ; count <= frequencey ; count++) {
System.out.print(i + " " );
}
}
}
}
Here's one approach to start you off could be based on the idea of keeping a count of how many times each integer in the initial array has occurred in a map. Once all the numbers have been counted, sort the map by order of ascending value, and then print the output of the map:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;
public class SortCount {
public static void main(String[] args) {
int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
HashMap<Integer,Integer> counts = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++) {
if(counts.containsKey(nums[
Integer c = counts.get(nums[i]) + 1;
counts.put(nums[i], c);
}
else {
counts.put(nums[i],1);
}
}
ValueComparator<Integer,Integer> bvc = new ValueComparator<Integer,Integer>(counts);
TreeMap<Integer,Integer> sortedMap = new TreeMap<Integer,Integer>(bvc);
sortedMap.putAll(counts);
ArrayList<Integer> output = new ArrayList<Integer>();
for(Integer i : sortedMap.keySet()) {
for(int c = 0; c < sortedMap.get(i); c++) {
output.add(i);
}
}
System.out.println(output.toString());
}
}
Which uses a Comparator class to compare the values in a Map:
import java.util.Comparator;
import java.util.Map;
public class ValueComparator<T1,T2 extends Comparable<T2>> implements Comparator<T1> {
Map<T1,T2> base;
public ValueComparator(Map<T1,T2> base) {
this.base = base;
}
#Override
public int compare(T1 k1, T1 k2) {
T2 val1 = base.get(k1);
T2 val2 = base.get(k2);
return val1.compareTo(val2);
}
}
If you just want to sort the array, use the following:
Arrays.sort(a);
If you want to sort it manually, I would recommend reading this page, where you can find pseudo-code for a variety of sorting algorithms.
However, if you are searching for a way to sort the array based on number frequency, I would recommend this page. You would have to inverse the sorting order, sonce you want them in ascending order.
Using TreeMap to store the element as key,count of occurrences as value and then sorting it based on values. Java 8 streams make below code concise and simple to understand
int[] a = {1,1,2,2,3,3,3,4,4,5,5,5,5,6,6,6,8};
// new element ? store its count as 1 , else increment its count
TreeMap<Integer,Integer> m1 = new TreeMap<>();
for(int i : a)
{
if(m1.containsKey(i))
{m1.put(i,m1.get(i)+1);}
else {m1.put(i,1);}
};
// sort and then if element i occurs n times, simply loop to add so in arraylist
ArrayList<Integer> b = new ArrayList<>();
m1.entrySet().stream()
.sorted((k1, k2) -> -k1.getValue().compareTo(k2.getValue())).forEach(e -> {
for(int i=0;i<e.getValue();i++)
b.add(e.getKey());
});
Arrays.stream(a).forEach(i -> System.out.print(i+ " "));
System.out.println();
b.stream().forEach(i -> System.out.print(i+ " "));
}
Using Java 8
Sort the array elements based on its frequencies
Assumptions -
1. Sort the array based on its natural occurrence in an ascending order
2. If two numbers having same frequencies then sort them based on natural number precedence
Example: - [ 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5]
Output: - [ 5, 4, 4, 2, 2, 2, 3, 3, 3, 1, 1, 1, 1, 1]
Solution: -
1. Create a HashMap which stores the array elements and its occurrences
2. Put hashmap into a List where we can apply sorting based on its frequencies using a customized comparator
3. Object Comparision is Java: -
  if Obj1 is less then Obj2 then return -1
  if Obj1 is equal to Obj2 then return 0
  if Obj1 is greater then Obj2 then return +1
4. In our case, if two numbers have the same frequences then we should put the number which has natural precedence in the output
  Ex: - if above example, number 2 and 3 occurred 3 times hence 2 should come first
public static void sortTheArrayByFrequency(int[] array){
Map<Integer, Integer> map = new HashMap<>();
//put array elements based on its frequncies
for(int i : array){
map.put(i, map.getOrDefault(i,0)+1);
}
//Put the hashmap into a list where we use customized comparator
List<Map.Entry<Integer, Integer>> list = new ArrayList<>();
for(Map.Entry<Integer, Integer> e : map.entrySet()){
list.add(e);
}
// list looks like [1=5, 2=3, 3=3, 4=2, 5=1]
Collections.sort(list, (a, b) -> {
// if its ouccrances are same then sort natually
//else sort based on freqncies
if(a.getValue() == b.getValue())
return a.getKey() - b.getKey();
else
return a.getValue() - b.getValue();
});
// list looks like [5=1, 4=2, 2=3, 3=3, 1=5]
for(Map.Entry<Integer, Integer> e : list){
int num = e.getValue();
while(num!=0){
System.out.print(e.getKey()+ " ");
num--;
}
}
}
Output:-
5 4 4 2 2 2 3 3 3 1 1 1 1 1
What about Arrays.sort(int[])? From its JavaDoc:
Sorts the specified array into ascending numerical order.
public static void main(String[] args) {
int unsortedArray[] = {0,0,0,1,3,3,2,1,3,5,6,0};
System.out.println("After sorting, the list elements are: "); //Just to show you it worked. :)
bubbleSoprt(unsortedArray,unsortedArray.length);
for(int i =0;i<unsortedArray.length;i++){
System.out.print( unsortedArray[i] + " ");
}
}
private static void bubbleSoprt(int []unsortedarray,int lenght){
int temp;
for(int counter= 0 ;counter<lenght-1;counter++){
for(int index = 0;index<lenght-1-counter;index++){
if(unsortedarray[index] > unsortedarray[index+1]){
temp = unsortedarray[index];
unsortedarray[index] = unsortedarray[index+1];
unsortedarray[index+1] = temp;
}
}
}
}
Easy and optimized.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Frequency {
public static void main(String[] args) {
int array[] = {5,2,8,8,5,5,8,1,1,2};
HashMap<Integer, Integer> data = new HashMap<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
if (data.containsKey(array[i])) {
Integer count = data.get(array[i]) + 1;
data.put(array[i], count);
} else {
data.put(array[i], 1);
}
}
Set<Entry<Integer, Integer>> set = data.entrySet();
ArrayList<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
for (Entry<Integer, Integer> entry : list) {
System.out.println(entry.getKey() + " <-> " + entry.getValue());
}
}
}
import java.io.*;
import java.lang.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
class SortingFrequency
{
public static void main(String args[]) throws Exception{
int i,j,temp,temp1,count;
int []a=new int[10];
int []freq=new int[10];
Scanner s=new Scanner(System.in);
for(i=0;i<5;i++){
a[i]=s.nextInt();
freq[i]=-1;
}
for(i=0;i<5;i++)
{
count=1;
for(j=i+1;j<5;j++)
{
if(a[i]==a[j])
{
count++;
freq[j]=0;
}
}
if(freq[i]!=0)
{
freq[i]=count;
}
}
Map map=new HashMap();
for(i=0;i<5;i++){
if(freq[i]!=0){
map.put(a[i],freq[i]);
System.out.println("map elt"+map);
System.out.println("a"+a[i]+"fr"+freq[i]);
}
}
Set<Entry<Integer,Integer>> set=map.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<Integer, Integer>>()
{
public int compare( Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
});
for(Map.Entry<Integer, Integer> entry:list){
System.out.println(entry.getKey()+" ==== "+entry.getValue());
}
}
}
The below program is bit lengthy but simple to understand. Hope this is what you were expecting.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.TreeMap;
public class Test {
public static void main(String[] args) {
int[] arra = {-2,-2,-2,-1,-1,-1,2,2,1,3,1,9,9,1,1,9,9};
for(int i:sortedArrary(arra)){
System.out.print(i+" ");
}
}
static int[] sortedArrary(int[] inputArray)
{
TreeMap<Integer,Integer> repetitiveElements = null;
if(inputArray==null || inputArray.length<=0)
return null;
repetitiveElements = new TreeMap<Integer,Integer>();
for(int i=0;i<inputArray.length;i++)
{
if(repetitiveElements.containsKey(inputArray[i]))
{
repetitiveElements.put(inputArray[i], repetitiveElements.get(inputArray[i])+1);
}else{
repetitiveElements.put(inputArray[i],1);
}
}
//System.out.println("repetitive "+repetitiveElements);
ArrayList<Integer> keysArray = new ArrayList<Integer>(repetitiveElements.size());
ArrayList<Integer> valuesArray = new ArrayList<Integer>(repetitiveElements.size());
int key;
Iterator<Integer> itr = repetitiveElements.keySet().iterator();
while(itr.hasNext())
{
key = itr.next();
keysArray.add(key);
valuesArray.add(repetitiveElements.get(key));
}
/*
System.out.println("keys "+keysArray);
System.out.println("values "+valuesArray);
*/
LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
int maxValue=-1;
int maxKey = -1;
int pos = -1;
for(int i=0;i<repetitiveElements.size();i++)
{
if(keysArray.get(i)==null)
continue;
maxKey = keysArray.get(i);
maxValue = valuesArray.get(i);
pos=i;
for(int j=0;j<repetitiveElements.size();j++)
{
if(valuesArray.get(j)!=null && maxValue>valuesArray.get(j))
{
maxValue = valuesArray.get(j);
maxKey = keysArray.get(j);
pos = j;
}else if(valuesArray.get(j)!=null && maxValue==valuesArray.get(j)){
if(keysArray.get(j)!=null && maxKey>keysArray.get(j))
{
maxKey = keysArray.get(j);
pos = j;
}
}
}
map.put(maxKey, maxValue);
valuesArray.set(pos, null);
keysArray.set(pos, null);
}
for(int i=0;i<keysArray.size();i++)
{
if(keysArray.get(i)!=null)
{
map.put(keysArray.get(i), valuesArray.get(i));
}
}
itr = map.keySet().iterator();
int count=0,value;
while(itr.hasNext())
{
key = itr.next();
value = map.get(key);
for(int i=0;i<value;i++)
{
inputArray[count++] = key;
}
}
return inputArray;
}
}
package problems;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SortByFrequency {
public static void main(String args[]) {
int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int len = arr.length;
for (int j = 0; j < len; j++) {
if (map.get(arr[j]) == null) {
map.put(arr[j], 1);
} else {
map.put(arr[j], (Integer) map.get(arr[j]) + 1);
}
}
Set<Entry<Integer, Integer>> set = map.entrySet();
ArrayList<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
list.sort(new Comparator<Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
if (o1.getValue() < o2.getValue()) {
return 1;
} else if (o1.getValue() > o2.getValue()) {
return -1;
} else if (o1.getValue() == o2.getValue()) {
if (o1.getKey() < o2.getKey()) {
return 1;
} else {
return -1;
}
}
return 0;
}
});
for (Map.Entry<Integer, Integer> en : list) {
int val = en.getValue();
while(val!=0){
System.out.println(en.getKey());
val--;
}
}
}
}
public class SortBasedOnFrequency {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] arr = new String[] { "abc", "def", "qas", "abc", "abc", "def" };
new SortBasedOnFrequency().sort(arr);
}
void sort(String[] a) {
Map<String, Integer> map = new HashMap<>();
for (String s : a) {
//convert array to map putting key as the array element and value as the
//number of occurence.
map.put(s, map.get(s) == null ? 1 : map.get(s) + 1);
}
List<Map.Entry<String, Integer>> mapEntryList = new ArrayList<>map.entrySet());// sort mapEntry list based on value
Collections.sort(mapEntryList, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return o1.getValue().compareTo(o2.getValue());
}
});
//print the object in sorting order of the occurrence.
for (Entry<String, Integer> m : mapEntryList) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
I didn't like the answers above, so I'm adding what I did. The general idea is pretty simple - just sort the list by Comparator that will take as an argument the hash map.
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] ar = new int[] {0,0,0,1,3,3,2,1,3,5,6,0};
Map<Integer,Integer> map = new HashMap<>();
List<Integer> output = new ArrayList<>();
for(int current : ar) {
int count = map.getOrDefault(current, 0);
map.put(current, count + 1);
output.add(current);
}
FrequencyComparator comp = new FrequencyComparator(map);
Collections.sort(output, comp);
for(Integer i : output){
System.out.print(i + " ");
}
}
}
And the FrequencyComparator:
import java.util.Comparator;
import java.util.Map;
public class FrequencyComparator implements Comparator<Integer> {
private final Map<Integer,Integer> freqMap;
FrequencyComparator(Map<Integer,Integer> i_freqMap) { this.freqMap = i_freqMap; }
#Override
public int compare(Integer k1, Integer k2) {
int freqCompare = freqMap.get(k1).compareTo(freqMap.get(k2));
int valueCompare = k1.compareTo(k2);
// If frequency is equal, then just compare by value, otherwise - compare by the frequency.
if(freqCompare == 0)
return valueCompare;
else
return freqCompare;
}
}
output:
2 5 6 1 1 3 3 3 0 0 0 0
Simply Using Arrays.
import java.util.*;
public class SortAccordingToFrequency {
public static void main(String[] args) {
int r;
int b[]={1,1,1,2,1,2,3,6,6,5};int i;int n=b.length;int k=0;
Arrays.sort(b);
int[] a=new int[n+1];
for(r=0;r<n;r++){
a[r]=b[r];}
a[r]=1882737378; //Any arbitrary value.
int c=1;int in[]=new int[10];
int[] e=new int[10];
for(i=0;i<n;i++){
if(a[i]==a[i+1])
c++;
else{
e[k]=a[i];
in[k]=c;k++;
c=1;
}
}
for (int f = 0; f < k; f++) {
for (int g = 0; g < k-f-1; g++) {
if (in[g] > in[g+1]){
int[] ans = swap(in[g], in[g+1]);
in[g]=ans[0];
in[g+1]=ans[1];
int[] an = swap(e[g], e[g+1]);
e[g]=an[0];
e[g+1]=an[1];
}
}
}
int d=0;
for(int x=0;x<k;x++){
for(int y=0;y<in[x];y++){
System.out.print(e[d]);
}d++;
}
}
static int[] swap(int n1,int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
int ans[]=new int[2];
ans[0]=n1;
ans[1]=n2;
return ans;
}
}
public class Frequency {
static int key;
public static void main(String[] args) {
Integer[] nums = { 7, 3, 4, 3, 4, 3, 4, 3, 6, 5, 7 };
Map<Integer, Integer> m1;
//Convert the integer array into an Array List.
ArrayList<Integer> numbers = new ArrayList<Integer>(Arrays.asList(nums));
//ArrayList to store the number of occurences of numbers.
List<Integer> values = new ArrayList<Integer>();
//ArrayList to show the array in requested order.
List<Integer> output = new ArrayList<Integer>();
m1 = new LinkedHashMap<Integer, Integer>();
for (int a : numbers) {
//Add data in Hash map where key is number and value is the total occurences of that number.
if (m1.containsKey(a)) {
int value = m1.get(a);
m1.put(a, ++value);
} else {
m1.put(a, 1);
}
}
System.out.println(m1);
for (Map.Entry<Integer, Integer> entry : m1.entrySet()) {
values.add(entry.getValue());
}
Collections.sort(values, Collections.reverseOrder());
System.out.println(values.toString());
for (int m = 0; m < values.size(); m++) {
for (Map.Entry<Integer, Integer> entry : m1.entrySet()) {
if (entry.getValue().equals(values.get(m))) {
key = entry.getKey();
System.out.println("Key is" + key);
for (int k = values.get(m); k > 0; k--) {
output.add(key);
}
break;
}
}
m1.remove(key);
}
System.out.println(output.toString());
}
}
I am a newbie to coding, I tried this by using "for loop". Here is my code -
//Driver Program
public static void main(String args[])
{
int[] array = { 2, 2, 3, 4, 5, 12, 2, 3, 3, 3, 12 };
sortByCount(array);
}
//Array element's count
static int elementsCount(int ar[], int n)
{
int count = 0;
for(int i : ar)
{
int max = n;
if(i == max)
{
count++;
}
max = i;
}
return count;
}
//Ascending order sort by count
static void sortByCount(int ar[])
{
int temp = 0;
for(int i = 0; i < ar.length; i++)
{
for(int j = i + 1; j < ar.length; j++)
{
if(elementsCount(ar, ar[i]) > elementsCount(ar, ar[j]))
{
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
printArray(ar);
}
//Print Array
static void printArray(int[] ar)
{
for(int i : ar)
{
System.out.println(i);
}
}
Using Map,ArrayList and Comparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class OrderArrayFrequency {
public static void main(String[] args) {
int nums[] = {0,0,0,1,3,3,2,1,3,5,6,0};
ConcurrentHashMap<Integer, Integer> counts = new ConcurrentHashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (counts.containsKey(nums[i])) {
Integer c = counts.get(nums[i]) + 1;
counts.put(nums[i], c);
} else {
counts.put(nums[i], 1);
}
}
ArrayList<Integer> list = new ArrayList<>();
for (Integer i : counts.keySet()) {
list.add(counts.get(i));
}
Collections.sort(list, new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
if (o1 < o2)
return -1;
return 0;
}
});
Set<Entry<Integer, Integer>> set = counts.entrySet();
for (Integer i : list) {
for (Entry<Integer, Integer> entry : set) {
if (entry.getValue().equals(i)) {
System.out.print(entry.getKey()+":"+entry.getValue()+ " ");
counts.remove(entry.getKey());
}
}
}
}
}
Output : 2:1 5:1 6:1 1:2 3:3 0:4
import java.util.*;
class SortArrayByFrequency
{
public static void main(String[] args)
{
int a[]={2,2,2,2,4,4,4,4,4,4,5,6,6,6,6,6,1,1,1};
int count=0;
int k[]=new int[10];// for elements
int v[]=new int[10];//store the frquency of corresponding element
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<a.length;i++)
{
if(map.containsKey(a[i]))
{
map.put(a[i],map.get(a[i])+1);
}
else
{
map.put(a[i],1);
}
}
Set<Integer> keys=map.keySet();
int i=0,j=0;
for(int key:keys){
//System.out.println(key+" : "+map.get(key));
v[i++]=map.get(key);
k[j++]=key;
}
System.out.println("--------------------");
//Sort the array which contains the frquency of elements
for(int f=0;f<i-1;f++){
//System.out.println(k[f]+" "+v[f]);
int min=f;
for(int g=f+1;g<i;g++)
{
if(v[min]>v[g])
{
min=g;
}
}
int temp=v[min];
v[min]=v[f];
v[f]=temp;
//here we swap the element according to sorting ------------
int temp1=k[min];
k[min]=k[f];
k[f]=temp1;
}
System.out.println("-----Array sort by frequency in ascending order------------");
for(int l=0;l<i;l++){
//System.out.println(v[l]+" :: "+k[l]);
for(int p=0;p<v[l];p++)
System.out.print(k[l]+" ");
}
}
}
Ascending order
//OUTPUT: 5 1 1 1 2 2 2 2 6 6 6 6 6 4 4 4 4 4 4
Already it has been answered but there's no good explanation of the code.So I will try that here.
Let the array to be sorted be : int[] array = {4,4,2,2,2,2,3,3,1,1,6,7,5}
First of all let us count the frequency of each number:
To do so we will create a HashMap data-structure which will have the array elements as Key and their frequency as value.And to store our output we will have a output list.
HashMap<Integer,Integer> freqMap = new HashMap<>();
ArrayList<Integer> output = new ArrayList<>();
getOrDefault(key,defaultValue) : This is a convenient way to handle the scenario where we want a returned value other than null which is being returned by get method whenever the key was not found.
Coming to the code:
for(int current : array)
{
int count = freqMap.getOrDefault(current,0); // if arrayelement is encountered first time it returns 0 otherwise it returns the actual count
freqMap.put(current,count++); // we increase the count by one and put it in the map
output.add(current); // we also add the element in the list.
}
Now we have out elements mapped with their frequency in HashMap.
- 2 comes four times
- 3 comes two times
- 4 comes two times
- 5,6 and 7 comes one time.
Now we need to sort the output list according to the frequency. For that we implement the comparator interface. In this interface we have a method
public int compare(Object obj1, Object obj2) //It compares the first object with the second object.
So we create a class SortComparator to implement this interface and create an object comp of class SortComparator.
SortComparator comp = new SortComparator(freqMap);
Collections.sort(output,comp);
for(Integer i : output)
{
System.out.print(i + " ");
}
This is the implementation of the Comparator interface:
class SortComparator implements Comparator<Integer>
{
private final Map<Integer,Integer> freqMap;
SortComparator(Map<Integer,Integer>freqMap)
{
this.freqMap = freqMap;
}
public int compare(Integer k1,Integer k2)
{
//Comparing by frequency
int freqCompare = freqMap.get(k2).compareTo(freqMap.get(k1));
//Comparing by value
int valueCompare = k2.compareTo(k1);
if(freqCompare == 0)//frequency of both k1 and k2 is same then
{
return valueCompare;
}
else
{
return freqCompare;
}
}
// sorting of an array in decreasing order on the basis of their frequencies.
import java.util.*;
class sorting {
static int x = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0; i<n; i++){
a[i] = sc.nextInt();
}
Arrays.sort(a);
// l is number of distinct elements in array a.
int l=1;
for(int i=0; i<n-1; i++){
if(a[i]!=a[i+1]){
l++;
}
}
// creating a 2d array from a 1d array having elements and their frequencies.
int b[][] = new int[l][2];
b[x][0] = a[0];
int c=1;
for(int i=1; i<n; i++){
if(a[i]!=a[i-1]){
b[x][1]=c;
x++;
c=1;
b[x][0] = a[i];
}
else{
c++;
}
if(i==n-1){
b[x][1]=c;
}
}
// sorting 2d array according their frequencies.
for(int i=0; i<b.length; i++){
for(int j=i; j<b.length; j++){
if(b[i][1]<b[j][1]){
int t = b[i][1];
b[i][1] = b[j][1];
b[j][1] = t;
t = b[i][0];
b[i][0] = b[j][0];
b[j][0] = t;
}
}
}
for(int i=0; i<b.length; i++){
int k=b[i][1];
for(int j=0; j<k; j++){
System.out.print(b[i][0]+" ");
}
}
}
// bubble sort.
public static void sort(int a[]) {
int n = a.length;
for(int i=0; i<n; i++){
for(int j=i; j<n; j++){
if(a[i]>a[j]){
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
}
Since Java 8 you can achieve this with a one-liner (split into several lines for better readability ;-)
int[] numbers = {0, 0, 0, 1, 3, 3, 2, 1, 3, 5, 6, 0};
List<Integer> result = IntStream.of(numbers)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(e -> Stream.generate(e::getKey).limit(e.getValue()))
.flatMap(Function.identity())
.collect(Collectors.toList());
or, if you prefer an array as a result
int[] result = IntStream.of(numbers)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(e -> Stream.generate(e::getKey).limit(e.getValue()))
.flatMap(Function.identity())
.mapToInt(Integer::intValue)
.toArray();
Answer in python:
n=input()
arr=[int(i) for i in n.split(' ')]
dict={}
for i in arr:
if(i in dict.keys()):
dict[i]+=1
else:
dict[i]=1
ans=[]
while len(ans)<=len(arr) and dict!={}:
maxval=min(list(dict.values()))
keys=[]
for key in dict.keys():
if(dict[key]==maxval):
keys+=[key]
keys=sorted(keys)
for i in keys:
ans+=[i]*dict[i]
del dict[i]
print(ans)
import java.util.Arrays;
import java.util.Comparator;
public class TestString {
public static void main(String[] args) {
int arrTemp[] = { 2, 2, 2, 1, 1, 4, 5, 6, 6, 7, 7, 7, 7 };
Arrays.sort(arrTemp);
Integer[][] sortedArray = new Integer[6][2];
int count = 0;
sortedArray[count][0] = arrTemp[0];
sortedArray[count][1] = 1;
for (int i = 0; i < arrTemp.length - 1; i++) {
for (int j = 1; j < arrTemp.length; j++) {
if (arrTemp[i] == arrTemp[j]) {
sortedArray[count][1] = sortedArray[count][1] + 1;
i = j;
} else {
++count;
sortedArray[count][0] = arrTemp[j];
sortedArray[count][1] = 1;
i = j;
}
}
}
Arrays.sort(sortedArray, new Comparator<Integer[]>() {
#Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[1].compareTo(o2[1]);
}
});
for (int row = 0; row < 6; row++) {
for (int col = 0; col < sortedArray[row][1]; col++) {
System.out.print(sortedArray[row][0] + " ");
}
}
}
}
Sort array based on frequency:
public static void main(String[] args) {
int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
Map<Integer, Integer> mp = new LinkedHashMap<>();
List<Integer> res = new ArrayList<>();
int count = 1;
for (int i = 0; i < arr.length; i++) {
if (!mp.containsKey(arr[i])) {
mp.put(arr[i], count);
} else {
mp.put(arr[i], mp.get(arr[i]) + 1);
}
}
if (!mp.containsValue(2)) {
for (Integer ab : arr)
res.add(ab);
Collections.sort(res);
Collections.reverse(res);
System.out.println(res);
} else {
Set<Entry<Integer, Integer>> set = mp.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<>(set);
Collections.sort(list, new Comparator<Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> obj1, Entry<Integer, Integer> obj2) {
if (obj2.getValue() > obj1.getValue())
return 1;
if (obj2.getValue() < obj1.getValue())
return -1;
else
return 0;
}
});
for (Map.Entry<Integer, Integer> e : list) {
for (int i = 1; i <= e.getValue(); i++)
res.add(e.getKey());
}
System.out.println(res);
}
}

Categories