settingsAccountsettings
Menusettings

Q: Arrange Integers - Java Task

+10 votes

You are given an array of integer numbers which you need to rearrange by their name in the English language. For example, the integers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 must be ordered as 8, 5, 4, 9, 1, 7, 6, 3, 2, 0. (eight, five, four, nine, one, seven, six, three, two, zero, i.e. sorted alphabetically)

Integers larger than ten are represented in a simplified way, for example 88 is ‘eight-eight’ and 1234 is ‘one-two-three-four’. That means that 88 comes before 85. If the name of one integer starts with the name of another integer, such as in 11 (one-one) and 111 (one-one-one), the smaller integer comes first.

There are no negative integers in the input.

Input:

  • The input is on a single line – the integers to be rearranged, separated by a comma and space.

Output:

  • On the only output line, print the rearranged integers, in format {n1, n2, n3 … n}

Constraints:

  • The input numbers are positive signed integers
  • There are no more than 50 integers in the input
  • Allowed time/memory: 100ms/16MB

Examples:

arrange integers in java example

asked in Java category by user hues
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

Here's my solution:

package com.tutorials7.java.exam;

import java.util.*;

public class Pro_01_ArrangeNumbers_13March2016 {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);

        String[] inputNumbers = console.nextLine().split("\\D+"); //D+ Splits all EXCEPT numbers
        String[] digitToEnglish = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

        TreeMap<String, List<String>> englishWordToNumber = new TreeMap<>();
        for (String inputNumber : inputNumbers) {
            StringBuilder sb = new StringBuilder();
            for (char character : inputNumber.toCharArray()) {
                sb.append(digitToEnglish[Character.getNumericValue(character)]);
            }
            if (!englishWordToNumber.containsKey(sb.toString())) {
                englishWordToNumber.put(sb.toString(), new ArrayList<>());
            }
            englishWordToNumber.get(sb.toString()).add(inputNumber);
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, List<String>> entry : englishWordToNumber.entrySet()) {
            for (String digit : entry.getValue()) {
                sb.append(digit + ", ");
            }
        }
        sb.delete(sb.length() - 2, sb.length());
        System.out.println(sb);
    }
}

 

answered by user john7
selected by user golearnweb
...