demonstrate the basic syntax of arrays in a given programming language. The codes include creating an array, assigning a value to it, and retrieving an element from it. The codes also show both fixed-length and dynamic arrays, and how to push a value into an array. The codes further illustrate how to create an empty array, an array with one member, and longer arrays by separating values with commas. The codes demonstrate how to append a value to an array using the += operator, retrieve values using indexing syntax, replace values, and create arrays of integers using the range operator. The codes also show how to index for retrieval using arrays and negative numbers for indexing from the end of the array.


Get-Content $PWD\input.txt | Out-File $PWD\output.txt

Get-Content $PWD\input.txt | Set-Content $PWD\output.txt

The code reads content from "input.txt" file into an intermediate variable, then writes the content from the variable into a new file called "output.txt". It assumes both files are located in the same directory as the script. It does not directly copy the file content, but uses an intermediate variable.


$string = 'alphaBETA'
$lower  = $string.ToLower()
$upper  = $string.ToUpper()
$title  = (Get-Culture).TextInfo.ToTitleCase($string)

$lower, $upper, $title

demonstrate the conversion of the string "alphaBETA" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.


# Create an Array by separating the elements with commas:
$array = "one", 2, "three", 4

# Using explicit syntax:
$array = @("one", 2, "three", 4)

# Send the values back into individual variables:
$var1, $var2, $var3, $var4 = $array

# An array of several integer ([int]) values:
$array = 0, 1, 2, 3, 4, 5, 6, 7

# Using the range operator (..):
$array = 0..7

# Strongly typed:
[int[]] $stronglyTypedArray = 1, 2, 4, 8, 16, 32, 64, 128

# An empty array:
$array = @()

# An array with a single element:
$array = @("one")

# I suppose this would be a jagged array:
$jaggedArray = @((11, 12, 13),
                 (21, 22, 23),
                 (31, 32, 33))

$jaggedArray | Format-Wide {$_} -Column 3 -Force

$jaggedArray[1][1] # returns 22

# A Multi-dimensional array:
$multiArray = New-Object -TypeName "System.Object[,]" -ArgumentList 6,6

for ($i = 0; $i -lt 6; $i++)
{
    for ($j = 0; $j -lt 6; $j++)
    {
        $multiArray[$i,$j] = ($i + 1) * 10 + ($j + 1)
    }
}

$multiArray | Format-Wide {$_} -Column 6 -Force

$multiArray[2,2] # returns 33

# An empty Hash Table:
$hash = @{}

# A Hash table populated with some values:
$nfcCentralDivision = @{
    Packers = "Green Bay"
    Bears   = "Chicago"
    Lions   = "Detroit"
}

# Add items to a Hash Table:
$nfcCentralDivision.Add("Vikings","Minnesota")
$nfcCentralDivision.Add("Buccaneers","Tampa Bay")

# Remove an item from a Hash Table:
$nfcCentralDivision.Remove("Buccaneers")

# Searching for items
$nfcCentralDivision.ContainsKey("Packers")
$nfcCentralDivision.ContainsValue("Green Bay")

# A bad value...
$hash1 = @{
    One = 1
    Two = 3
}

# Edit an item in a Hash Table:
$hash1.Set_Item("Two",2)

# Combine Hash Tables:

$hash2 = @{
    Three = 3
    Four  = 4
}

$hash1 + $hash2

# Using the ([ordered]) accelerator the items in the Hash Table retain the order in which they were input:
$nfcCentralDivision = [ordered]@{
    Bears   = "Chicago"
    Lions   = "Detroit"
    Packers = "Green Bay"
    Vikings = "Minnesota"
}

$list = New-Object -TypeName System.Collections.ArrayList -ArgumentList 1,2,3

# or...

$list = [System.Collections.ArrayList]@(1,2,3)

$list.Add(4) | Out-Null
$list.RemoveAt(2)

create a collection in a statically-typed language, add a few values to it, and demonstrate the use of common collection types in PowerShell such as arrays, hash tables, and ArrayList from .NET. The code also explains the zero-based indexing of arrays and the two types of hash tables: normal and ordered.


Works with: PowerShell version 3.0
#  Define the items to pack
$Item = @(
    [pscustomobject]@{ Name = 'panacea'; Unit = 'vials'  ; value = 3000; Weight = 0.3; Volume = 0.025 }
    [pscustomobject]@{ Name = 'ichor'  ; Unit = 'ampules'; value = 1800; Weight = 0.2; Volume = 0.015 }
    [pscustomobject]@{ Name = 'gold'   ; Unit = 'bars'   ; value = 2500; Weight = 2.0; Volume = 0.002 }
    )

#  Define our maximums
$MaxWeight = 25
$MaxVolume = 0.25

#  Set our default value to beat
$OptimalValue = 0

#  Iterate through the possible quantities of item 0, without going over the weight or volume limit
ForEach ( $Qty0 in 0..( [math]::Min( [math]::Truncate( $MaxWeight / $Item[0].Weight ), [math]::Truncate( $MaxVolume / $Item[0].Volume ) ) ) )
    {
    #  Calculate the remaining space
    $RemainingWeight = $MaxWeight - $Qty0 * $Item[0].Weight
    $RemainingVolume = $MaxVolume - $Qty0 * $Item[0].Volume

    #  Iterate through the possible quantities of item 1, without going over the weight or volume limit
    ForEach ( $Qty1 in 0..( [math]::Min( [math]::Truncate( $RemainingWeight / $Item[1].Weight ), [math]::Truncate( $RemainingVolume / $Item[1].Volume ) ) ) )
        {
        #  Calculate the remaining space
        $RemainingWeight2 = $RemainingWeight - $Qty1 * $Item[1].Weight
        $RemainingVolume2 = $RemainingVolume - $Qty1 * $Item[1].Volume

        #  Calculate the maximum quantity of item 2 for the remaining space, without going over the weight or volume limit
        $Qty2 = [math]::Min( [math]::Truncate( $RemainingWeight2 / $Item[2].Weight ), [math]::Truncate( $RemainingVolume2 / $Item[2].Volume ) )

        #  Calculate the total value of the items packed
        $TrialValue =   $Qty0 * $Item[0].Value +
                        $Qty1 * $Item[1].Value +
                        $Qty2 * $Item[2].Value

        #  Describe the trial solution
        $Solution  = "$Qty0 $($Item[0].Unit) of $($Item[0].Name), "
        $Solution += "$Qty1 $($Item[1].Unit) of $($Item[1].Name), and "
        $Solution += "$Qty2 $($Item[2].Unit) of $($Item[2].Name) worth a total of $TrialValue."

        #  If the trial value is higher than previous most valuable trial...
        If ( $TrialValue -gt $OptimalValue )
            {
            #  Set the new number to beat
            $OptimalValue = $TrialValue

            #  Overwrite the previous optimal solution(s) with the trial solution
            $Solutions  = @( $Solution )
            }

        #  Else if the trial value matches the previous most valuable trial...
       ElseIf ( $TrialValue -eq $OptimalValue )
            {
            #  Add the trial solution to the list of optimal solutions
            $Solutions += @( $Solution )
            }
        }
    }

#  Show the results
$Solutions

determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.


for ($i = 1; $i -le 10; $i++) {
    Write-Host -NoNewLine $i
    if ($i -eq 10) {
        Write-Host
        break
    }
    Write-Host -NoNewLine ", "
}

switch (1..10) {
    { $true }     { Write-Host -NoNewLine $_ }
    { $_ -lt 10 } { Write-Host -NoNewLine ", " }
    { $_ -eq 10 } { Write-Host }
}

The code outputs a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within a loop structure. An alternative solution uses a switch statement to iterate over the given range.


#Input Data
$a=@"
des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01             ieee dw01 dware gtech
dw02             ieee dw02 dware
dw03             std synopsys dware dw03 dw02 dw01 ieee gtech
dw04             dw04 ieee dw01 dware gtech
dw05             dw05 ieee dware
dw06             dw06 ieee dware
dw07             ieee dware
dware            ieee dware
gtech            ieee gtech
ramlib           std ieee
std_cell_lib     ieee std_cell_lib
synopsys
"@
#Convert to Object[]
$c = switch ( $a.split([char] 10) ) {
    $_ {
        $b=$_.split(' ')
        New-Object PSObject -Property @{
            Library = $b[0]
            "Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
        }
    }
}
#Add pure dependencies
$c | ForEach-Object {
    $_."Library Dependencies" | Where-Object {
        $d=$_
        $(:andl foreach($i in $c) {
            if($d -match $i.Library) {
                $false
                break andl
            }
        }) -eq $null
    } | ForEach-Object {
        $c+=New-Object PSObject -Property @{
            Library=$_
            "Library Dependencies"=@()
        }
    }
}
#Associate with a dependency value
##Initial Dependency Value
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
    Name="Dep Value"
    Expression={
        1
    }
}
##Modify Dependency Value, perform check for incorrect dependency
##Dep Value is determined by a parent child relationship, if a library is a parent, all libraries dependant on it are children
for( $i=0; $i -lt $d.count; $i++ ) {
    $errmsg=""
    foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
        #Foreach other Child Library where this is a dependency, increase the Dep Value of the Child
        if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
            if( $k -match $d[$i].Library ) {
                foreach( $n in $d[$i]."Library Dependencies" ) {
                    if( $n -match $d[$j].Library ) {
                        $errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
                        break
                    }
                }
                $true
                break orl
            }
        } ) ) {
            #If the child has already been processed, increase the Dep Value of its children
            if( $j -lt $i ) {
                foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
                    if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
                        if( $m -match $d[$j].Library ) {
                            $true
                            break orl2
                        }
                    } ) ) {
                        $d[$l]."Dep Value"+=$d[$i]."Dep Value"
                    }
                }
            }
            $d[$j]."Dep Value"+=$d[$i]."Dep Value"
        }
        if( $errmsg -ne "" ) {
            $errmsg
            $d=$null
            break
        }
    }
}
#Sort and Display
if( $d ) {
    $d | Sort "Dep Value",Library | ForEach-Object {
        "{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
    } {
        "{0,-14} $($_."Library Dependencies")" -f $_.Library
    }
}

The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.


"spicywiener".StartsWith("spicy")
"spicywiener".Contains("icy")
"spicywiener".EndsWith("wiener")
"spicywiener".IndexOf("icy")
[regex]::Matches("spicywiener", "i").count

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


