gpt4 book ai didi

c# - 获取接下来的 500 个 "free"数字

转载 作者:行者123 更新时间:2023-12-03 19:33:46 25 4
gpt4 key购买 nike

我有一个包含数字的数组,代表使用过的位置。我想获取从 1 到任意数字的前 500 个未使用的数字。

例如,我的数组包含以下数字:1,2,5,6,8,9

基于该数组,我想要一个包含以下数字的新数组:3,4,7,10,11,12,13,14....500,501,502,503,504,505,506,507

有没有比循环增加数字更有效的方法,检查该数字是否包含在默认数组中,如果没有将其放入新数组中,则检查新数组是否有 500 个值,然后中断从循环中?

谢谢!

最佳答案

我建议实现生成器:

// source should be sorted
private static IEnumerable<int> Free(IEnumerable<int> source) {
int last = 0;
bool first = true;

foreach (var item in source) {
if (first)
first = false;
else
for (int i = last + 1; i < item; ++i) // <- Hole
yield return i;

last = item;
}

// The array exhausted
for (int i = last + 1; ; ++i)
yield return i;
}

然后在 Linq 的帮助下生成任意数量的项目

int[] used = new[] { 1,2,5,6,8,9};

int[] free = Free(used)
.Take(501) // <- if you want 507 being the last item you have to take 501 items
.ToArray();

Console.Write(string.Join(", ", free));

结果:

3, 4, 7, 10, 11, 12, 13, 14, ..., 505, 506, 507

关于c# - 获取接下来的 500 个 "free"数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43982251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com