Powershell 3 Cmdlets Hackerrank Solution -
But :
# Read all lines into an array $lines = @($input) # Or read line by line $firstLine = Read-Host # not recommended – use [Console]::ReadLine() Better approach: powershell 3 cmdlets hackerrank solution
Introduction: Why PowerShell 3 on HackerRank? PowerShell is no longer just a Windows administration tool; it has become a powerful cross-platform scripting language. HackerRank includes PowerShell 3.0 as an available language for solving algorithm, data structure, and Linux shell-style problems. However, many developers attempt to use PowerShell like C# or Python, missing the elegance and conciseness of cmdlets . But : # Read all lines into an
$lines = @($input) $n = [int]$lines[0] $arr = $lines[1].Trim() -split '\s+' | ForEach-Object [int]$_ Problem: Given two arrays a and b of 3 integers each, compare corresponding elements. Award 1 point to a if a[i] > b[i] , 1 point to b if b[i] > a[i] . Return [aliceScore, bobScore] . Solution using PowerShell 3.0 cmdlets: # Read input $lines = @($input) $a = $lines[0].Trim() -split ' ' | ForEach-Object [int]$_ $b = $lines[1].Trim() -split ' ' | ForEach-Object [int]$_ Compare using pipeline $aliceScore = 0 $bobScore = 0 0..2 | ForEach-Object if ($a[$ ] -gt $b[$ ]) $aliceScore++ elseif ($b[$ ] -gt $a[$ ]) $bobScore++ However, many developers attempt to use PowerShell like
$s = @($input)[0] $words = $s -split '(?=[A-Z])' Write-Output $words.Count Regex split with lookahead. 8. Example 5: Sorting and Filtering – "Birthday Cake Candles" Problem: Count how many tallest candles exist (maximum height). Cmdlet pipeline: $lines = @($input) $n = [int]$lines[0] $heights = $lines[1].Trim() -split ' ' | ForEach-Object [int]$_ $max = ($heights | Measure-Object -Maximum).Maximum ($heights | Where-Object $_ -eq $max ).Count | Write-Output
Write-Output "$aliceScore $bobScore"