获取所有可能加起来达到给定数字的总和

发布于 2024-12-03 20:17:44 字数 292 浏览 3 评论 0原文

我正在为 Android 制作一个数学应用程序。在这些字段之一中,用户可以输入一个整数(无数字且大于 0)。这个想法是获得所有可能的和,使这个 int,没有双精度(在这种情况下 4+1 == 1+4)。唯一已知的是这个 int。

例如:

假设用户输入 4,我希望应用程序返回:

  • 4
  • 3+1
  • 2+2
  • 2+1+1
  • 1+1+1+1

显然 4 == 4 所以也应该添加。关于我应该如何做这件事有什么建议吗?

I'm making an math app for the android. In one of these fields the user can enter an int (no digits and above 0). The idea is to get all possible sums that make this int, without doubles (4+1 == 1+4 in this case). The only thing known is this one int.

For example:

Say the user enters 4, I would like the app to return:

  • 4
  • 3+1
  • 2+2
  • 2+1+1
  • 1+1+1+1

Obviously 4 == 4 so that should be added too. Any suggestions as to how i should go about doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

淡看悲欢离合 2024-12-10 20:17:44

这是一个简单的算法,旨在

从以下位置执行此操作:http://introcs。 cs.princeton.edu/java/23recursion/Partition.java.html

公共类分区 { 

    公共静态无效分区(int n){
        分区(n,n,“”);
    }
    公共静态无效分区(int n,int max,字符串前缀){
        如果(n==0){
            StdOut.println(前缀);
            返回;
        }

        for (int i = Math.min(max, n); i >= 1; i--) {
            分区(ni, i, 前缀 + " " + i);
        }
    }


    公共静态无效主(字符串[] args){ 
        int N = Integer.parseInt(args[0]);
        分区(N);
    }

}

Here's a simple algorithm that purports to do that

from : http://introcs.cs.princeton.edu/java/23recursion/Partition.java.html

public class Partition { 

    public static void partition(int n) {
        partition(n, n, "");
    }
    public static void partition(int n, int max, String prefix) {
        if (n == 0) {
            StdOut.println(prefix);
            return;
        }

        for (int i = Math.min(max, n); i >= 1; i--) {
            partition(n-i, i, prefix + " " + i);
        }
    }


    public static void main(String[] args) { 
        int N = Integer.parseInt(args[0]);
        partition(N);
    }

}
压抑⊿情绪 2024-12-10 20:17:44

有一些简短而优雅的递归解决方案来生成它们,但以下内容可能更容易在现有代码中使用和实现:

import java.util.*;

public class SumIterator implements Iterator<List<Integer>>, Iterable<List<Integer>> {

  // keeps track of all sums that have been generated already
  private Set<List<Integer>> generated;

  // holds all sums that haven't been returned by `next()`
  private Stack<List<Integer>> sums;

  public SumIterator(int n) {

    // first a sanity check...
    if(n < 1) {
      throw new RuntimeException("'n' must be >= 1");
    }

    generated = new HashSet<List<Integer>>();
    sums = new Stack<List<Integer>>();

    // create and add the "last" sum of size `n`: [1, 1, 1, ... , 1]
    List<Integer> last = new ArrayList<Integer>();
    for(int i = 0; i < n; i++) {
      last.add(1);
    }
    add(last);

    // add the first sum of size 1: [n]
    add(Arrays.asList(n));
  }

  private void add(List<Integer> sum) {
    if(generated.add(sum)) {
      // only push the sum on the stack if it hasn't been generated before
      sums.push(sum);
    }
  }

  @Override
  public boolean hasNext() {
    return !sums.isEmpty();
  }

  @Override
  public Iterator<List<Integer>> iterator() {
    return this;
  }

  @Override
  public List<Integer> next() {
    List<Integer> sum = sums.pop();                         // get the next sum from the stack
    for(int i = sum.size() - 1; i >= 0; i--) {              // loop from right to left
      int n = sum.get(i);                                   //   get the i-th number
      if(n > 1) {                                           //   if the i-th number is more than 1
        for(int j = n-1; j > n/2; j--) {                    //     if the i-th number is 10, loop from 9 to 5
          List<Integer> copy = new ArrayList<Integer>(sum); //       create a copy of the current sum
          copy.remove(i);                                   //       remove the i-th number
          copy.add(i, j);                                   //       insert `j` where the i-th number was
          copy.add(i + 1, n-j);                             //       insert `n-j` next to `j`
          add(copy);                                        //       add this new sum to the stack
        }                                                   //     
        break;                                              //   stop looping any further
      }                                                     
    }
    return sum;
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException();
  }
}

