Home > Software design >  Rounding up individual elements in an array and sorting them afterwards
Rounding up individual elements in an array and sorting them afterwards

Time:08-24

I am trying to solve for:

Original array elements: [0 16 27 73 55]

  • first round them up 0-> 0 stays; 16 is rounded up to 20 and converted to 2. 27 is rounded up to 30 and converted to 3. 73 is rounded down to 70 and converted to 7. 55 is rounded up to 60 and converted to 6.

  • second I short the converted "new"elements and get an OUTPUT:

[0,2,3,6,7]

if any new elements are the same, both enetries are kept for isntance [0,2,3,6,6,7]

Many thanks for your thoughst and support.

CodePudding user response:

Okay, based on the clarification comment you made, it sounds like you don't know how to approach rounding to the nearest multiple of 10. If you don't want to use float/decimal solutions, you can use "mod" and I'd write a function like...

public class Main {
  static int NearMult10(int srcVal) {
    int remainder = srcVal % 10;

    if (remainder < 5) { return srcVal - remainder; }
    else { return srcVal   (10 - remainder); }
  }

  public static void main(String[] args) {
    System.out.println("rounded...");
    int[] srcList = { 3, 6, 12, 18, 37, 81, 108 };
    int srcCount = srcList.length;
    
    for (int i = 0; i < srcCount; i  )
    {
        System.out.println("src: "   srcList[i]   " => result: "   NearMult10(srcList[i]));
    }
  }
}

And just use that "NearMult10" method. The result of that example code looks like...

rounded...
src: 3 => result: 0
src: 6 => result: 10
src: 12 => result: 10
src: 18 => result: 20
src: 37 => result: 40
src: 81 => result: 80
src: 108 => result: 110

You can call the sort method on whatever array you build.

  • Related