How to resolve the algorithm Range expansion step by step in the PowerShell programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Range expansion step by step in the PowerShell programming language
Table of Contents
Problem Statement
A format for expressing an ordered list of integers is to use a comma separated list of either Example The list of integers: Is accurately expressed by the range expression: (And vice-versa).
Expand the range description: Note that the second element above, is the range from minus 3 to minus 1.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Range expansion step by step in the PowerShell programming language
Source code in the powershell programming language
function range-expansion($array) {
function expansion($arr) {
if($arr) {
$arr = $arr.Split(',')
$arr | foreach{
$a = $_
$b, $c, $d, $e = $a.Split('-')
switch($a) {
$b {return $a}
"-$c" {return $a}
"$b-$c" {return "$(([Int]$b)..([Int]$c))"}
"-$c-$d" {return "$(([Int]$("-$c"))..([Int]$d))"}
"-$c--$e" {return "$(([Int]$("-$c"))..([Int]$("-$e")))"}
}
}
} else {""}
}
$OFS = ", "
"$(expansion $array)"
$OFS = " "
}
range-expansion "-6,-3--1,3-5,7-11,14,15,17-20"
function Expand-Range
{
[CmdletBinding()]
[OutputType([int])]
Param
(
[Parameter(Mandatory=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
[ValidatePattern('^[0-9,-]*$')]
[string]
$Range
)
try
{
if ($Range -match '-,') # I'm not good enough to weed this case out with Regex
{
throw "Input string was not in a correct format."
}
[int[]]$output = $Range -split ',' | ForEach-Object {
[int[]]$array = $_ -split '(?<=\d)-'
if ($array.Count -gt 1) # $array contains one or two elements
{
$array[0]..$array[1] # two elements = start and end of range
}
else
{
$array # one element = an integer
}
}
}
catch
{
throw "Input string was not in a correct format."
}
$output
}
(Expand-Range "-6,-3--1,3-5,7-11,14,15,17-20") -join ", "
You may also check:How to resolve the algorithm List comprehensions step by step in the Lua programming language
You may also check:How to resolve the algorithm Empty directory step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Keyboard input/Flush the keyboard buffer step by step in the MiniScript programming language
You may also check:How to resolve the algorithm Stirling numbers of the first kind step by step in the Tcl programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the BASIC256 programming language