function triples($p) {
    if($p -gt 4) {
        # ai + bi + ci = pi <= p
        # ai < bi < ci --> 3ai < pi <= p and ai + 2bi < pi <= p
        $pa = [Math]::Floor($p/3)
        1..$pa | foreach {
            $ai = $_
            $pb = [Math]::Floor(($p-$ai)/2)
            ($ai+1)..$pb | foreach {
                $bi = $_
                $pc = $p-$ai-$bi
                ($bi+1)..$pc | where {
                    $ci = $_
                    $pi = $ai + $bi + $ci
                    $ci*$ci -eq $ai*$ai + $bi*$bi
                 } |
                foreach {
                    [pscustomobject]@{
                        a = "$ai"
                        b = "$bi"
                        c = "$ci"
                        p = "$pi"
                    }
                }
            }
        }
    }
    else {
        Write-Error "$p is not greater than 4"
    }
}
function gcd ($a, $b)  {
    function pgcd ($n, $m)  {
        if($n -le $m) {
            if($n -eq 0) {$m}
            else{pgcd $n ($m%$n)}
        }
        else {pgcd $m $n}
    }
    $n = [Math]::Abs($a)
    $m = [Math]::Abs($b)
    (pgcd $n $m)
}
$triples = (triples 100)

$coprime = $triples |
where {((gcd $_.a $_.b) -eq 1) -and ((gcd $_.a $_.c) -eq 1) -and  ((gcd $_.b $_.c) -eq 1)}

"There are $(($triples).Count) Pythagorean triples with perimeter no larger than 100
 and $(($coprime).Count) of them are coprime."

There are 17 Pythagorean triples with perimeter no larger than 100 and 7 of them are coprime.

"Calculate the number of Pythagorean triples with a perimeter no larger than 100 and count how many of these are primitive. The program should also be capable of handling large perimeter values up to 100,000,000."


Library: WPK
New-Window -Show

Library: Windows Forms
$form = New-Object Windows.Forms.Form
$form.Text = "A Window"
$form.Size = New-Object Drawing.Size(150,150)
$form.ShowDialog() | Out-Null

"Creates an empty GUI window that can respond to close requests."


Open a text file, count the frequency of each letter from A to Z, and optionally include punctuation characters.


function Get-Factor ($a) {
    1..$a | Where-Object { $a % $_ -eq 0 }
}

function Get-Factor ($a) {
    1..[Math]::Sqrt($a) `
        | Where-Object { $a % $_ -eq 0 } `
        | ForEach-Object { $_; $a / $_ } `
        | Sort-Object -Unique
}

calculate the factors of a given positive integer. The factors are the positive integers that can divide the input number to give a positive integer result. The code does not handle zero or negative integers. It uses a range of integers up to the square root of the input number for efficiency. It filters out the factors and calculates the corresponding larger factors, returning all factors of the input number.


$file =
@'
Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.
'@.Split("`n")

$arr = @()
$file | foreach {
    $line = $_
    $i = 0
    $hash = [ordered]@{}
    $line.split('$') | foreach{
        $hash["$i"] = "$_"
        $i++
     }
    $arr += @([pscustomobject]$hash)
}
$arr | Format-Table -HideTableHeaders -Wrap *

Given      a          text       file   of     many      lines,     where    fields  within   a      line
are        delineated by         a      single 'dollar'  character, write    a       program
that       aligns     each       column of     fields    by         ensuring that    words    in     each
column     are        separated  by     at     least     one        space.
Further,   allow      for        each   word   in        a          column   to      be       either left
justified, right      justified, or     center justified within     its      column.

"Code reads a text file with lines separated by dollar characters. It aligns each column of words by adding at least one space between them and allows for left, right, or center justification within each column. The code also handles trailing dollar characters, ensures all columns share the same alignment, and disregards consecutive spaces at the end of lines. The minimum space between columns is computed from the text, not hard-coded, and there's no need to add separating characters between or around columns."


$e = "This is a test Guvf vf n grfg"

[char[]](0..64+78..90+65..77+91..96+110..122+97..109+123..255)[[char[]]$e] -join ""

function Invoke-Rot13 {
  param(
    [char[]]$message
  )
  begin {
    $outString = New-Object System.Collections.ArrayList
    $alpha = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
    $alphaL = $alpha + $alpha
    $alphaU = $alphaL.toUpper()
    $int = 13
  }
  process{
    $message | ForEach-Object {
      # test if char is special
      if ($_ -match '[^\p{L}\p{Nd}]') {
        $outString += $_
      }
      # test if char is digit
      elseif ($_ -match '\d') {
        $outString += $_
      }
      # test if char is upperCase
      elseif ($_ -ceq $_.ToString().ToUpper()) {
        $charIndex = $alphaU.IndexOf($_.tostring())
        $outString += $alphaU[$charIndex+$int]
      }
      # test if char is lowerCase
      elseif ($_ -ceq $_.ToString().ToLower()) {
        $charIndex = $alphaL.IndexOf($_.tostring())
        $outString += $alphaL[$charIndex+$int]
      }
      else {
        $outString += $_
      }
    } # end foreach
  } # end process
  end {
    # output string and join all chars
    $outString -join ""
  }
} # end function

PS> $message = '{!This is /A\ Test123}'
PS> $messageE = Invoke-Rot13 -message $message
PS> $messageE
PS> Invoke-Rot13 -message $messageE
{!Guvf vf /N\ Grfg123}
{!This is /A\ Test123}

The code implements a rot-13 function that encodes every line of input from a file or standard input. It replaces every letter of the ASCII alphabet with the letter rotated 13 characters around the 26 letter alphabet. The function works on both upper and lower case letters, preserves case, and passes all non-alphabetic characters without alteration. It can be wrapped in a utility program similar to a common UNIX utility.


Works with: PowerShell version 4.0
$list = @{
"def" = "one"
"abc" = "two"
"jkl" = "three"
"abcdef" = "four"
"ghi" = "five"
"ghijkl" = "six"
 }
 $list.GetEnumerator() | sort {-($PSItem.Name).length}, Name

Name                           Value
----                           -----
abcdef                         four
ghijkl                         six
abc                            two
def                            one
ghi                            five
jkl                            three

sort an array of composite structures, specifically name-value pairs, by the key 'name' using a custom comparator.


for ($i = 1; $i -le 5; $i++) {
    for ($j = 1; $j -le $i; $j++) {
        Write-Host -NoNewline *
    }
    Write-Host
}

1..5 | ForEach-Object {
    1..$_ | ForEach-Object {
        Write-Host -NoNewline *
    }
    Write-Host
}

demonstrate how to use nested for loops to print a specific pattern. The number of iterations of the inner loop is controlled by the outer loop. The pattern consists of increasing number of asterisks on each line. The same result can also be achieved using the range operator and ForEach-Object cmdlet, replacing the inner loop with "*" * $_.


$hashtable = @{}

$hashtable = @{
    "key1" = "value 1"
    key2 = 5            # if the key name has no spaces, no quotes are needed.
}

$hashtable.foo    = "bar"
$hashtable['bar'] = 42
$hashtable."a b"  = 3.14  # keys can contain spaces, property-style access needs quotation marks, then
$hashtable[5]     = 8     # keys don't need to be strings

# Case insensitive keys, both end up as the same key:
$h=@{}
$h['a'] = 1
$h['A'] = 2
$h

Name                           Value
----                           -----
a                              2

# Case sensitive keys:
$h = New-Object -TypeName System.Collections.Hashtable
$h['a'] = 1
$h['A'] = 2
$h

Name                           Value
----                           -----
A                              2
a                              1

$hashtable.key1     # value 1
$hashtable['key2']  # 5

$obj = [PSCustomObject]@{
    "key1" = "value 1"
    key2 = 5
}

create and manipulate an associative array or hashtable. The codes initialize the hashtable with key/value pairs, assign or replace individual values using a property-style access method or indexing, and retrieve values. They also handle case-insensitive string comparison in PowerShell. Additionally, they demonstrate the creation of an object using a hashtable literal, which is a more efficient method.


Function msstate{
    Param($current_seed)
    Return (214013*$current_seed+2531011)%2147483648}

Function randMS{
    Param($MSState)
    Return [int]($MSState/65536)}

Function randBSD{
    Param($BSDState)
    Return (1103515245*$BSDState+12345)%2147483648}

Write-Host "MS: seed=0"
$seed=0 #initialize seed
For($i=1;$i-le5;$i++){
    $seed = msstate($seed)
    $rand = randMS($seed)
    Write-Host $rand}

Write-Host "BSD: seed=0"
$seed=0 #initialize seed
For($j=1;$j-le5;$j++){
    $seed = randBSD($seed)
    Write-Host $seed}

The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.


function isEven {
	param ([int]$value)
	return [bool]($value % 2 -eq 0)
}

function doubleValue {
	param ([int]$value)
	return [int]($value * 2)
}

function halveValue {
	param ([int]$value)
	return [int]($value / 2)
}

function multiplyValues {
	param (
		[int]$plier,
		[int]$plicand,
		[int]$temp = 0
	)

	while ($plier -ge 1)
	{
		if (!(isEven $plier)) {
			$temp += $plicand
		}
		$plier = halveValue $plier
		$plicand = doubleValue $plicand
	}

return $temp
}

multiplyValues 17 34

function halveInt( [int] $rhs )
{
	[math]::floor( $rhs / 2 )
}

function doubleInt( [int] $rhs )
{
	$rhs*2
}

function isEven( [int] $rhs )
{
	-not ( $_ % 2 )
}

function Ethiopian( [int] $lhs , [int] $rhs )
{
	$scratch = @{}
	1..[math]::floor( [math]::log( $lhs , 2 ) + 1 ) |
	ForEach-Object {
		$scratch[$lhs] = $rhs
		$lhs
		$lhs = halveInt( $lhs )
		$rhs = doubleInt( $rhs ) } |
	Where-Object { -not ( isEven $_ ) } |
	ForEach-Object { $sum = 0 } { $sum += $scratch[$_] } { $sum }
}

Ethiopian 17 34

The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two numbers using only addition, doubling, and halving operations. The multiplication process involves repeatedly halving the first number and doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column to get the product.


function Get-Factorial ($x) {
    if ($x -eq 0) {
        return 1
    }
    return $x * (Get-Factorial ($x - 1))
}
function Get-Factorial ($x) {
    if ($x -eq 0) {
        return 1
    } else {
        $product = 1
        1..$x | ForEach-Object { $product *= $_ }
        return $product
    }
}
Works with: PowerShell version 2

function Get-Factorial ($x) {
    if ($x -eq 0) {
        return 1
    }
    return (Invoke-Expression (1..$x -join '*'))
}

"Function to calculate and return the factorial of a given number, either through iterative or recursive methods. The function optionally includes error handling for negative input values."


[int]$guesses = $bulls = $cows = 0
[string]$guess = "none"
[string]$digits = ""

while ($digits.Length -lt 4)
{
    $character = [char](49..57 | Get-Random)

    if ($digits.IndexOf($character) -eq -1) {$digits += $character}
}

Write-Host "`nGuess four digits (1-9) using no digit twice.`n" -ForegroundColor Cyan

while ($bulls -lt 4)
{
    do
    {
        $prompt = "Guesses={0:0#}, Last='{1,4}', Bulls={2}, Cows={3}; Enter your guess" -f $guesses, $guess, $bulls, $cows
        $guess = Read-Host $prompt

        if ($guess.Length -ne 4)                     {Write-Host "`nMust be a four-digit number`n" -ForegroundColor Red}
        if ($guess -notmatch "[1-9][1-9][1-9][1-9]") {Write-Host "`nMust be numbers 1-9`n"         -ForegroundColor Red}
    }
    until ($guess.Length -eq 4)

    $guesses += 1
    $bulls = $cows = 0

    for ($i = 0; $i -lt 4; $i++)
    {
        $character = $digits.Substring($i,1)

        if ($guess.Substring($i,1) -eq $character)
        {
            $bulls += 1
        }
        else
        {
            if ($guess.IndexOf($character) -ge 0)
            {
                $cows += 1
            }
        }
    }
}

Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan

generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.


function Get-RandomNormal
    {
    [CmdletBinding()]
    Param ( [double]$Mean, [double]$StandardDeviation )

    $RandomNormal = $Mean + $StandardDeviation * [math]::Sqrt( -2 * [math]::Log( ( Get-Random -Minimum 0.0 -Maximum 1.0 ) ) ) * [math]::Cos( 2 * [math]::PI * ( Get-Random -Minimum 0.0 -Maximum 1.0 ) )

    return $RandomNormal
    }

#  Standard deviation function for testing
function Get-StandardDeviation
    {
    [CmdletBinding()]
    param ( [double[]]$Numbers )

    $Measure = $Numbers | Measure-Object -Average
    $PopulationDeviation = 0
    ForEach ($Number in $Numbers) { $PopulationDeviation += [math]::Pow( ( $Number - $Measure.Average ), 2 ) }
    $StandardDeviation = [math]::Sqrt( $PopulationDeviation / ( $Measure.Count - 1 ) )
    return $StandardDeviation
    }

#  Test
$RandomNormalNumbers = 1..1000 | ForEach { Get-RandomNormal -Mean 1 -StandardDeviation 0.5 }

$Measure = $RandomNormalNumbers | Measure-Object -Average

$Stats = [PSCustomObject]@{
    Count             = $Measure.Count
    Average           = $Measure.Average
    StandardDeviation = Get-StandardDeviation -Numbers $RandomNormalNumbers
}

$Stats | Format-List

"Generates a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using specific algorithms if only uniformly distributed random numbers can be generated by the libraries."


function dotproduct( $a, $b) {
    $a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res}
}
dotproduct (1..2) (1..2)
dotproduct (1..10) (11..20)

