-1
import java.util.Scanner;

public class abc {
    public static void main(String[] args) {
        char[] ch = str.toCharArray();
        int len = ch.length;

        for (int i = 0; i < len; i++) {
            int counte = 0;
            char c = str.charAt(i);

            for (int j = 0; j < len; j++) {
                if (c == ch[j]) {
                    counte++;
                    ch[j] = '\u0000';
                }
            }

            if (counte > 0) System.out.print(c + "-" + counte + ",");
        }
    }
}

Input:

BBBBBbbbbbbCCooooPPPu

Output:

5-B,6-b,2-C,4-o,3-P,1-u

But I want the output to be:

6-b,5-B,4-o,3-P,2-C,1-u

How can I solve this?

Ivar
  • 6,138
  • 12
  • 49
  • 61
gorgorj
  • 11
  • 4

4 Answers4

0

Check this example code using classes found in java.util

import java.util.*;
import java.text.*;

public class abc {
    public static void main(String[] args) {
        //String as parameter. Should be args[0]; or something?
        String str = "BBBBBbbbbbbCCooooPPPu"; 
        //Format with leading zeros to allow sorting up to 999
        NumberFormat nf = new DecimalFormat("000");

        //Create reverse-sorted set to hold counts
        Set<String> sorted = new TreeSet<String>(Collections.reverseOrder() );
        [...] //Do your thing as before...
            if (counte > 0) {
                //Add to Set (ordered...) using number format
                sorted.add(nf.format(counte) + "-" + c);
            }
        }
        //Join together set to create output String
        StringJoiner sj = new StringJoiner(",");
        for(String s : sorted) {
            //Trim away leading zeros
            sj.add(s.replaceAll("\\G0", ""));
        }
        //Output
        System.out.println(sj.toString());
    }
}
Jan
  • 13,738
  • 3
  • 30
  • 55
  • in what manner? The example I gave will already sort descending by byte-count. Where else do you need improvement? (Any you could motivate my by accepting answer first ;-)) It might be helpful to see full code - yours doesn't even compile as str is undefined. – Jan Nov 25 '15 at 13:18
  • you will have problems after 9, then you must format numbers. – guillaume girod-vitouchkina Nov 25 '15 at 13:20
0

Don't print the values 5-B, 6-b etc.. but store their value in an array and the number of occurrences would be the key :

result[5] = '5-B';
result[6] = '6-b';
// etc...

and finally just inverse this array with some sorting function.

teeyo
  • 3,665
  • 3
  • 22
  • 37
0

You need to sort.

The following code do this, never minds if letters are consecutives or not.

public static void see_string () 
{
    List<Pair<Integer,String>> lp=new ArrayList<Pair<Integer,String>>();
    Map<String, Integer> mci=new HashMap<String, Integer>();

    // Populate
    String str="mylongstringtoscanandsomore";
    str="BBBBBbbbbbbCCooooPPPu";

    int size=str.length();

    for (int pos=0;pos<size;pos++)
        {
        String ch=str.substring(pos,pos+1);
        int val=0;
        if (mci.containsKey(ch)) {val=mci.get(ch);}
        val++;
        mci.put(ch, val);
        }

    // map => list
    for (Map.Entry<String, Integer> e : mci.entrySet())
        lp.add(new Pair<Integer,String>(e.getValue(),e.getKey()));

    // SORT
    reverse_sort(lp);

    size=lp.size();

    // See
    for (int pos=0;pos<size;pos++)
        {
        System.out.println(lp.get(pos).getLeft()+"=>"+lp.get(pos).getRight());
        }

}

// http://stackoverflow.com/questions/521171/a-java-collection-of-value-pairs-tuples

public class Pair<L,R> implements java.io.Serializable  {

      private final L left;
      private final R right;

      public Pair(L left, R right) {
        this.left = left;
        this.right = right;
      }

      public L getLeft() { return left; }
      public R getRight() { return right; }

      @Override
      public int hashCode() { return left.hashCode() ^ right.hashCode(); }

      @Override
      public boolean equals(Object o) {
        if (o == null) return false;
        if (!(o instanceof Pair)) return false;
        Pair pairo = (Pair) o;
        return this.left.equals(pairo.getLeft()) &&
               this.right.equals(pairo.getRight());
      }

    }


// T key to sort
static public <T extends Comparable<T>, Object,K extends Object> 
void reverse_sort(List<Pair<T,K>> _list)
{

    class ComparaterTK <T extends Comparable<T>,K> implements Comparator<Pair<T,K>>
    {
      public int compare(Pair<T,K> ob1, Pair<T,K> ob2)
        {
          return ob2.getLeft().compareTo(ob1.getLeft());
      }
    }

    // simple sort
    Collections.sort(_list, new ComparaterTK<T,K>());
}
  • that is best the code, but i think that have a simple code to do it . – gorgorj Nov 25 '15 at 13:23
  • My code could certainly be improved, but I prefer clarity. 1 You have to count. A simple loop can do it. 2 You must sort by quantities. Or you can use the trick of prepending quantity before char. Beware of prepending also the 0. – guillaume girod-vitouchkina Nov 25 '15 at 15:16
0

This is the easiest way of reaching your requirement using lambdas.

 String string = "BBBBBbbbbbbCCooooPPPu";
 Stream.of(string.split(""))
            .collect(Collectors.groupingBy(s -> s, Collectors.counting()))
            .entrySet().stream().
            sorted((Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) -> o2.getValue().compareTo(o1.getValue())).
            forEachOrdered(e -> System.out.print(e.getValue() + " - " + e.getKey()+", "));
Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Madushan Perera
  • 2,568
  • 2
  • 17
  • 36