fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4.  
  5.  
  6. /* Name of the class has to be "Main" only if the class is public. */
  7. public class Main
  8. {
  9. static void printRLEDigits(String input) {
  10. Scanner sc = new Scanner(input);
  11. int freq = 0;
  12. int oldNum = 0;
  13. boolean first = true;
  14.  
  15. out: while(sc.hasNext()) {
  16.  
  17. String s = sc.next(); // getting "number" delimited with whitespaces
  18. for (char c: s.toCharArray()) {
  19. if (!Character.isDigit(c)) {
  20. break out;
  21. }
  22. int i = c - '0';
  23. if (i != oldNum || first) {
  24. if (first)
  25. first = false;
  26. else // digit changed
  27. System.out.printf("%dx%d.", freq, oldNum);
  28. oldNum = i;
  29. freq = 1;
  30. } else {
  31. freq++;
  32. }
  33. }
  34. }
  35. if (!first)
  36. System.out.printf("%dx%d.%n", freq, oldNum);
  37. else
  38. System.out.println("No integer found");
  39. sc.close();
  40. }
  41.  
  42. static void printRLE(String input) {
  43. Scanner sc = new Scanner(input);
  44. int freq = 0;
  45. int oldNum = 0;
  46. boolean first = true;
  47.  
  48. while(sc.hasNextInt()) {
  49.  
  50. int i = sc.nextInt();
  51.  
  52. if (i != oldNum || first) {
  53. if (first)
  54. first = false;
  55. else // integer value changed
  56. System.out.printf("%dx%d.", freq, oldNum);
  57. oldNum = i;
  58. freq = 1;
  59. } else {
  60. freq++;
  61. }
  62. }
  63. if (!first)
  64. System.out.printf("%dx%d.%n", freq, oldNum);
  65. else
  66. System.out.println("No integer found");
  67. sc.close();
  68. }
  69.  
  70.  
  71. public static void main (String[] args) throws java.lang.Exception
  72. {
  73. String[] tests = {
  74. "",
  75. "abc.",
  76. "11 11 11",
  77. "112 223",
  78. "1 1 1\n7 7 2 2 1",
  79. "1 1 1\n7 7 2 2 0 ",
  80. "0 0 0",
  81. };
  82.  
  83. for (String test: tests) {
  84. System.out.println("test=[" + test + "]");
  85. System.out.println("Numbers: ");
  86. printRLE(test);
  87. System.out.println("Digits: ");
  88. printRLEDigits(test);
  89.  
  90. System.out.println("--------");
  91. }
  92. }
  93. }
Success #stdin #stdout 0.18s 38620KB
stdin
Standard input is empty
stdout
test=[]
Numbers: 
No integer found
Digits: 
No integer found
--------
test=[abc.]
Numbers: 
No integer found
Digits: 
No integer found
--------
test=[11 11 11]
Numbers: 
3x11.
Digits: 
6x1.
--------
test=[112 223]
Numbers: 
1x112.1x223.
Digits: 
2x1.3x2.1x3.
--------
test=[1 1 1
7 7 2 2 1]
Numbers: 
3x1.2x7.2x2.1x1.
Digits: 
3x1.2x7.2x2.1x1.
--------
test=[1 1 1
7 7 2 2 0 ]
Numbers: 
3x1.2x7.2x2.1x0.
Digits: 
3x1.2x7.2x2.1x0.
--------
test=[0 0 0]
Numbers: 
3x0.
Digits: 
3x0.
--------