5
935

implement a function to calculate the dot product of two vectors of the same length by multiplying corresponding terms and summing the products.


Get-Content c:\file.txt |
    ForEach-Object {
        $_
    }

ForEach-Object -inputobject (get-content c:\file.txt) {$_}

"Reads data from a text stream either word-by-word or line-by-line until the end of the stream, which has an unknown amount of data."


Using a cmdlet:Get-Date
or using .NET classes and properties:[DateTime]::Now

the system time in a specified unit. This can be utilized for debugging, network information, generating random number seeds, or tracking program performance. The code may use a system command or a built-in language function to achieve this. The related task involves formatting the date.


function Add-SEDOLCheckDigit
    {
    Param ( #  Validate input as six-digit SEDOL number
            [ValidatePattern( "^[0123456789bcdfghjklmnpqrstvwxyz]{6}$" )]
            [parameter ( Mandatory = $True ) ]
            [string]
            $SixDigitSEDOL )

    #  Convert to array of single character strings, using type char as an intermediary
    $SEDOL = [string[]][char[]]$SixDigitSEDOL

    #  Define place weights
    $Weight = @( 1, 3, 1, 7, 3, 9 )

    #  Define character values (implicit in 0-based location within string)
    $Characters = "0123456789abcdefghijklmnopqrstuvwxyz"

    $CheckSum = 0

    #  For each digit, multiply the character value by the weight and add to check sum
    0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] }

    #  Derive the check digit from the partial check sum
    $CheckDigit = ( 10 - $CheckSum % 10 ) % 10

    #  Return concatenated result
    return ( $SixDigitSEDOL + $CheckDigit )
    }

#  Test
$List = @(
    "710889"
    "B0YBKJ"
    "406566"
    "B0YBLH"
    "228276"
    "B0YBKL"
    "557910"
    "B0YBKR"
    "585284"
    "B0YBKT"
    "B00030"
    )

ForEach ( $PartialSEDOL in $List )
    {
    Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL
    }

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.


function nth($inp){
    $suffix = "th"

    switch($inp % 100){
        11{$suffix="th"}
        12{$suffix="th"}
        13{$suffix="th"}
        default{
            switch($inp % 10){
                1{$suffix="st"}
                2{$suffix="nd"}
                3{$suffix="rd"}
            }
        }
    }
    return "$inp$suffix "
}

0..25 | %{Write-host -nonewline (nth "$_")};""
250..265 | %{Write-host -nonewline (nth "$_")};""
1000..1025 | %{Write-host -nonewline (nth "$_")};""

The code generates a string representation of an integer with its ordinal suffix. It takes an integer greater than or equal to zero as input and returns the number followed by an apostrophe and its ordinal suffix. The function is tested with ranges of integer inputs: 0..25, 250..265, 1000..1025.


$limit = 20
$data  = @("3 Fizz","5 Buzz","7 Baxx")
	#An array with whitespace as the delimiter
	#Between the factor and the word

for ($i = 1;$i -le $limit;$i++){
	$outP = ""
	foreach ($x in $data){
		$data_split = $x -split " "	#Split the "<factor> <word>"
		if (($i % $data_split[0]) -eq 0){
			$outP += $data_split[1]	#Append the <word> to outP
		}
	}
	if(!$outP){	#Is outP equal to NUL?
		Write-HoSt $i
	} else {
		Write-HoSt $outP
	}
}

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


$str = "World!"
$str = "Hello, " + $str
$str

Hello, World!

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


Library: turtle
# handy constants with script-wide scope
[Single]$script:QUARTER_PI=0.7853982
[Single]$script:HALF_PI=1.570796

# leverage GDI (Forms and Drawing)
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
$script:TurtlePen = New-Object Drawing.Pen darkGreen
$script:Form = New-Object Windows.Forms.Form
$script:Canvas = $Form.CreateGraphics()

# implement a turtle graphics model
Class Turtle { # relies on the script-scoped $TurtlePen and $Canvas
  # member properties for turtle's position and orientation
  [Single]$TurtleX
  [Single]$TurtleY
  [Single]$TurtleAngle

  # constructors
  Turtle() {
    $this.TurtleX, $this.TurtleY = 44.0, 88.0
    $this.TurtleAngle = 0.0
  }
  Turtle([Single]$InitX, [Single]$InitY, [Single]$InitAngle) {
    $this.TurtleX, $this.TurtleY = $InitX, $InitY
    $this.TurtleAngle = $InitAngle
  }

  # methods for turning and drawing
  [Void]Turn([Single]$Angle) {  # $Angle measured in radians
    $this.TurtleAngle += $Angle  # use positive $Angle for right turn, negative for left turn
  }
  [Void]Forward([Single]$Distance) {
    # draw line segment
    $TargetX = $this.TurtleX + $Distance * [Math]::Cos($this.TurtleAngle)
    $TargetY = $this.TurtleY + $Distance * [Math]::Sin($this.TurtleAngle)
    $script:Canvas.DrawLine($script:TurtlePen, $this.TurtleX, $this.TurtleY, $TargetX, $TargetY)
    # relocate turtle to other end of segment
    $this.TurtleX = $TargetX
    $this.TurtleY = $TargetY
  }
} # end of Turtle class definition

# Implement dragon curve drawing methods in a subclass that inherits Turtle
Class DragonTurtle : Turtle {

  # DCL: recursive dragon curve, starting with left turns
  [Void]DCL([Byte]$Step, [Single]$Length) {
    $AdjustedStep = $Step - 1
    $AdjustedLength = $Length / [Math]::Sqrt(2.0)

    $this.Turn(-$script:QUARTER_PI)
    if ($AdjustedStep -gt 0) {
      $this.DCR($AdjustedStep, $AdjustedLength)
    } else {
      $this.Forward($AdjustedLength)
    }
    $this.Turn($script:HALF_PI)
    if ($AdjustedStep -gt 0) {
      $this.DCL($AdjustedStep, $AdjustedLength)
    } else {
      $this.Forward($AdjustedLength)
    }
    $this.Turn(-$script:QUARTER_PI)
  }

  # DCR: recursive dragon curve, starting with right turns
  [Void]DCR([Byte]$Step, [Single]$Length) {
    $AdjustedStep = $Step - 1
    $AdjustedLength = $Length / [Math]::Sqrt(2.0)

    $this.Turn($script:QUARTER_PI)
    if ($AdjustedStep -gt 0) {
      $this.DCR($AdjustedStep, $AdjustedLength)
    } else {
      $this.Forward($AdjustedLength)
    }
    $this.Turn(-$script:HALF_PI)
    if ($AdjustedStep -gt 0) {
      $this.DCL($AdjustedStep, $AdjustedLength)
    } else {
      $this.Forward($AdjustedLength)
    }
    $this.Turn($script:QUARTER_PI)
  }
} # end of DragonTurtle subclass definition

# prepare anonymous dragon-curve painting function for WinForms dialog
$Form.add_paint({
  [DragonTurtle]$Dragon = [DragonTurtle]::new()
  $Dragon.DCR(14,128)
})

# display the GDI Form window, which triggers its prepared anonymous drawing function
$Form.ShowDialog()

generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.


Function GuessNumber($Guess)
{
    $Number = Get-Random -min 1 -max 11
    Write-Host "What number between 1 and 10 am I thinking of?"
        Do
        {
        Write-Warning "Try again!"
        $Guess = Read-Host "What's the number?"
        }
        While ($Number -ne $Guess)
    Write-Host "Well done! You successfully guessed the number $Guess."
}

$myNumber = Read-Host "What's the number?"
GuessNumber $myNumber

The code generates a random number between 1 and 10. It then prompts the user to guess the number. If the guess is incorrect, the user is prompted to guess again. This process continues until the user guesses the correct number, at which point the program displays a "Well guessed!" message and terminates. A conditional loop is used to facilitate repeated guessing until the correct number is identified. The code also includes a function that analyzes the provided number each time it is called.


$asString = 97..122 | ForEach-Object -Begin {$asArray = @()} -Process {$asArray += [char]$_} -End {$asArray -join('')}
$asString

generate a sequence of all lowercase ASCII characters from 'a' to 'z'. The sequence can be in the form of an array, list, lazy sequence, or an indexable string. The code should be written in a robust and reliable style, suitable for a large program, and should use strong typing if available. The code should avoid manually enumerating all the lowercase characters to prevent bugs. The code should be clear and easy to understand during a code review. An alternative method for PowerShell-v6.0.0rc is also provided.


Library: Microsoft .NET Framework
@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