您可以像这样使用它:

int n = 10;
for(List<Integer> sum : new SumIterator(n)) {
  System.out.println(n + " = " + sum);
}

它将打印:

10 = [10]
10 = [6, 4]
10 = [6, 3, 1]
10 = [6, 2, 1, 1]
10 = [7, 3]
10 = [7, 2, 1]
10 = [8, 2]
10 = [9, 1]
10 = [5, 4, 1]
10 = [5, 3, 1, 1]
10 = [5, 2, 1, 1, 1]
10 = [8, 1, 1]
10 = [7, 1, 1, 1]
10 = [4, 3, 1, 1, 1]
10 = [4, 2, 1, 1, 1, 1]
10 = [6, 1, 1, 1, 1]
10 = [5, 1, 1, 1, 1, 1]
10 = [3, 2, 1, 1, 1, 1, 1]
10 = [4, 1, 1, 1, 1, 1, 1]
10 = [3, 1, 1, 1, 1, 1, 1, 1]
10 = [2, 1, 1, 1, 1, 1, 1, 1, 1]
10 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

There are short and elegant recursive solution to generate them, but the following may be easier to use and implement in existing code:

import java.util.*;

public class SumIterator implements Iterator<List<Integer>>, Iterable<List<Integer>> {

  // keeps track of all sums that have been generated already
  private Set<List<Integer>> generated;

  // holds all sums that haven't been returned by `next()`
  private Stack<List<Integer>> sums;

  public SumIterator(int n) {

    // first a sanity check...
    if(n < 1) {
      throw new RuntimeException("'n' must be >= 1");
    }

    generated = new HashSet<List<Integer>>();
    sums = new Stack<List<Integer>>();

    // create and add the "last" sum of size `n`: [1, 1, 1, ... , 1]
    List<Integer> last = new ArrayList<Integer>();
    for(int i = 0; i < n; i++) {
      last.add(1);
    }
    add(last);

    // add the first sum of size 1: [n]
    add(Arrays.asList(n));
  }

  private void add(List<Integer> sum) {
    if(generated.add(sum)) {
      // only push the sum on the stack if it hasn't been generated before
      sums.push(sum);
    }
  }

  @Override
  public boolean hasNext() {
    return !sums.isEmpty();
  }

  @Override
  public Iterator<List<Integer>> iterator() {
    return this;
  }

  @Override
  public List<Integer> next() {
    List<Integer> sum = sums.pop();                         // get the next sum from the stack
    for(int i = sum.size() - 1; i >= 0; i--) {              // loop from right to left
      int n = sum.get(i);                                   //   get the i-th number
      if(n > 1) {                                           //   if the i-th number is more than 1
        for(int j = n-1; j > n/2; j--) {                    //     if the i-th number is 10, loop from 9 to 5
          List<Integer> copy = new ArrayList<Integer>(sum); //       create a copy of the current sum
          copy.remove(i);                                   //       remove the i-th number
          copy.add(i, j);                                   //       insert `j` where the i-th number was
          copy.add(i + 1, n-j);                             //       insert `n-j` next to `j`
          add(copy);                                        //       add this new sum to the stack
        }                                                   //     
        break;                                              //   stop looping any further
      }                                                     
    }
    return sum;
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException();
  }
}

You can use it like this:

int n = 10;
for(List<Integer> sum : new SumIterator(n)) {
  System.out.println(n + " = " + sum);
}

which would print:

10 = [10]
10 = [6, 4]
10 = [6, 3, 1]
10 = [6, 2, 1, 1]
10 = [7, 3]
10 = [7, 2, 1]
10 = [8, 2]
10 = [9, 1]
10 = [5, 4, 1]
10 = [5, 3, 1, 1]
10 = [5, 2, 1, 1, 1]
10 = [8, 1, 1]
10 = [7, 1, 1, 1]
10 = [4, 3, 1, 1, 1]
10 = [4, 2, 1, 1, 1, 1]
10 = [6, 1, 1, 1, 1]
10 = [5, 1, 1, 1, 1, 1]
10 = [3, 2, 1, 1, 1, 1, 1]
10 = [4, 1, 1, 1, 1, 1, 1]
10 = [3, 1, 1, 1, 1, 1, 1, 1]
10 = [2, 1, 1, 1, 1, 1, 1, 1, 1]
10 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
開玄 2024-12-10 20:17:44

这是称为分区的数学概念。总的来说,这……很困难,但是有一些针对小数量的技术。从 wiki 页面链接的大量有用内容。

