Skip to content

Commit caee4bd

Browse files
committed
Redesign of algorithm
1 parent 10b2877 commit caee4bd

File tree

2 files changed

+30
-20
lines changed

2 files changed

+30
-20
lines changed

.vscode/settings.json

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{}

AutomatedLab.Common/Common/Public/Split-Array.ps1

+29-20
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,41 @@ function Split-Array
44
[Parameter(Mandatory = $true)]
55
[System.Collections.IEnumerable]$List,
66

7-
[Parameter(Mandatory = $true, ParameterSetName = 'ChunkSize')]
8-
[int]$ChunkSize,
7+
[Parameter(Mandatory = $true, ParameterSetName = 'MaxChunkSize')]
8+
[Alias('ChunkSize')]
9+
[int]$MaxChunkSize,
910

11+
[ValidateRange(2, [long]::MaxValue)]
1012
[Parameter(Mandatory = $true, ParameterSetName = 'ChunkCount')]
11-
[int]$ChunkCount
13+
[int]$ChunkCount,
14+
15+
[switch]$AllowEmptyChunks
1216
)
13-
$aggregateList = @()
1417

15-
if ($ChunkCount)
18+
if (-not $AllowEmptyChunks -and ($list.Count -lt $ChunkCount))
1619
{
17-
$ChunkSize = [Math]::Ceiling($List.Count / $ChunkCount)
20+
Write-Error "List count ($($List.Count)) is smaller than ChunkCount ($ChunkCount).)"
21+
return
1822
}
19-
20-
$blocks = [Math]::Floor($List.Count / $ChunkSize)
21-
$leftOver = $List.Count % $ChunkSize
22-
for ($i = 0; $i -lt $blocks; $i++)
23+
24+
if ($PSCmdlet.ParameterSetName -eq 'MaxChunkSize')
25+
{
26+
$ChunkCount = [Math]::Ceiling($List.Count / $MaxChunkSize)
27+
}
28+
$containers = foreach ($i in 1..$ChunkCount)
2329
{
24-
$end = $ChunkSize * ($i + 1) - 1
25-
26-
$aggregateList += @(, $List[$start..$end])
27-
$start = $end + 1
28-
}
29-
if ($leftOver -gt 0)
30+
New-Object System.Collections.Generic.List[object]
31+
}
32+
33+
$iContainer = 0
34+
foreach ($item in $List)
3035
{
31-
$aggregateList += @(, $List[$start..($end + $leftOver)])
36+
$containers[$iContainer].Add($item)
37+
$iContainer++
38+
if ($iContainer -ge $ChunkCount) {
39+
$iContainer = 0
40+
}
3241
}
33-
34-
, $aggregateList
35-
}
42+
43+
$containers
44+
}

0 commit comments

Comments
 (0)