function Read-ConfigurationFile
{
    [CmdletBinding()]
    Param
    (
        # Path to the configuration file.  Default is "C:\ConfigurationFile.cfg"
        [Parameter(Mandatory=$false, Position=0)]
        [string]
        $Path = "C:\ConfigurationFile.cfg"
    )

    [string]$script:fullName = ""
    [string]$script:favouriteFruit = ""
    [bool]$script:needsPeeling = $false
    [bool]$script:seedsRemoved = $false
    [string[]]$script:otherFamily = @()

    function Get-Value ([string]$Line)
    {
        if ($Line -match "=")
        {
            [string]$value = $Line.Split("=",2).Trim()[1]
        }
        elseif ($Line -match " ")
        {
            [string]$value = $Line.Split(" ",2).Trim()[1]
        }

        $value
    }

    # Process each line in file that is not a comment.
    Get-Content $Path | Select-String -Pattern "^[^#;]" | ForEach-Object {

        [string]$line = $_.Line.Trim()

        if ($line -eq [String]::Empty)
        {
            # do nothing for empty lines
        }
        elseif ($line.ToUpper().StartsWith("FULLNAME"))
        {
            $script:fullName = Get-Value $line
        }
        elseif ($line.ToUpper().StartsWith("FAVOURITEFRUIT"))
        {
            $script:favouriteFruit = Get-Value $line
        }
        elseif ($line.ToUpper().StartsWith("NEEDSPEELING"))
        {
            $script:needsPeeling = $true
        }
        elseif ($line.ToUpper().StartsWith("SEEDSREMOVED"))
        {
            $script:seedsRemoved = $true
        }
        elseif ($line.ToUpper().StartsWith("OTHERFAMILY"))
        {
            $script:otherFamily = (Get-Value $line).Split(',').Trim()
        }
    }

    Write-Verbose -Message ("{0,-15}= {1}" -f "FULLNAME", $script:fullName)
    Write-Verbose -Message ("{0,-15}= {1}" -f "FAVOURITEFRUIT", $script:favouriteFruit)
    Write-Verbose -Message ("{0,-15}= {1}" -f "NEEDSPEELING", $script:needsPeeling)
    Write-Verbose -Message ("{0,-15}= {1}" -f "SEEDSREMOVED", $script:seedsRemoved)
    Write-Verbose -Message ("{0,-15}= {1}" -f "OTHERFAMILY", ($script:otherFamily -join ", "))
}

Read-ConfigurationFile -Path .\temp.txt -Verbose

The code reads a configuration file in standard format from ".\temp.txt", ignoring lines beginning with a hash or semicolon and blank lines. It sets variables based on the configuration entries, with four specific variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' being set to specific values. An additional option with multiple parameters is stored in an array 'otherfamily'. The code tests if the variables are set and displays them if the -Verbose switch is used.


Works with: PowerShell version 3
Add-Type -AssemblyName System.Device

$BNA = New-Object System.Device.Location.GeoCoordinate 36.12, -86.67
$LAX = New-Object System.Device.Location.GeoCoordinate 33.94, -118.40

$BNA.GetDistanceTo( $LAX ) / 1000

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


$wc = New-Object Net.WebClient
$wc.DownloadString('http://www.rosettacode.org')

Print the content of a specified URL to the console using HTTP request.


