[英]Create Batches from a stack
我努力讓我解決這個頭,但基本上是試圖創建的,例如批名單1-200
, 201-400
, 401-53
從的數值453
。
到目前為止,我能數分割453
到列表200
, 200
, 53
,基本上告訴我,我需要創建3個批次。
但是,不確定如何創建批次嗎?
到目前為止,這是我創建堆棧的代碼
public List<int> CreateStacks(Int32 number, Int32 stackSize)
{
List<int> stacks = new List<int>();
int d = number / stackSize;
if (d == 0)
{
return stacks;
}
int r = number % stackSize;
string str = string.Join(",", Enumerable.Repeat("200", d));
if (number % 100 > 0)
{
str = str + ", " + r;
foreach(var s in str.Split(',').ToList())
{
stacks.Add(Convert.ToInt32(s));
}
}
return stacks;
}
有什么建議嗎?
我創建了另一個名為CreateRanges()
方法,該方法產生您提供的輸出,但所有范圍都從一個開始。 每個范圍應以零或一開始; 在您的示例中,第一批實際上有201個項目。
// Stacks: 200, 200, 53
// Ranges: <1,200>, <201,400>, <401,453>
void Main()
{
var stacks = CreateStacks(453, 200);
Console.WriteLine("Stacks: " + string.Join(", ", stacks.Select(n => n.ToString()).ToArray()));
var ranges = CreateRanges(453, stacks);
Console.WriteLine("Ranges: " + string.Join(", ", ranges.Select(t => $"<{t.Item1},{t.Item2}>").ToArray()));
Console.WriteLine();
}
public static List<Tuple<int, int>> CreateRanges(Int32 number, List<int> stacks)
{
var ranges = new List<Tuple<int, int>>();
var index = 0;
foreach (var stack in stacks){
ranges.Add(new Tuple<int, int>(index + 1, stack + index));
index += stack;
}
return ranges;
}
public static List<int> CreateStacks(Int32 number, Int32 stackSize)
{
List<int> stacks = new List<int>();
int d = number / stackSize;
if (d == 0)
{
return stacks;
}
int r = number % stackSize;
string str = string.Join(",", Enumerable.Repeat("200", d));
if (number % 100 > 0)
{
str = str + ", " + r;
foreach (var s in str.Split(',').ToList())
{
stacks.Add(Convert.ToInt32(s));
}
}
return stacks;
}
您可以使用for循環並確定計數是否已達到200,然后創建一個新列表。
int total = 453;
int batchCount = 200;
List<List<int>> batches = new List<List<int>>();
for (int i = 0; i < total; i++)
{
if (i % batchCount == 0)
{
batches.Add(new List<int>());
}
batches[batches.Count -1].Add(i);
}
列表batches
將包含3個具有所有數字的int
列表。
我的鏡頭實際上是“創建批次列表”:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var batches = Batchify( 453, 200);
Console.WriteLine(batches.Count);
foreach( Batch batch in batches )
{
Console.WriteLine("{0}-{1}", batch.Start, batch.End);
}
}
public static List<Batch> Batchify( int number, int size)
{
List<Batch> result = new List<Batch>();
int running = number;
int startIndex = 0;
do
{
int endIndex = running < size ? startIndex+running : startIndex+size-1;
result.Add(new Batch{ Start = startIndex, End = endIndex });
startIndex = endIndex+1;
running -= size;
}while(running > 0);
return result;
}
}
public class Batch
{
public int Start{get;set;}
public int End{get;set;}
}
實際中: https : //dotnetfiddle.net/oqFmv0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.