【问题标题】:generalizing a recurrence概括复发
【发布时间】:2012-10-22 03:55:00
【问题描述】:

我不确定如何为以下重复编写代码:

[a, b] --> [a, a*2/3, a*1/3+b*2/3, b];

[a, b, c] --> [a, a*2/3, a*1/3+b*2/3, b, b*2/3+ c/3, b/3+c*2/3, c]

就是这样,获取一个列表,然后像示例中那样扩展它。我不确定如何为此编写代码。有人可以帮我吗?

【问题讨论】:

  • 你打错了吗?第二个列表的第二个词不应该是a*2/3+b/3吗?此外,您可能不应该混合使用a*1/3a/3,始终使用其中一个;他们的意思是一样的。
  • @CoryKendall 你是对的。你能解决它吗?
  • 没有太多的重复,更多的是线性插值。
  • 对于第二个数组,你期望 a*2/3+c*1/3 和 a*1/3+c*2/3 吗?
  • 是否需要扩展为具有 [a b c d] 的列表?

标签: recurrence


【解决方案1】:

很简单:将一个列表作为输入,并生成一个列表作为输出。

public static <T extends Number> List<Double> expandThirds(List<T> input) {
    List<Double> output = new ArrayList<Double>();

    if(input.size() == 0)
        return output;

    output.add(input.get(0).doubleValue());

    for(int i=0; i<input.size()-1; i++) {
        double a = input.get(i).doubleValue();
        double b = input.get(i+1).doubleValue();
        output.add(a*2/3 + b/3);
        output.add(a*3 + b*2/3);
        output.add(b);
    }
    return output;
}

【讨论】:

    【解决方案2】:

    我觉得你可以这样写:

    double[] inputArray = new double[]{0.56,2.4,3.6};//pass you input array of size>1
    List<Double> outList = new ArrayList<Double>();
    //assuming minimum length of array = 2
    for (int i=0; i<inputArray.length-1;i++){
        permute(inputArray[i], inputArray[i+1], outList);
    }
    System.out.println(outList);
    

    其中generateRecurrance 是私有自定义方法,如下所示:

    private void generateRecurrance(double a, double b, List<Double> outList) {
        outList.add(a);
        outList.add(a*1/3+b*2/3);
        outList.add(a*2/3+b*1/3);
        outList.add(b);
    }
    

    【讨论】:

    • 这不是排列;别这么说。
    • @nneonneo 是的。问题中提到的recurrance 好吗?
    • @YogendraSingh 该函数应该接受n 数字的数组
    • 不,这也不是复发(正如我在评论中提到的那样)......不太确定我会如何称呼你写的内容。
    • @philippe:我更新了处理双数组的答案。请随意更改类型。
    【解决方案3】:

    编写一个函数来处理第一种情况,并将其命名为mySequenceHelper。这里就不写了,不过应该能处理这种情况:

    [a, b] --> [a*2/3+b/3, a*1/3+b*2/3, b];
    

    现在编写一个名为mySequence 的函数,并将每对数字传递给mySequenceHelper,将每组结果附加到一个主列表。这是java中的一个简单的:

    public List<Float> mySequence(List<Float> inputs) {
        List<Float> toReturn = new LinkedList<Float>();
    
        // Add the first term manually:
        toReturn.add(inputs.get(0));
    
        // For each pair of values in inputs, add the appropriate 3 terms
        for (int i = 0; i < inputs.size() - 1; i++) {
            toReturn.addAll(mySequenceHelper(inputs.get(i), inputs.get(i+1)));
        }
    
        return toReturn;
    }
    

    【讨论】:

    • 不幸的是,这会重复端点之一。也许你的意思是[a, b] -&gt; [a*2/3+b/3, a*1/3+b*2/3, b];
    猜你喜欢
    • 2012-02-18
    • 2021-12-09
    • 2017-05-06
    • 2017-05-11
    • 2019-12-20
    • 1970-01-01
    • 2014-07-20
    • 2014-08-22
    相关资源
    最近更新 更多