function Test-LuhnNumber
{
  <#
    .SYNOPSIS
        Tests validity of credit card numbers.
    .DESCRIPTION
        Tests validity of credit card numbers using the Luhn test.
    .PARAMETER Number
        The number must be 11 or 16 digits.
    .EXAMPLE
        Test-LuhnNumber 49927398716
    .EXAMPLE
        [int64[]]$numbers = 49927398716, 49927398717, 1234567812345678, 1234567812345670
        C:\PS>$numbers | ForEach-Object {
                  "{0,-17}: {1}" -f $_,"$(if(Test-LuhnNumber $_) {'Is valid.'} else {'Is not valid.'})"
              }
  #>
    [CmdletBinding()]
    [OutputType([bool])]
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [ValidateScript({$_.Length -eq 11 -or $_.Length -eq 16})]
        [ValidatePattern("^\d+$")]
        [string]
        $Number
    )

    $digits = ([Regex]::Matches($Number,'.','RightToLeft')).Value

    $digits |
        ForEach-Object `
               -Begin   {$i = 1} `
               -Process {if ($i++ % 2) {$_}} |
        ForEach-Object `
               -Begin   {$sumOdds = 0} `
               -Process {$sumOdds += [Char]::GetNumericValue($_)}
    $digits |
        ForEach-Object `
               -Begin   {$i = 0} `
               -Process {if ($i++ % 2) {$_}} |
        ForEach-Object `
               -Process {[Char]::GetNumericValue($_) * 2} |
        ForEach-Object `
               -Begin   {$sumEvens = 0} `
               -Process {
                            $_number = $_.ToString()
                            if ($_number.Length -eq 1)
                            {
                                $sumEvens += [Char]::GetNumericValue($_number)
                            }
                            elseif ($_number.Length -eq 2)
                            {
                                $sumEvens += [Char]::GetNumericValue($_number[0]) + [Char]::GetNumericValue($_number[1])
                            }
                        }

    ($sumOdds + $sumEvens).ToString()[-1] -eq "0"
}
Test-LuhnNumber 49927398716

The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


Works with: PowerShell version 2

function Get-JosephusPrisoners ( [int]$N, [int]$K )
    {
    #  Just for convenience
    $End = $N - 1

    #  Create circle of prisoners
    $Prisoners = New-Object System.Collections.ArrayList ( , (0..$End) )

    #  For each starting point of the reducing circle...
    ForEach ( $Start in 0..($End - 1) )
        {
        #  We subtract one from K for the one we advanced by incrementing $Start
        #  Then take K modulus the length of the remaining circle
        $RoundK = ( $K - 1 ) % ( $End - $Start + 1 )

        #  Rotate the remaining prisoners K places around the remaining circle
        $Prisoners.SetRange( $Start, $Prisoners[ $Start..$End ][ ( $RoundK + $Start - $End - 1 )..( $RoundK - 1 ) ] )
        }
    return $Prisoners
    }

#  Get the prisoner order for a circle of 41 prisoners, selecting every third
$Prisoners = Get-JosephusPrisoners -N 41 -K 3

#  Display the prisoner order
$Prisoners -join " "

#  Display the last remaining prisoner
"Last prisoner remmaining: " + $Prisoners[-1]

#  Display the last three remaining prisoners
$S = 3
"Last $S remaining: " + $Prisoners[-$S..-1]

The code implements the Josephus problem, where given 'n' prisoners and 'k' as the step count, it determines the final survivor. It also provides a way to calculate which prisoner is at any given position on the killing sequence. The code follows an iterative algorithm, rotating the circle of prisoners equivalent to the executioner walking around, and selects the next prisoner to be executed. It also handles the scenario where multiple survivors are allowed.


The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is "ha" and 5, the output will be "hahahahaha". Similarly, if the input is "*" and 5, the output will be "*****".


"I am a string" -match '\bstr'       # true
"I am a string" -replace 'a\b','no'  # I am no string

utilize regular expressions to match and substitute parts of a string. The -match and -replace operators are used by default, which are case-insensitive. However, case-sensitive operations can be achieved using the -cmatch and -creplace operators.


$a = [int] (Read-Host First Number)
$b = [int] (Read-Host Second Number)

Write-Host "Sum:                              $($a + $b)"
Write-Host "Difference:                       $($a - $b)"
Write-Host "Product:                          $($a * $b)"
Write-Host "Quotient:                         $($a / $b)"
Write-Host "Quotient, round to even:          $([Math]::Round($a / $b))"
Write-Host "Remainder, sign follows first:    $($a % $b)"

[Math]::Pow($a, $b)

take two integers as input from the user, calculate and display their sum, difference, product, integer quotient, remainder, and exponentiation (if possible). The code does not include error handling. It specifies the rounding direction for the quotient and the sign of the remainder. It also includes an example of the 'divmod' operator. The code automatically converts numbers to accommodate the result, expanding Int32 to Int64 or converting to a floating-point type for non-integer quotients. The remainder carries the sign of the first operand. The code uses .NET BCL to perform exponentiation if no operator exists.


Works with: PowerShell version 4.0
[regex]::Matches("the three truths", "th").count

3

[regex]::Matches("ababababab","abab").count

2

The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the string to be searched and the substring to look for. It returns an integer representing the count of non-overlapping occurrences. The matching is done either from left-to-right or right-to-left to yield the highest number of non-overlapping matches.


Works with: PowerShell version 4.0
function hanoi($n, $a,  $b, $c) {
    if($n -eq 1) {
        "$a -> $c"
    } else{
         hanoi ($n - 1) $a $c $b
         hanoi 1 $a $b $c
         hanoi ($n - 1) $b $a $c
    }
}
hanoi 3 "A" "B" "C"

A -> C
A -> B
C -> B
A -> C
B -> A
B -> C
A -> C

"Implement a recursive solution to solve the Towers of Hanoi problem."


function choose($n,$k) {
    if($k -le $n -and 0 -le $k) {
        $numerator = $denominator = 1
        0..($k-1) | foreach{
            $numerator *= ($n-$_)
            $denominator *= ($_ + 1)
        }
        $numerator/$denominator
    } else {
        "$k is greater than $n or lower than 0"
    }
}
choose 5 3
choose 2 1
choose 10 10
choose 10 2
choose 10 8

10
2
1
45
45

The code calculates any binomial coefficient, with a specific emphasis on outputting the binomial coefficient of 5 choose 3, which equals 10. It uses the formula for binomial coefficients and includes tasks for combinations, permutations, combinations with repetitions, and permutations with repetitions. The code also handles cases where order is important or unimportant, and with or without replacement.


implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


$s = "Hëlló Wørłð"
$s.Length
$s = "Hëlló Wørłð"
[System.Text.Encoding]::Unicode.GetByteCount($s)

[System.Text.Encoding]::UTF8.GetByteCount($s)

The code calculates the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It handles Unicode code points correctly, including Non-BMP code points, providing the actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if the language supports it.


function Get-RandomInteger
{
    Param
    (
        [Parameter(Mandatory=$false,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [ValidateScript({$_ -ge 4})]
        [int[]]
        $InputObject = 64
    )

    Begin
    {
        $rng = New-Object -TypeName System.Security.Cryptography.RNGCryptoServiceProvider
    }
    Process
    {
        foreach($count in $InputObject)
        {
            $bytes = New-Object -TypeName Byte[] -Argument $count
            $rng.GetBytes($bytes)
            [System.BitConverter]::ToInt32($bytes,0)
        }
    }
    End
    {
        Remove-Variable -Name rng -Scope Local
    }
}

4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {$_} -Column 6 -Force

demonstrate how to generate a random 32-bit number using a system's built-in mechanism, not just a software algorithm like /dev/urandom devices in Unix. The generated number is also presented in hexadecimal format.


Works with: PowerShell version 4.0
$string = "top and tail"
$string
$string.Substring(1)
$string.Substring(0, $string.Length - 1)
$string.Substring(1, $string.Length - 2)

$string = "top and tail"
$string
$string[1..($string.Length - 1)] -join ""
$string[0..($string.Length - 2)] -join ""
$string[1..($string.Length - 2)] -join ""

top and tail
op and tail
top and tai
op and tai

demonstrate how to remove the first, last, or both characters from a string, accounting for any valid Unicode code point in UTF-8 or UTF-16 encoding. The program references logical characters, not 8-bit or 16-bit code units.


if (Get-Process -Name "notepad" -ErrorAction SilentlyContinue)
{
    Write-Warning -Message "notepad is already running."
}
else
{
    Start-Process -FilePath C:\Windows\notepad.exe
}

The code checks if an instance of an application is already running. If so, it displays a warning message and exits. If not, it starts the application.


Works with: PowerShell version 3
$A = 1, 2, 3, 4, 5
Get-Random $A -Count $A.Count
Works with: PowerShell version 2
function shuffle ($a) {
    $c = $a.Clone()  # make copy to avoid clobbering $a
    1..($c.Length - 1) | ForEach-Object {
        $i = Get-Random -Minimum $_ -Maximum $c.Length
        $c[$_-1],$c[$i] = $c[$i],$c[$_-1]
        $c[$_-1]  # return newly-shuffled value
    }
    $c[-1]  # last value
}

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. It can be modified to return a new shuffled array if in-place modification is not possible. The algorithm can also be adjusted to iterate from left to right if needed. The function takes an array as input and returns a shuffled array.


function last-dayofweek {
    param(
     [Int][ValidatePattern("[1-9][0-9][0-9][0-9]")]$year,
     [String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek
    )
    $date = (Get-Date -Year $year -Month 1 -Day 1)
    while($date.DayOfWeek -ne $dayofweek) {$date = $date.AddDays(1)}
    while($date.year -eq $year) {
        if($date.Month -ne $date.AddDays(7).Month) {$date.ToString("yyyy-dd-MM")}
        $date = $date.AddDays(7)
    }
}
last-dayofweek 2012 "Friday"

2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28

function Get-Date0fDayOfWeek
{
    [CmdletBinding(DefaultParameterSetName="None")]
    [OutputType([datetime])]
    Param
    (
        [Parameter(Mandatory=$false,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [ValidateRange(1,12)]
        [int]
        $Month = (Get-Date).Month,

        [Parameter(Mandatory=$false,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
        [ValidateRange(1,9999)]
        [int]
        $Year = (Get-Date).Year,

        [Parameter(Mandatory=$true, ParameterSetName="Sunday")]
        [switch]
        $Sunday,

        [Parameter(Mandatory=$true, ParameterSetName="Monday")]
        [switch]
        $Monday,

        [Parameter(Mandatory=$true, ParameterSetName="Tuesday")]
        [switch]
        $Tuesday,

        [Parameter(Mandatory=$true, ParameterSetName="Wednesday")]
        [switch]
        $Wednesday,

        [Parameter(Mandatory=$true, ParameterSetName="Thursday")]
        [switch]
        $Thursday,

        [Parameter(Mandatory=$true, ParameterSetName="Friday")]
        [switch]
        $Friday,

        [Parameter(Mandatory=$true, ParameterSetName="Saturday")]
        [switch]
        $Saturday,

        [switch]
        $First,

        [switch]
        $Last,

        [switch]
        $AsString,

        [Parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Format = "dd-MMM-yyyy"
    )

    Process
    {
        [datetime[]]$dates = 1..[DateTime]::DaysInMonth($Year,$Month) | ForEach-Object {
            Get-Date -Year $Year -Month $Month -Day $_ -Hour 0 -Minute 0 -Second 0 |
            Where-Object -Property DayOfWeek -Match $PSCmdlet.ParameterSetName
        }

        if ($First -or $Last)
        {
            if ($AsString)
            {
                if ($First) {$dates[0].ToString($Format)}
                if ($Last)  {$dates[-1].ToString($Format)}
            }
            else
            {
                if ($First) {$dates[0]}
                if ($Last)  {$dates[-1]}
            }
        }
        else
        {
            if ($AsString)
            {
                $dates | ForEach-Object {$_.ToString($Format)}
            }
            else
            {
                $dates
            }
        }
    }
}

1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday

The code takes a year as input and returns the dates of the last Fridays of each month for that year. It accepts both integer and DateTime values for the month and year parameters, and can output the results as DateTime objects or formatted time strings. It also supports pipeline input based on the month parameter.


Write-Host -NoNewLine "Goodbye, "
Write-Host -NoNewLine "World!"

"Display the string 'Goodbye, World!' without appending a newline at the end."


#region Define the Windows Form
[Void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

$Form1 = New-Object System.Windows.Forms.Form
$label1 = New-Object System.Windows.Forms.Label
$label2 = New-Object System.Windows.Forms.Label
$txtInputText = New-Object System.Windows.Forms.TextBox
$txtInputNumber = New-Object System.Windows.Forms.TextBox
$btnAccept = New-Object System.Windows.Forms.Button
$label3 = New-Object System.Windows.Forms.Label
$btnCancel = New-Object System.Windows.Forms.Button
$SuspendLayout
#
# label1
#
$label1.AutoSize = $true
$label1.Location = New-Object System.Drawing.Point(23, 36)
$label1.Name = "label1"
$label1.Size = New-Object System.Drawing.Size(34, 13)
$label1.TabIndex = 0
$label1.Text = "String"
#
# label2
#
$label2.AutoSize = $true
$label2.Location = New-Object System.Drawing.Point(13, 62)
$label2.Name = "label2"
$label2.Size = New-Object System.Drawing.Size(44, 13)
$label2.TabIndex = 1
$label2.Text = "Number"
#
# txtInputText
#
$txtInputText.Location = New-Object System.Drawing.Point(63, 33)
$txtInputText.Name = "txtInputText"
$txtInputText.Size = New-Object System.Drawing.Size(100, 20)
$txtInputText.TabIndex = 0
#
# txtInputNumber
#
$txtInputNumber.Location = New-Object System.Drawing.Point(63, 59)
$txtInputNumber.Name = "txtInputNumber"
$txtInputNumber.Size = New-Object System.Drawing.Size(100, 20)
$txtInputNumber.TabIndex = 1
$txtInputNumber.Text = "75000"
#
# btnAccept
#
$btnAccept.DialogResult = [System.Windows.Forms.DialogResult]::OK
$btnAccept.Location = New-Object System.Drawing.Point(16, 94)
$btnAccept.Name = "btnAccept"
$btnAccept.Size = New-Object System.Drawing.Size(75, 23)
$btnAccept.TabIndex = 2
$btnAccept.Text = "Accept"
$btnAccept.UseVisualStyleBackColor = $true
$btnAccept.add_Click({$rc="Accept"; $Form1.Close()})
#
# label3
#
$label3.AutoSize = $true
$label3.Location = New-Object System.Drawing.Point(13, 9)
$label3.Name = "label3"
$label3.Size = New-Object System.Drawing.Size(173, 13)
$label3.TabIndex = 5
$label3.Text = "Please input a string and a number:"
#
# btnCancel
#
$btnCancel.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$btnCancel.Location = New-Object System.Drawing.Point(97, 94)
$btnCancel.Name = "btnCancel"
$btnCancel.Size = New-Object System.Drawing.Size(75, 23)
$btnCancel.TabIndex = 3
$btnCancel.Text = "Cancel"
$btnCancel.UseVisualStyleBackColor = $true
#
# Form1
#
$Form1.AcceptButton = $btnAccept
$Form1.CancelButton = $btnCancel
$Form1.ClientSize = New-Object System.Drawing.Size(196, 129)
$Form1.ControlBox = $false
$Form1.Controls.Add($btnCancel)
$Form1.Controls.Add($label3)
$Form1.Controls.Add($btnAccept)
$Form1.Controls.Add($txtInputNumber)
$Form1.Controls.Add($txtInputText)
$Form1.Controls.Add($label2)
$Form1.Controls.Add($label1)
$Form1.Name = "Form1"
$Form1.Text = "RosettaCode"

#endregion Define the Windows Form

### Show the input form
$f = $Form1.ShowDialog()
if ( $f -eq [System.Windows.Forms.DialogResult]::Cancel ) { "User selected Cancel" }
else { "User entered `"{0}`" for the text and {1} for the number" -f $txtInputText.Text, $txtInputNumber.Text }

implement a graphical user interface in PowerShell, a .NET language, to input a string and the integer 75000, utilizing the full functionality of the System.Windows.Forms assembly.


# Author: M. McNabb
function Get-CaesarCipher
{
Param
(
[Parameter(
Mandatory=$true,ValueFromPipeline=$true)]
[string]
$Text,

[ValidateRange(1,25)]
[int]
$Key = 1,

[switch]
$Decode
)

begin
{
    $LowerAlpha = [char]'a'..[char]'z'
    $UpperAlpha = [char]'A'..[char]'Z'
}

process
{
    $Chars = $Text.ToCharArray()

    function encode
    {
        param
        (
        $Char,
        $Alpha = [char]'a'..[char]'z'
        )
        $Index = $Alpha.IndexOf([int]$Char)
        $NewIndex = ($Index + $Key) - $Alpha.Length
        $Alpha[$NewIndex]
    }

    function decode
    {
        param
        (
        $Char,
        $Alpha = [char]'a'..[char]'z'
        )
        $Index = $Alpha.IndexOf([int]$Char)
        $int = $Index - $Key
        if ($int -lt 0) {$NewIndex = $int + $Alpha.Length}
        else {$NewIndex = $int}
        $Alpha[$NewIndex]
    }

    foreach ($Char in $Chars)
    {
        if ([int]$Char -in $LowerAlpha)
        {
            if ($Decode) {$Char = decode $Char}
            else {$Char = encode $Char}
        }
        elseif ([int]$Char -in $UpperAlpha)
        {
            if ($Decode) {$Char = decode $Char $UpperAlpha}
            else {$Char = encode $Char $UpperAlpha}
        }

        $Char = [char]$Char
        [string]$OutText += $Char
    }

    $OutText
    $OutText = $null
}
}

Encode:
PS C:\> 'Pack my box with five dozen liquor jugs.' | Get-CaesarCipher -key 3
Sdfn pb era zlwk ilyh grchq oltxru mxjv.

Decode:
PS C:\> 'Sdfn pb era zlwk ilyh grchq oltxru mxjv.' | Get-CaesarCipher -key 3 -Decode
Pack my box with five dozen liquor jugs.

Encode lines of text from a file:
PS C:\> Get-Content C:\Text.txt | Get-CaesarCipher -key 10
Vsxo yxo.
Vsxo dgy!
Vsxo drboo;

