【问题标题】:Check for sums in array Java检查数组 Java 中的总和
【发布时间】:2016-11-07 05:31:39
【问题描述】:

我正在用 Java 做一个名为 30 的骰子游戏。我有一个包含骰子值的数组,例如 [1, 3, 4, 5, 5, 6]。从该数组中,我希望能够找到给出给定总和的每个组,但每个骰子只能计算一次。

例如,如果我有数组 [1, 3, 4, 5, 5, 6] 并且想要找到每个等于 12 的组,这将给我例如 1+5+6=12 和 3+4 +5=12。

如果用 [1, 1, 1, 1, 2, 6] 这样的例子,我会得到 1+1+1+1+2+6=12。

总会有 6 个骰子,但我要查找的总和可以是 4 到 12 之间的任何值。

有人可以帮帮我吗?我真的没有任何代码可以提供,它只会令人困惑并且根本没有帮助。

【问题讨论】:

标签: java arrays


【解决方案1】:

我有一个算法可以解决您的问题,但您必须根据自己的需要对其进行调整。 不幸的是,我不知道它是否属于任何特定的已知数据结构。

简而言之,我会说它将您的数组转换为二进制位置并在其上循环,从没有标记任何项目的位置到标记所有项目的位置。

  • 数组大小 = 6
  • 初始标记数组 = "000000" // 6 个位置未标记
  • 最终标记数组 = "111111" // 标记 6 个位置

递增二进制数组,它只对标记的位置求和。我们将能够总结所有可能的组合。

测试 1

给定你的参数:

  • 总和 = 12
  • 数组 = {1, 3, 4, 5, 5, 6}

结果是:

Position: 011010  // means the sum of item in position 1,2,4 (3 + 4 + 5 = 12)
Position: 011100  // means the sum of item in position 1,2,3 (3 + 4 + 5 = 12)
Position: 100011  // means the sum of item in position 0,4,5 (1 + 5 + 6 = 12)
Position: 100101  // means the sum of item in position 0,3,5 (1 + 5 + 6 = 12)

测试 2

给定你的参数:

  • 总和 = 12
  • 数组 = {1, 1, 1, 1, 2, 6}

结果是:

Position: 111111  // means the sum of item in position 0,1,2,3,4,5 (1+1+1+1+2+6 = 12)

代码可能会有所改进,但如下所示,在要求和的位置上简单地打印“1”,得到所需的数字。

public class Algorithm {

public static void main(String[] args) {
	Algorithm checkSum = new Algorithm();

	Integer[] array = {1, 3, 4, 5, 5, 6};
	Integer sum = 12;
	checkSum.find(array, sum);
	
	System.out.println("------------------");
	
	Integer[] array2 = {1, 1, 1, 1, 2, 6};
	Integer sum2 = 12;
	checkSum.find(array2, sum2);
}

private void find(Integer[] array, Integer sum) {
	// This could be replaced by a StringUtils lib to fill with "1" the size of the array
	String maxBinary = "";
	for (int i=0; i<array.length; i++) {
		maxBinary += "1";
	}
	
	int maxDecimal = Integer.parseInt(maxBinary, 2);
	
	// This will iterate from "000000" to "111111"
	for (int i=0; i<=maxDecimal; i++) {
		String binaryNumber = lpad(Integer.toBinaryString(i), array.length);
		
		int checkSum = 0;
		for (int j=0; j<binaryNumber.length(); j++) {
			if ("1".equals(binaryNumber.substring(j,j+1))) {
				checkSum += array[j]; 
			}
		}
		// This is the check to see if the sum is the desired one
		if (sum == checkSum) {
			System.out.println("Positions: " + binaryNumber);
		}	
	}
}

/**
 * This is a simple LPAD function to add zeros to the left of the string. 
 */
private String lpad(String text, Integer size) {
	String regex = "%0"+ size + "d";
	return String.format(regex, Integer.parseInt(text));
}
}

希望对你有帮助!

【讨论】:

    【解决方案2】:

    这里是一个没有经过很好测试并且可能有点幼稚的解决方案。我使用整数列表,因为我不喜欢数组,抱歉!

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import org.junit.Before;
    import org.junit.Test;
    
    public class PickNumbersTest {
    
        private List<Integer> numbers;
    
        @Before
        public void before() {
            Integer[] ints = new Integer[] { 1, 3, 4, 5, 5, 6 };
            numbers = new ArrayList<>();
            numbers.addAll(Arrays.asList(ints));        
        }
    
        @Test
        public void test() {
    
            PickNumbers p = new PickNumbers();
            List<List<Integer>> result = p.pick(12,  numbers);
    
            System.out.println(result);
        }
    }
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class PickNumbers {
    
        public List<List<Integer>> pick(final int sum, final List<Integer> values) {
    
            // make a copy to avoid making changes to passed in List
            List<Integer> numbers = copy(values);
    
            List<List<Integer>> results = new ArrayList<List<Integer>>();
    
            while (!pickSingle(sum, numbers).isEmpty()) {
    
                List<Integer> currentResult = pickSingle(sum, numbers);
    
                results.add(currentResult);
                currentResult.forEach(i -> numbers.remove(i));
    
            }
    
            return results;
        }
    
        protected List<Integer> pickSingle(final int sum, final List<Integer> values) {
            int rest = sum;
            List<Integer> result = new ArrayList<>();
            Picker p = new Picker(values);
    
            while (rest > 0 && p.hasNext()) {
    
                int i = p.next();
    
                if (i > rest) {
                    p.remove();
                } else if (i == rest) {
                    result.add(i);
                    return result;
                } else { // i < rest
                    result.add(i);
                    p.remove();
                    rest = rest - i;
                }
            }
    
            return new ArrayList<>();
        }
    
        private List<Integer> copy(final List<Integer> values) {
    
            List<Integer> copy = new ArrayList<Integer>();
            copy.addAll(values);
    
            return copy;
        }
    }
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class Picker {
    
        private List<Integer> values = new ArrayList<Integer>();
    
        public Picker(final List<Integer> values) {
    
            this.values.addAll(values);
            this.values.sort(null);
            Collections.reverse(this.values);
        }
    
        public int next() {
    
            return values.get(0);
        }
    
        public void remove() {
    
            values.remove(0);
        }
    
        public boolean hasNext() {
    
            return values.size() > 0;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-16
      • 1970-01-01
      • 2021-08-28
      • 2023-04-03
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-17
      相关资源
      最近更新 更多