Home > Software engineering >  Algorithm that shows n numbers whose sum is 100 with regression
Algorithm that shows n numbers whose sum is 100 with regression

Time:11-02

I need an algorithm that accepts the total numbers count and the first number as input, where the sum of these numbers must be 100.

Examples:

Input: count = 5, first = 50

Output must be something LIKE that: 50, 30, 15, 3.5, 1.5

Input: count = 7, first = 30

Output must be something LIKE that: 30, 25, 20, 10, 7.5, 5, 2.5

it is not very important for me that the output is as I indicated it in the examples, it's all about

I just do this code, and I can't figure out how to integrate the "first" variable to it:

public class Main {
    public static void main(String[] args) {
        var count = 5;
        var first = 50;
        System.out.println(calc(first, count)); // [6.7, 13.3, 20.0, 26.7, 33.3]
    }
    private static List<BigDecimal> calc(double first, double count) {
        double total = 100;
        int multiplier = 0;
        for (int i = 1; i <= count; i  ) {
            multiplier =i;
        }
        BigDecimal a = BigDecimal.valueOf(total / multiplier);
        List<BigDecimal> list = new ArrayList<>();
        BigDecimal b = BigDecimal.ZERO;
        for (int i = 0; i < count; i  ) {
            b = b.add(a);
            list.add(b.setScale(1, RoundingMode.HALF_UP));
        }
        return list;
    }
}

CodePudding user response:

Why can't you subtract the first number from the total, and decrease count by 1?

import java.util.*;
import java.math.*;

public class Main {
    public static void main(String[] args) {
        var count = 5;
        var first = 50;
        System.out.println(calc(first, count)); // [6.7, 13.3, 20.0, 26.7, 33.3]
    }
    private static List<BigDecimal> calc(double first, double count) {
        double total = 100 - first; // Decrease total by first
        count--; // Decrement
        int multiplier = 0;
        for (int i = 1; i <= count; i  ) {
            multiplier =i;
        }
        BigDecimal a = BigDecimal.valueOf(total / multiplier);
        List<BigDecimal> list = new ArrayList<>();
        list.add(BigDecimal.valueOf(first)); // Add first to list
        BigDecimal b = BigDecimal.ZERO;
        for (int i = 0; i < count; i  ) {
            b = b.add(a);
            list.add(b.setScale(1, RoundingMode.HALF_UP));
        }
        return list;
    }
}
  • Related