implement both encoding and decoding functions for a Caesar cipher. The cipher uses a key between 1 and 25 to rotate the alphabet letters either left or right. The encoding function replaces each letter with the 1st to 25th next letter in the alphabet, looping from Z back to A. The code also includes examples of how to use the cipher. Despite its simplicity, the cipher provides minimal security as it can be easily cracked through frequency analysis or by trying all 25 keys. The Caesar cipher is identical to the Vigenère cipher with a key length of 1 and to the Rot-13 cipher with a key of 13.


function gcd ($a, $b)  {
    function pgcd ($n, $m)  {
        if($n -le $m) {
            if($n -eq 0) {$m}
            else{pgcd $n ($m-$n)}
        }
        else {pgcd $m $n}
    }
    $n = [Math]::Abs($a)
    $m = [Math]::Abs($b)
    (pgcd $n $m)
}
function lcm ($a, $b)  {
    [Math]::Abs($a*$b)/(gcd $a $b)
}
lcm 12 18

function gcd ($a, $b)  {
    function pgcd ($n, $m)  {
        if($n -le $m) {
            if($n -eq 0) {$m}
            else{pgcd $n ($m%$n)}
        }
        else {pgcd $m $n}
    }
    $n = [Math]::Abs($a)
    $m = [Math]::Abs($b)
    (pgcd $n $m)
}
function lcm ($a, $b)  {
    [Math]::Abs($a*$b)/(gcd $a $b)
}
lcm 12 18

36

calculate the least common multiple (LCM) of two integers, m and n. The LCM is the smallest positive integer that is a multiple of both m and n. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m x n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of m and n.


function Get-CheckDigitCUSIP {
    [CmdletBinding()]
    [OutputType([int])]
    Param ( #  Validate input
        [Parameter(Mandatory=$true, Position=0)]
        [ValidatePattern( '^[A-Z0-9@#*]{8}\d$' )] # @#*
        [ValidateScript({$_.Length -eq 9})]
        [string]
        $cusip
    )
    $sum = 0
    0..7 | ForEach { $c = $cusip[$_] ; $v = $null
        if ([Char]::IsDigit($c)) { $v = [char]::GetNumericValue($c) }
        if ([Char]::IsLetter($c)) { $v = [int][char]$c - [int][char]'A' +10 }
        if ($c -eq '*') { $v = 36 }
        if ($c -eq '@') { $v = 37 }
        if ($c -eq '#') { $v = 38 }
        if($_ % 2){ $v += $v }
        $sum += [int][Math]::Floor($v / 10 ) + ($v % 10)
    }
    [int]$checkDigit_calculated = ( 10 - ($sum % 10) ) % 10
    return( $checkDigit_calculated )
}

function Test-IsCUSIP {
    [CmdletBinding()]
    [OutputType([bool])]
    Param (
        [Parameter(Mandatory=$true, Position=0)]
        [ValidatePattern( '^[A-Z0-9@#*]{8}\d$' )]
        [ValidateScript({$_.Length -eq 9})]
        [string]
        $cusip
    )
    [int]$checkDigit_told = $cusip[-1].ToString()
    $checkDigit_calculated = Get-CheckDigitCUSIP $cusip
    ($checkDigit_calculated -eq $checkDigit_told)
}

$data = @"
037833100`tApple Incorporated
17275R102`tCisco Systems
38259P508`tGoogle Incorporated
594918104`tMicrosoft Corporation
68389X106`tOracle Corporation   (incorrect)
68389X105`tOracle Corporation
"@ -split "`n"
$data |%{ Test-IsCUSIP $_.Split("`t")[0] }

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


Write-Host Word Size: ((Get-WMIObject Win32_Processor).DataWidth)
Write-Host -NoNewLine "Endianness: "
if ([BitConverter]::IsLittleEndian) {
    Write-Host Little-Endian
} else {
    Write-Host Big-Endian
}

prints the word size and endianness of the host machine. It's important to note that the endianness check is mostly irrelevant for PowerShell as it currently only has a Windows implementation, and current Windows versions don't operate on big-endian systems. However, theoretically, this check should still function.


