2012-10-22 27 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