2012-10-22 29 views
1

我不知道我怎么会写代码以下复发:概括复发

[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]

就是这样,需要一个列表,并扩大了作为例子。我不知道我该如何编写代码。有人可以帮助我吗?

+3

你犯了一个错字吗?第二个列表的第二项不应该是“a * 2/3 + b/3”吗?另外你也许不应该混合使用'a * 1/3'和'a/3',他们的意思是一样的。 –

+0

@CoryKendall你是对的。你能解决它吗? – cybertextron

+2

没有太多的再现,更多的是线性插值。 – nneonneo

回答

2

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

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; 
} 
0

编写一个函数来处理第一个案例,并将其称为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; 
} 
+0

不幸的是,这会重复其中一个端点。也许你的意思是'[a,b] - > [a * 2/3 + b/3,a * 1/3 + b * 2/3,b];'。 – nneonneo

+0

@nneonneo谢谢,修复。 –

1

我认为你可以这样写:

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); 
} 
+0

这不是一个排列;不要那样称呼它。 – nneonneo

+0

@nneonneo是的。如问题中提到的那样,“复发”很好? –

+0

@YogendraSingh该函数应该包含一个'n'数字的数组 – cybertextron