$get1 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json")
$get2 = (New-Object Net.WebClient).DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$match1 = [regex]::matches($get1, "`"title`":`"Category:(.+?)`"")
$match2 = [regex]::matches($get2, "title=`"Category:([^`"]+?)`">[^<]+?[^\(]*\((\d+) members\)")
$r = 1
$langs = $match1 | foreach { $_.Groups[1].Value.Replace("\","") }
$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {
    if ($langs.Contains($_.Groups[1].Value))
    {
        [pscustomobject]@{
            Rank = "$r"
            Members =  "$($_.Groups[2].Value)"
            Language = "$($_.Groups[1].Value)"
        }
        $r++
    }
}
1..30 | foreach{
    [pscustomobject]@{
        "Rank 1..30" = "$($_)"
        "Members 1..30" =  "$($res[$_-1].Members)"
        "Language 1..30" = "$($res[$_-1].Language)"
        "Rank 31..60" = "$($_+30)"
        "Members 31..60" =  "$($res[$_+30].Members)"
        "Language 31..60" = "$($res[$_+30].Language)"
    }
}| Format-Table -AutoSize

Rank 1..30 Members 1..30 Language 1..30 Rank 31..60 Members 31..60 Language 31..60
---------- ------------- -------------- ----------- -------------- ---------------
1          887           Tcl            31          405            Seed7
2          877           Racket         32          397            Julia
3          853           Python         33          389            PL/I
4          798           J              34          387            Fortran
5          775           Ruby           35          386            ALGOL 68
6          766           Perl 6         36          376            Lua
7          758           C              37          369            Pascal
8          746           Go             38          367            R
9          740           D              39          364            Groovy
10         710           Perl           40          363            F Sharp
11         701           REXX           41          363            Forth
12         692           PicoLisp       42          358            PHP
13         682           Haskell        43          342            AWK
14         675           Mathematica    44          340            Sidef
15         652           Java           45          335            MATLAB
16         623           Ada            46          325            Liberty BASIC
17         591           AutoHotkey     47          297            Octave
18         562           C++            48          287            Factor
19         551           Common Lisp    49          286            Scheme
20         548           Scala          50          285            NetRexx
21         532           BBC BASIC      51          284            Oforth
22         523           Icon           52          280            Oz
23         516           C sharp        53          274            Run BASIC
24         508           OCaml          54          272            E
25         502           Nim            55          271            Bracmat
26         488           PureBasic      56          268            PowerShell
27         487           Clojure        57          263            Prolog
28         455           Erlang         58          260            Lasso
29         441           PARI/GP        59          249            Delphi
30         434           JavaScript     60          239            Smalltalk
$response = (New-Object Net.WebClient).DownloadString("http://rosettacode.org/wiki/Category:Programming_Languages")
$languages = [regex]::matches($response,'title="Category:(.*?)">') | foreach {$_.Groups[1].Value}

$response = [Net.WebClient]::new().DownloadString("http://rosettacode.org/w/index.php?title=Special:Categories&limit=5000")
$response = [regex]::Replace($response,'(\d+),(\d+)','$1$2')

$members  = [regex]::matches($response,'
]+>([^<]+)[^(]*[(](\d+) member[s]?[)]
') | foreach { [pscustomobject]@{
            Members =  [Int]($_.Groups[2].Value)
            Language = [String]($_.Groups[1].Value)
        }} | where {$languages.Contains($_.Language)} | sort -Descending Members

Get-Date -UFormat "Sample output on %d %B %Y at %R %Z"
$members | Select-Object -First 10 | foreach -Begin {$r, $rank, $count = 0, 0,-1} {
    $r++
    if ($count -ne $_.Members) {$rank = $r}
    $count = $_.Members
    $x = $_.Members.ToString("N0",[System.Globalization.CultureInfo]::CreateSpecificCulture('en-US'))
    $entry = "($x entries)"
    [String]::Format("Rank: {0,2} {1,15} {2}",$rank,$entry,$_.Language)
}

The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It accesses data through web scraping or API methods, with optional filtering for incorrect results. The code also provides a complete ranked listing of all programming languages.


$colors = "Black","Blue","Cyan","Gray","Green","Magenta","Red","White","Yellow",
          "DarkBlue","DarkCyan","DarkGray","DarkGreen","DarkMagenta","DarkRed","DarkYellow"

foreach ($color in $colors)
{
    Write-Host "$color" -ForegroundColor $color
}

Iterates through each element in a collection in order and prints it, using a "for each" loop or another loop if "for each" is not available in the language.


Works with: PowerShell version 1
$words = "Hello,How,Are,You,Today".Split(',')
[string]::Join('.', $words)
Works with: PowerShell version 2
$words = "Hello,How,Are,You,Today" -split ','
$words -join '.'
Works with: PowerShell version 2

"Hello,How,Are,You,Today", ",,Hello,,Goodbye,," | ForEach-Object {($_.Split(',',[StringSplitOptions]::RemoveEmptyEntries)) -join "."}

"Tokenizes a string by separating it into an array using commas, then displays the words to the user separated by a period, while ensuring no empty elements are returned using the StringSplitOptions enumeration."


function Get-GCD ($x, $y)
{
  if ($x -eq $y) { return $y }
  if ($x -gt $y) {
    $a = $x
    $b = $y
  }
  else {
    $a = $y
    $b = $x
  }
  while ($a % $b -ne 0) {
    $tmp = $a % $b
    $a = $b
    $b = $tmp
  }
  return $b
}

function Get-GCD ($x, $y) {
  if ($y -eq 0) { $x } else { Get-GCD $y ($x%$y) }
}

Function Get-GCD( $x, $y ) {
    while ($y -ne 0) {
        $x, $y = $y, ($x % $y)
    }
    [Math]::abs($x)
}

find the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. The implementation is based on Python.


function isNumeric ($x) {
    try {
        0 + $x | Out-Null
        return $true
    } catch {
        return $false
    }
}

function isNumeric ($x) {
    $x2 = 0
    $isNum = [System.Int32]::TryParse($x, [ref]$x2)
    return $isNum
}

implement a boolean function to check if a given string is numeric, including floating point and negative numbers. The function uses arithmetic operations and returns false if it fails. However, it doesn't correctly handle strings like "8.". Alternatively, it can use the .NET framework's System.Int32.TryParse() method. Note that PowerShell 1.0 does not support 'try'.


$wc = New-Object Net.WebClient
$wc.DownloadString('https://sourceforge.net')

Send a GET request to the URL "https://www.w3.org/" without authentication, print the obtained resource to the console, and check the host certificate for validity. If the certificate is not valid, an exception is thrown.


function Get-Ranking
{
    [CmdletBinding(DefaultParameterSetName="Standard")]
    [OutputType([PSCustomObject])]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [string]
        $InputObject,

        [Parameter(Mandatory=$false,
                   ParameterSetName="Standard")]
        [switch]
        $Standard,

        [Parameter(Mandatory=$false,
                   ParameterSetName="Modified")]
        [switch]
        $Modified,

        [Parameter(Mandatory=$false,
                   ParameterSetName="Dense")]
        [switch]
        $Dense,

        [Parameter(Mandatory=$false,
                   ParameterSetName="Ordinal")]
        [switch]
        $Ordinal,

        [Parameter(Mandatory=$false,
                   ParameterSetName="Fractional")]
        [switch]
        $Fractional
    )

    Begin
    {
        function Get-OrdinalRank ([PSCustomObject[]]$Values)
        {
            for ($i = 0; $i -lt $Values.Count; $i++)
            {
                $Values[$i].Rank = $i + 1
            }

            $Values
        }

        function Get-Rank ([PSCustomObject[]]$Scores)
        {
            foreach ($score in $Scores)
            {
                $score.Group | ForEach-Object {$_.Rank = $score.Rank}
            }

            $Scores.Group
        }

        function New-Competitor ([string]$Name, [int]$Score, [int]$Rank = 0)
        {
            [PSCustomObject]@{
                Name  = $Name
                Score = $Score
                Rank  = $Rank
            }
        }

        $competitors = @()
        $scores = @()
    }
    Process
    {
        @($input) | ForEach-Object {$competitors += New-Competitor -Name $_.Split()[1] -Score $_.Split()[0]}
    }
    End
    {
        $scores = $competitors |
            Sort-Object   -Property Score -Descending |
            Group-Object  -Property Score |
            Select-Object -Property @{Name="Score"; Expression={[int]$_.Name}}, @{Name="Rank"; Expression={0}}, Count, Group

        switch ($PSCmdlet.ParameterSetName)
        {
            "Standard"
            {
                $rank = 1

                for ($i = 0; $i -lt $scores.Count; $i++)
                {
                    $scores[$i].Rank = $rank
                    $rank += $scores[$i].Count
                }

                Get-Rank $scores
            }
            "Modified"
            {
                $rank = 0

                foreach ($score in $scores)
                {
                    $rank = $score.Count + $rank
                    $score.Rank = $rank
                }

                Get-Rank $scores
            }
            "Dense"
            {
                for ($i = 0; $i -lt $scores.Count; $i++)
                {
                    $scores[$i].Rank = $i + 1
                }

                Get-Rank $scores
            }
            "Ordinal"
            {
                Get-OrdinalRank $competitors
            }
            "Fractional"
            {
                Get-OrdinalRank $competitors | Group-Object -Property Score | ForEach-Object {
                    if ($_.Count -gt 1)
                    {
                        $rank = ($_.Group.Rank | Measure-Object -Average).Average

                        foreach ($competitor in $_.Group)
                        {
                            $competitor.Rank = $rank
                        }
                    }
                }

                $competitors
            }
        }
    }
}

$scores = "44 Solomon","42 Jason","42 Errol","41 Garry","41 Bernard","41 Barry","39 Stephen"

$scores | Get-Ranking -Standard

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


demonstrate the use of trigonometric functions including sine, cosine, tangent and their inverses using the same angle in both radians and degrees. The output is an array of objects containing the results in both radians and degrees. The code also handles cases where the language does not have built-in trigonometric functions, by calculating these functions based on known approximations or identities.


$Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
    While($true)
    {
        Write-Host $n
        $n ++
        Start-Sleep -m 500
    }
}
Finally
{
    $End_Time = (Get-date).second
    $Time_Diff = $End_Time - $Start_Time
    Write-Host "Total time in seconds"$Time_Diff
}

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.


convert a numerical string to an integer, increment the value, and then convert it back to a string. The code also utilizes PowerShell's automatic casting based on the left-most operand to reduce the number of casts.


<#
.Synopsis
    Finds the deepest common directory path of files passed through the pipeline.
.Parameter File
    PowerShell file object.
#>
function Get-CommonPath {
[CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [System.IO.FileInfo] $File
    )
    process {
        # Get the current file's path list
        $PathList =  $File.FullName -split "\$([IO.Path]::DirectorySeparatorChar)"
        # Get the most common path list
        if ($CommonPathList) {
            $CommonPathList = (Compare-Object -ReferenceObject $CommonPathList -DifferenceObject $PathList -IncludeEqual `
                -ExcludeDifferent -SyncWindow 0).InputObject
        } else {
            $CommonPathList = $PathList
        }
    }
    end {
        $CommonPathList -join [IO.Path]::DirectorySeparatorChar
    }
}

"C:\a\b\c\d\e","C:\a\b\e\f","C:\a\b\c\d\x" | Get-CommonPath
C:\a\b

"Output: The code defines a routine that identifies the common directory path from a set of directory paths using a specified directory separator. It tests this routine using '/' as the directory separator and three specific strings as input paths. The code also identifies if there's a built-in function in the language used that can perform this task."


function Measure-Data
{
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    Param
    (
        [Parameter(Mandatory=$true,
                   Position=0)]
        [double[]]
        $Data
    )

    Begin
    {
        function Get-Mode ([double[]]$Data)
        {
            if ($Data.Count -gt ($Data | Select-Object -Unique).Count)
            {
                $groups = $Data | Group-Object | Sort-Object -Property Count -Descending

                return ($groups | Where-Object {[double]$_.Count -eq [double]$groups[0].Count}).Name | ForEach-Object {[double]$_}
            }
            else
            {
                return $null
            }
        }

        function Get-StandardDeviation ([double[]]$Data)
        {
            $variance = 0
            $average  = $Data | Measure-Object -Average | Select-Object -Property Count, Average

            foreach ($number in $Data)
            {
                $variance +=  [Math]::Pow(($number - $average.Average),2)
            }

            return [Math]::Sqrt($variance / ($average.Count-1))
        }

        function Get-Median ([double[]]$Data)
        {
            if ($Data.Count % 2)
            {
                return $Data[[Math]::Floor($Data.Count/2)]
            }
            else
            {
                return ($Data[$Data.Count/2], $Data[$Data.Count/2-1] | Measure-Object -Average).Average
            }
        }
    }
    Process
    {
        $Data = $Data | Sort-Object

        $Data | Measure-Object -Maximum -Minimum -Sum -Average |
                Select-Object -Property Count,
                                        Sum,
                                        Minimum,
                                        Maximum,
                                        @{Name='Range'; Expression={$_.Maximum - $_.Minimum}},
                                        @{Name='Mean' ; Expression={$_.Average}} |
                Add-Member -MemberType NoteProperty -Name Median            -Value (Get-Median $Data)            -PassThru |
                Add-Member -MemberType NoteProperty -Name StandardDeviation -Value (Get-StandardDeviation $Data) -PassThru |
                Add-Member -MemberType NoteProperty -Name Mode              -Value (Get-Mode $Data)              -PassThru
    }
}

$statistics = Measure-Data 4, 5, 6, 7, 7, 7, 8, 1, 1, 1, 2, 3
$statistics

The code calculates the median value of a vector of floating-point numbers. It handles cases with even number of elements by returning the average of the two middle values. It uses the selection algorithm for efficient computation. It also includes functions for calculating various statistical measures like mean, mode, and standard deviation.


print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.


$x = $y = $i = $j = $r = -16
$colors = [Enum]::GetValues([System.ConsoleColor])

while(($y++) -lt 15)
{
    for($x=0; ($x++) -lt 84; Write-Host " " -BackgroundColor ($colors[$k -band 15]) -NoNewline)
    {
        $i = $k = $r = 0

        do
        {
            $j = $r * $r - $i * $i -2 + $x / 25
            $i = 2 * $r * $i + $y / 10
            $r = $j
        }
        while (($j * $j + $i * $i) -lt 11 -band ($k++) -lt 111)
    }

    Write-Host
}

generate and draw the Mandelbrot set using various available algorithms and functions.


function Get-Sum ($a) {
    return ($a | Measure-Object -Sum).Sum
}

function Get-Product ($a) {
    if ($a.Length -eq 0) {
        return 0
    } else {
        $p = 1
        foreach ($x in $a) {
            $p *= $x
        }
        return $p
    }
}

Works with: PowerShell version 2
function Get-Product ($a) {
    if ($a.Length -eq 0) {
        return 0
    }
    $s = $a -join '*'
    return (Invoke-Expression $s)
}

function Get-SumAndProduct ($a) {
    $sum = 0
    if ($a.Length -eq 0) {
        $prod = 0
    } else {
        $prod = 1
        foreach ($x in $a) {
            $sum += $x
            $prod *= $x
        }
    }
    $ret = New-Object PSObject
    $ret | Add-Member NoteProperty Sum $sum
    $ret | Add-Member NoteProperty Product $prod
    return $ret
}

compute the sum and product of an array of integers using the Measure-Object cmdlet in PowerShell. The function returns a custom object with appropriate properties for both calculations.


$Year = 2016
[System.DateTime]::IsLeapYear( $Year )

"Determines if a specified year is a leap year in the Gregorian calendar."


$str = "foo"
$dup = $str

$dup = $str.Clone()

make a copy of a string or create an additional reference to an existing string in PowerShell using .NET, considering the immutability of .NET strings. The Clone() method is used for actual copying.


function F($n) {
    if ($n -eq 0) { return 1 }
    return $n - (M (F ($n - 1)))
}

function M($n) {
    if ($n -eq 0) { return 0 }
    return $n - (F (M ($n - 1)))
}

implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.


provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like "http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1", and "%25%32%35".


function BinarySearch-Iterative ([int[]]$Array, [int]$Value)
{
    [int]$low = 0
    [int]$high = $Array.Count - 1

    while ($low -le $high)
    {
        [int]$mid = ($low + $high) / 2

        if ($Array[$mid] -gt $Value)
        {
            $high = $mid - 1
        }
        elseif ($Array[$mid] -lt $Value)
        {
            $low = $mid + 1
        }
        else
        {
            return $mid
        }
    }

    return -1
}

function BinarySearch-Recursive ([int[]]$Array, [int]$Value, [int]$Low = 0, [int]$High = $Array.Count)
{
    if ($High -lt $Low)
    {
        return -1
    }

    [int]$mid = ($Low + $High) / 2

    if ($Array[$mid] -gt $Value)
    {
        return BinarySearch $Array $Value $Low ($mid - 1)
    }
    elseif ($Array[$mid] -lt $Value)
    {
        return BinarySearch $Array $Value ($mid + 1) $High
    }
    else
    {
        return $mid
    }
}

function Show-SearchResult ([int[]]$Array, [int]$Search, [ValidateSet("Iterative", "Recursive")][string]$Function)
{
    switch ($Function)
    {
        "Iterative" {$index = BinarySearch-Iterative -Array $Array -Value $Search}
        "Recursive" {$index = BinarySearch-Recursive -Array $Array -Value $Search}
    }

    if ($index -ge 0)
    {
        Write-Host ("Using BinarySearch-{0}: {1} is at index {2}" -f $Function, $numbers[$index], $index)
    }
    else
    {
        Write-Host ("Using BinarySearch-{0}: {1} not found" -f $Function, $Search) -ForegroundColor Red
    }
}
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 41 -Function Iterative
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 99 -Function Iterative
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 86 -Function Recursive
Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 11 -Function Recursive

The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a "secret value" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.


$i = 0
foreach ($s in $args) {
    Write-Host Argument (++$i) is $s
}

retrieve and print the list of command-line arguments provided to the program. It also parses these arguments intelligently. In the case of PowerShell, it accesses script arguments through the $args array. An example command line is also provided for reference.


# JSON input is being stored in ordered hashtable.
# Ordered hashtable is available in PowerShell v3 and higher.
[ordered]@{ "foo"= 1; "bar"= 10, "apples" } | ConvertTo-Json

# ConvertFrom-Json converts a JSON-formatted string to a custom object.
# If you use the Invoke-RestMethod cmdlet there is not need for the ConvertFrom-Json cmdlet
Invoke-WebRequest -Uri "http://date.jsontest.com" | ConvertFrom-Json

"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON."


#NoTeS: This sample code does not validate inputs
#	Thus, if there are errors the 'scary' red-text
#	error messages will appear.
#
#	This code will not work properly in floating point values of n,
#	and negative values of A.
#
#	Supports negative values of n by reciprocating the root.

$epsilon=1E-10		#Sample Epsilon (Precision)

function power($x,$e){	#As I said in the comment
	$ret=1
	for($i=1;$i -le $e;$i++){
		$ret*=$x
	}
	return $ret
}
function root($y,$n){					#The main Function
	if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n}	#This checks if n is negative.
	$ans=1

	do{
		$d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp
		$ans+=$d
	} while ($d -lt -$epsilon -or $d -gt $epsilon)

	if (0+$n -lt 0){return 1/$ans} else {return $ans}
}

#Sample Inputs
root 625 2
root 2401 4
root 2 -2
root 1.23456789E-20 34
root 9.87654321E20 10	#Quite slow here, I admit...

((root 5 2)+1)/2	#Extra: Computes the golden ratio
((root 5 2)-1)/2

Implement the principal nth root of a positive real number A, without using System.Math classes.


Find the hostname of the current system using the ComputerName environment variable in Windows or .NET classes and methods in PowerShell.


CLS

Function isNumeric ($x)
{
    $x2 = 0
    $isNum = [System.Int32]::TryParse($x,[ref]$x2)
Return $isNum
}

$NumberArray = @()
While( $NumberArray.Count -lt 4 ){
    $NumberArray += Random -Minimum 1 -Maximum 10
}

Write-Host @"
Welcome to the 24 game!

Here are your numbers: $($NumberArray -join ",").
Use division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers.
"@

Do
{
$Wrong = 0
$EndResult = $null
$TempChar = $null
$TempChar2 = $null
$Count = $null

$AllowableCharacters = $NumberArray + "+-*/()".ToCharArray()
    $Result = Read-Host
        Foreach($Char in $Result.ToCharArray())
        {
            If( $AllowableCharacters -notcontains $Char ){ $Wrong = 1 }
        }

        If($Wrong -eq 1)
        {
            Write-Warning "Wrong input! Please use only the given numbers."
        }
        Foreach($Char in $Result.ToCharArray())
        {
            If((IsNumeric $TempChar) -AND (IsNumeric $Char))
            {
                Write-Warning "Wrong input! Combining two or more numbers together is not allowed!"
            }
            $TempChar = $Char
        }
        Foreach($Char in $Result.ToCharArray())
        {
            If(IsNumeric $Char)
            {
                $Count++
            }
        }
        If($Count -eq 4)
        {
            $EndResult = Invoke-Expression $Result
                If($EndResult -eq 24)
                {
                    Write-Host "`nYou've won the game!"
                }
                Else
                {
                    Write-Host "`n$EndResult is not 24! Too bad."
                }
        }
        Else
        {
            Write-Warning "Wrong input! You did not supply four numbers."
        }
}
While($EndResult -ne 24)

The code randomly selects and displays four digits from 1 to 9, and prompts the player to form an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using addition, subtraction, multiplication, and division operations. The code checks and evaluates the player's input expression, but does not generate or test the possibility of an expression. It also includes a function to determine if a string is numeric.


function Compress-RLE ($s) {
    $re = [regex] '(.)\1*'
    $ret = ""
    foreach ($m in $re.Matches($s)) {
        $ret += $m.Length
        $ret += $m.Value[0]
    }
    return $ret
}

function Expand-RLE ($s) {
    $re = [regex] '(\d+)(.)'
    $ret = ""
    foreach ($m in $re.Matches($s)) {
        $ret += [string] $m.Groups[2] * [int] [string] $m.Groups[1]
    }
    return $ret
}

PS> Compress-RLE "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
12W1B12W3B24W1B14W
PS> Expand-RLE "12W1B12W3B24W1B14W"
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW

implement a run-length encoding and decoding function for a string containing uppercase characters. The function compresses repeated characters by storing the length of the run and can also reverse the compression.


$s = "Hello"
Write-Host $s World.

# alternative, using variable expansion in strings
Write-Host "$s World."

$s2 = $s + " World."
Write-Host $s2

Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.


Works with: PowerShell version 2
$c = New-Object Net.WebClient
$words = -split ($c.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'))
$top_anagrams = $words `
    | ForEach-Object {
          $_ | Add-Member -PassThru NoteProperty Characters `
                   (-join (([char[]] $_) | Sort-Object))
      } `
    | Group-Object Characters `
    | Group-Object Count `
    | Sort-Object Count `
    | Select-Object -First 1

$top_anagrams.Group | ForEach-Object { $_.Group -join ', ' }

The code identifies sets of words from a given list (http://wiki.puzzlers.org/pub/wordlists/unixdict.txt) that are anagrams of each other, focusing on those sets with the most words. The implementation significantly improves runtime, reducing it from 2 minutes to 1.5 seconds using more .Net methods.


Text based solution
Works with: PowerShell version 2
function Draw-SierpinskiCarpet ( [int]$N )
    {
    $Carpet = @( '#' ) * [math]::Pow( 3, $N )
    ForEach ( $i in 1..$N )
        {
        $S = [math]::Pow( 3, $i - 1 )
        ForEach ( $Row in 0..($S-1) )
            {
            $Carpet[$Row+$S+$S] = $Carpet[$Row] * 3
            $Carpet[$Row+$S]    = $Carpet[$Row] + ( " " * $Carpet[$Row].Length ) + $Carpet[$Row]
            $Carpet[$Row]       = $Carpet[$Row] * 3
            }
        }
    $Carpet
    }

Draw-SierpinskiCarpet 3

generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.


Works with: PowerShell version 2
function Get-HuffmanEncodingTable ( $String )
    {
    #  Create leaf nodes
    $ID = 0
    $Nodes = [char[]]$String |
        Group-Object |
        ForEach { $ID++; $_ } |
        Select  @{ Label = 'Symbol'  ; Expression = { $_.Name  } },
                @{ Label = 'Count'   ; Expression = { $_.Count } },
                @{ Label = 'ID'      ; Expression = { $ID      } },
                @{ Label = 'Parent'  ; Expression = { 0        } },
                @{ Label = 'Code'    ; Expression = { ''       } }

    #  Grow stems under leafs
    ForEach ( $Branch in 2..($Nodes.Count) )
        {
        #  Get the two nodes with the lowest count
        $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2

        #  Create a new stem node
        $ID++
        $Nodes += '' |
            Select  @{ Label = 'Symbol'  ; Expression = { ''       } },
                    @{ Label = 'Count'   ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } },
                    @{ Label = 'ID'      ; Expression = { $ID      } },
                    @{ Label = 'Parent'  ; Expression = { 0        } },
                    @{ Label = 'Code'    ; Expression = { ''       } }

        #  Put the two nodes in the new stem node
        $LowNodes[0].Parent = $ID
        $LowNodes[1].Parent = $ID

        #  Assign 0 and 1 to the left and right nodes
        $LowNodes[0].Code = '0'
        $LowNodes[1].Code = '1'
        }

    #  Assign coding to nodes
    ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] )
        {
        $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code
        }

    $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol
    return $EncodingTable
    }

#  Get table for given string
$String = "this is an example for huffman encoding"
$HuffmanEncodingTable = Get-HuffmanEncodingTable $String

#  Display table
$HuffmanEncodingTable | Format-Table -AutoSize

#  Encode string
$EncodedString = $String
ForEach ( $Node in $HuffmanEncodingTable )
    {
    $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code )
    }
