How to swap using different data types


Keywords:java 


Question: 

Ok so lets suppose I have an array of 4 ints ==

int[] input = new int[]{1,2,3,4};

//now I some how converted these numbers into words and gets an array:-
String Str = new String[]{one,two,three,four};
//then I run a sort method on Str.
Arrays.sort(Str);
//and I got this array in the end  ::: {four,one,three,two}

Now i want to reconvert it into numbers(int) so that my final result should look like this:- {4,1,3,2}

In Summery :- I want to sort the input int arrays through its English(words)representation

Examples :-

[input]      [convert to words]         [sorting]             [Result]

{1,2,3,4} => {one,two,three,four} =>{four,one,three,two} => 4,1,3,2

{55,23,3,45} =>{fifty five, twenty three, three, fourty five} => {fifty five, fourty five, three, twenty three} => {55,45,3,23}

so, uptill now I manage to convert the inputs into words and sort it but I dont know how to convert the Str array back to its original int array as showen in the examples above...

THE REAL QUESTION :- I know i can convert it using loops and array..but i wanna know is it possible to do it using array swapping??[maybe through its indexes??]

P.s:- Sorry for any in convenience I may cause to you. and thanks in advance


3 Answers: 

you can do the following..

  1. instead of storing separately you can create a class and store that.

    public class Numbers {
    String word;
    Integer digit;
    
    public Numbers(String w, int d) {
        word = w;
        digit = d;
    }
    

    }

  2. use Arrays.sort and create your custom comparator

    Arrays.sort(n, new Comparator<Numbers>() {
        public int compare(Numbers word, Numbers o) {
            return word.digit.compareTo((o.digit));
        }
    });
    


Assuming you know how to convert int to String, Just use your "intToWord" fucntion in comparator:

Arrays.sort(n, new Comparator<Integer>() {
  public int compare(Integer a, Integer b) {
      return intToWord(a).compareTo(intToWord(b));
  }
}


You have already translated the numbers into words, and you're having problems translating them back.

Create a map with key,value pair like {"one","1"},{"two","2"} when you are doing the conversion in the first part. Then just use that map to convert the sorted results back.