Tribonacci序列

时间:2018-01-10 23:33:41

标签: c#

我正在尝试解决this exercise

myprint

它适用于给出的测试,但我仍然无法通过最终检查。什么指针我做错了什么?

3 个答案:

答案 0 :(得分:0)

只是引起你的好奇,代码中的注释(对于c#)是不正确的,因为它表示如果n == 0返回长度为1的数组。令人困惑,但正确的返回值是一个空数组,如指令集和op发布的问题的注释中所指定的那样。

正如您所说,问题是您需要在signature次迭代后返回n,因此在一次迭代后,检查需要一个长度为1的数组。

在python中回答:

def tribonacci(signature, n):
    if n == 0:
        return []

    next_sum = 0

    for i in range(len(signature)):
        next_sum += signature[i]

    return  signature[:-2] + tribonacci(signature[-2:] + [next_sum], n-1)

或列表理解:

def tribonacci(signature, n):
    if n == 0:
       return []
    return signature[:-2] + tribonacci(signature[-2:] + [sum([ e for e in signature ])], n-1)

答案 1 :(得分:0)

既然你弄清楚了,我会提出我的解决方案。

我创建了一个辅助函数来返回一个无限的Tribonacci序列,然后在所需的函数中使用它。

using System.Collections.Generic;
using System.Linq;

public class Xbonacci {
  public double[] Tribonacci(double[] signature, int n) {
    // hackonacci me
    // if n==0, then return an array of length 1, containing only a 0
    if (n == 0)
        return new double[] { 0 };
    else
        return Tribonacci(signature).Take(n).ToArray();
  }

  public IEnumerable<double> Tribonacci(double[] signature) {
      foreach (var n in signature)
          yield return n;

      var buffer = new Queue<double>(signature);
      while (true) {
          var next = buffer.Sum();
          yield return next;
          buffer.Dequeue();
          buffer.Enqueue(next);
      }
  }
}

如果修复了C#测试中的错误,则会将Tribonacci的{​​{1}}减少为:

n

答案 2 :(得分:0)

这是F#中的通用解决方案,可以接受任何长度的签名列表。输出示例: 1)“ genBonacci [1; 1] 10”:[1; 1; 2; 3; 5; 8; 13; 21; 34; 55](标准斐波那契); 2)“ genBonacci [1; 1; 2] 10”:[1; 1; 2; 4; 7; 13; 24; 44; 81; 149](Tribonacci); 3)“ genBonacci [1; 1; 2; 0] 10”:[1; 1; 2; 0; 4; 7; 13; 24; 48; 92](“ Tetra” bonacci)。

let genBonacci (sign:int list) n = 
    let len = List.length sign
    match n,sign with
    |_,[]->[]
    |a,x when a<1+len->List.take a x
    |a,x->
        let rec loop upTo i aList =
            match i,aList with
            |i,y when i < upTo-> [List.take len y |> List.sum]@aList |> loop upTo (i+1)
            |_->aList
        List.rev x |> loop a len |> List.rev