双线性序列给出奇怪的结果

双线性序列给出奇怪的结果

本文介绍了双线性序列给出奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图提高我的表演技能(不存在),但在将公式写入代码时遇到了问题.这是我要尝试的公式-用引号引起来-将转换"为代码.

I'm trying to get my performance skills (none existent) up to par but ran into a problem with writing out a formula into code. This is the formula I'm trying to - quote unquote - "convert" to code.

数字u(0) = 1u中的第一个数字. 对于u中的每个xy = 2 * x + 1z = 3 * x + 1也必须也在u中. u中没有其他数字. 例如:u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]

The number u(0) = 1 is the first one in u. For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too. There are no other numbers in u. Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]

1给出34,然后3给出7104给出913,然后7给出1522等...

1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...

这是我到目前为止所拥有的:

And this is what I have so far:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(DblLinear(10));
        //Expected result: 22
        Console.WriteLine(DblLinear(20));
        //Expected result: 57
        Console.WriteLine(DblLinear(30));
        //Expected result: 91
        Console.WriteLine(DblLinear(50));
        //Expected result: 175
    }
    public static int DblLinear (int n)
    {
        List<int> linArr = new List<int>();
        linArr.Add(1);

        int i = 0;
        while(linArr.Count < n)
        {
            linArr.Add((2 * linArr[i]) + 1);
            linArr.Add((3 * linArr[i]) + 1);
            linArr.Sort();
            i++;
        }
        return linArr[n - 1];
    }
}

计算是正确的,直到达到27.之后,它开始疯狂运行,我不知道它在做什么错.

The calculations are right until it hits 27. After that it just runs wild and I have no idea what it does wrong.

推荐答案

您从序列中取出一项,然后产生两项.因此,您确实需要一些数据结构来存储它们,因为它们的数量会增加.堆将是最好的.如果您想直接使用.net中的功能,则可以使用SortedSet.

You take one item from sequence and produce two. So You really need some data structure to store them, as their numbers would increase. Heap would be the best. If You want to go with what we have directly in .net, You can use SortedSet.

public static IEnumerable<int> DblLinear2()
{
    SortedSet<int> seq = new SortedSet<int> { 1 };

    while (true)
    {
        int min = seq.First();
        seq.Remove(min);
        yield return min;
        seq.Add(min * 2 + 1);
        seq.Add(min * 3 + 1);
    }
}

结果:

这篇关于双线性序列给出奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:23