This is the mathematical concept known as partitions. In general, it's... difficult, but there are techniques for small numbers. A load of useful stuff linked from the wiki page.

与酒说心事 2024-12-10 20:17:44

对于数字 N,您知道最大项数为 N。因此,您将首先枚举所有这些可能性。

对于每个可能的项数,都有多种可能性。这个公式现在让我困惑,但基本上,这个想法是从 (N+1-i + 1 + ... + 1) 开始,其中 i 是项数,并将 1 从左向右移动,第二种情况是为 (Ni + 2 + ... + 1)
直到您无法进行另一次移动而不导致未排序的组合。

(还有,你为什么又给这个机器人加标签了?)

For a number N you know that the max number of terms is N. so, you will start by enumerating all those possibilities.

For each possible number of terms, there are a number of possibilities. The formula eludes me now, but basically, the idea is to start by (N+1-i + 1 + ... + 1) where i is the number of terms, and to move 1s from left to right, second case would be (N-i + 2 + ... + 1)
until you cannot do another move without resulting in an unsorted combination.

(Also, why did you tagged this android again?)

莫言歌 2024-12-10 20:17:44

这与子集和问题算法有关。

N = {N*1, (N-1)+1, (N-2)+2, (N-3)+3 ..,
N-1 = {(N-1), ((N-1)-1)+2, ((N-1)-1)+3..}

等等。

所以这是一个涉及替换的递归函数;然而,在处理大量数据时,这是否有意义,你必须自己决定。

This is related to the subset sum problem algorithm.

N = {N*1, (N-1)+1, (N-2)+2, (N-3)+3 ..,
N-1 = {(N-1), ((N-1)-1)+2, ((N-1)-1)+3..}

etc.

So it's a recursive function involving substitution; whether that makes sense or not when dealing with large numbers, however, is something you'll have to decide for yourself.

痕至 2024-12-10 20:17:44

所有这些解决方案看起来都有点复杂。这可以通过简单地“递增”一个初始化为包含 1=N 的列表来实现。

如果人们不介意从 C++ 进行转换,则以下算法会产生所需的输出。

bool next(vector<unsigned>& counts) {
    if(counts.size() == 1)
        return false;

    //increment one before the back
    ++counts[counts.size() - 2];

    //spread the back into all ones
    if(counts.back() == 1)
        counts.pop_back();
    else {
        //reset this to 1's
        unsigned ones = counts.back() - 1;
        counts.pop_back();
        counts.resize(counts.size() + ones, 1);
    }
    return true;
}

void print_list(vector<unsigned>& list) {
    cout << "[";
    for(unsigned i = 0; i < list.size(); ++i) {
        cout << list[i];
        if(i < list.size() - 1)
            cout << ", ";
    }
    cout << "]\n";
}

int main() {
    unsigned N = 5;
    vector<unsigned> counts(N, 1);
    do {
        print_list(counts);
    } while(next(counts));
    return 0;
}

对于 N=5,算法给出以下结果

[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 2, 1]
[1, 1, 3]
[1, 2, 1, 1]
[1, 2, 2]
[1, 3, 1]
[1, 4]
[2, 1, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 3]
[3, 1, 1]
[3, 2]
[4, 1]
[5]

All of these solutions seem a little complex. This can be achieved by simply "incrementing" a list initialized to contain 1's=N.

If people don't mind converting from c++, the following algorithm produces the needed output.

bool next(vector<unsigned>& counts) {
    if(counts.size() == 1)
        return false;

    //increment one before the back
    ++counts[counts.size() - 2];

    //spread the back into all ones
    if(counts.back() == 1)
        counts.pop_back();
    else {
        //reset this to 1's
        unsigned ones = counts.back() - 1;
        counts.pop_back();
        counts.resize(counts.size() + ones, 1);
    }
    return true;
}

void print_list(vector<unsigned>& list) {
    cout << "[";
    for(unsigned i = 0; i < list.size(); ++i) {
        cout << list[i];
        if(i < list.size() - 1)
            cout << ", ";
    }
    cout << "]\n";
}

int main() {
    unsigned N = 5;
    vector<unsigned> counts(N, 1);
    do {
        print_list(counts);
    } while(next(counts));
    return 0;
}

for N=5 the algorithm gives the following

[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 2, 1]
[1, 1, 3]
[1, 2, 1, 1]
[1, 2, 2]
[1, 3, 1]
[1, 4]
[2, 1, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 3]
[3, 1, 1]
[3, 2]
[4, 1]
[5]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文