C#:所有小于3的索引子列表

一、所有小于3的索引子列表

  • 题目:
    整数列表中找出子列表的起始索引,要求子列表的连续5个值都小于3,将所有起始索引放进一个列表。

  • 定义一个FindSublistStartIndices方法,该方法接受一个整数列表、子列表的长度和阈值,并返回所有满足子列表中的值都小于阈值的起始索引。
    在Main方法中,我们使用这个方法打印出所有满足条件的起始索引。

二、程序

using System;
using System.Collections.Generic;
using System.Linq;
 
public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> {5, 2, 1, 4, 5, 6, 1, 2, 1, 2, 1,2,1,2};
        int sublistLength = 5;
        int threshold = 3;
 
        var startIndices = FindSublistStartIndices(numbers, sublistLength, threshold);
 
        foreach (var index in startIndices)
        {
            Console.WriteLine(index);
        }
    }
 
    public static IEnumerable<int> FindSublistStartIndices(List<int> numbers, int sublistLength, int threshold)
    {
        for (int i = 0; i < numbers.Count - sublistLength + 1; i++)
        {
            var sublist = numbers.GetRange(i, sublistLength);
            if (sublist.All(n => n < threshold))
            {
                yield return i;
            }
        }
    }
}

运行结果:
Start index of sublist with consecutive values < 3: 6
6
7
8
9

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,447评论 0 9
  • 一、编程规约 (一)命名规约 【强制】 代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束。反...
    喝咖啡的蚂蚁阅读 1,535评论 0 2
  • 来源与:阿里云栖 禁止用于商业用途 ps:如果需要电子书 评论你们邮箱 我会发给你们 下面感觉还是有点乱 目录 一...
    小向资源网阅读 7,674评论 0 12
  • 前言 本开发规范基于《阿里巴巴Java开发手册终极版》修改,并集成我们自己的项目开发规范,整合而成。 为表示对阿里...
    4ea0af17fd67阅读 5,667评论 0 5
  • 第3章 Lisp概览 毫无疑问,Common Lisp是一门庞大的语言。——Guy L. Steele(另一本Li...
    geoeee阅读 1,183评论 0 4