$EncodedString

The code generates a Huffman encoding for each character in the given string "this is an example for huffman encoding". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.


Works with: PowerShell version 3
$Label1  = [System.Windows.Forms.Label]@{
            Text = 'There have been no clicks yet'
            Size = '200, 20' }
$Button1 = [System.Windows.Forms.Button]@{
            Text = 'Click me'
            Location = '0, 20' }

$Button1.Add_Click(
    {
    $Script:Clicks++
    If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" }
    Else                 { $Label1.Text = "There have been $Clicks clicks" }
    } )

$Form1 = New-Object System.Windows.Forms.Form
$Form1.Controls.AddRange( @( $Label1, $Button1 ) )

$Clicks = 0

$Result = $Form1.ShowDialog()

Works with: PowerShell version 2
Add-Type -AssemblyName System.Windows.Forms

$Label1 = New-Object System.Windows.Forms.Label
$Label1.Text = 'There have been no clicks yet'
$Label1.Size = '200, 20'

$Button1 = New-Object System.Windows.Forms.Button
$Button1.Text = 'Click me'
$Button1.Location = '0, 20'

$Button1.Add_Click(
    {
    $Script:Clicks++
    If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" }
    Else                 { $Label1.Text = "There have been $Clicks clicks" }
    } )

$Form1 = New-Object System.Windows.Forms.Form
$Form1.Controls.AddRange( @( $Label1, $Button1 ) )

$Clicks = 0

$Result = $Form1.ShowDialog()

[xml]$Xaml = @"
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name = "Window1"
    Width  = "200"
    Height = "120"
    ShowInTaskbar = "True">
    <StackPanel>
        <Label
            x:Name  = "Label1"
            Height  = "40"
            Width   = "200"
            Content = "There have been no clicks"/>
        <Button
            x:Name  = "Button1"
            Height  = "25"
            Width   = "60"
            Content = "Click me"/>
    </StackPanel>
</Window>
"@

$Window1 = [Windows.Markup.XamlReader]::Load( [System.Xml.XmlNodeReader]$Xaml )

$Label1  = $Window1.FindName( "Label1"  )
$Button1 = $Window1.FindName( "Button1" )

$Button1.Add_Click(
    {
    $Script:Clicks++
    If ( $Clicks -eq 1 ) { $Label1.Content = "There has been 1 click" }
    Else                 { $Label1.Content = "There have been $Clicks clicks" }
    } )

$Clicks = 0

$Result = $Window1.ShowDialog()

Implement a windowed application with a label and a button. The label initially displays "There have been no clicks yet". The button, labelled "click me", updates the label to show the number of times it has been clicked when interacted with.


The code uses a for loop to perform a countdown from 10 to 0. It may also utilize the range operator to generate a continuous range of integers.