WinForms[edit]
Translation of: Logo
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.


Character Length[edit]
$s = "Hëlló Wørłð"
$s.Length
Byte Length[edit]
Translation of: C#

$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
First method[edit]
$string = "top and tail"
$string
$string.Substring(1)
$string.Substring(0, $string.Length - 1)
$string.Substring(1, $string.Length - 2)

Second method[edit]
$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

Alternate Version[edit]

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.


version 1[edit]
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

version 2[edit]

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.


Translation of: C#
$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

PowerShell: Using web scraping[edit]
Translation of: Python
$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."


Recursive Euclid Algorithm[edit]
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) }
}
Iterative Euclid Algorithm[edit]

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.


Windows Forms[edit]
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()

WPF[edit]
[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.


# Author: D. Cudnohufsky
function Get-VigenereCipher
{
    Param
    (
        [Parameter(Mandatory=$true)]
        [string] $Text,

        [Parameter(Mandatory=$true)]
        [string] $Key,

        [switch] $Decode
    )

    begin
    {
        $map = [char]'A'..[char]'Z'
    }

    process
    {
        $Key = $Key -replace '[^a-zA-Z]',''
        $Text = $Text -replace '[^a-zA-Z]',''

        $keyChars = $Key.toUpper().ToCharArray()
        $Chars = $Text.toUpper().ToCharArray()

        function encode
        {

            param
            (
                $Char,
                $keyChar,
                $Alpha = [char]'A'..[char]'Z'
            )

            $charIndex = $Alpha.IndexOf([int]$Char)
            $keyIndex = $Alpha.IndexOf([int]$keyChar)
            $NewIndex = ($charIndex + $KeyIndex) - $Alpha.Length
            $Alpha[$NewIndex]

        }

        function decode
        {

            param
            (
                $Char,
                $keyChar,
                $Alpha = [char]'A'..[char]'Z'
            )

            $charIndex = $Alpha.IndexOf([int]$Char)
            $keyIndex = $Alpha.IndexOf([int]$keyChar)
            $int = $charIndex - $keyIndex
            if ($int -lt 0) { $NewIndex = $int + $Alpha.Length }
            else { $NewIndex = $int }
            $Alpha[$NewIndex]
        }

        while ( $keyChars.Length -lt $Chars.Length )
        {
            $keyChars = $keyChars + $keyChars
        }

        for ( $i = 0; $i -lt $Chars.Length; $i++ )
        {

            if ( [int]$Chars[$i] -in $map -and [int]$keyChars[$i] -in $map )
            {
                if ($Decode) {$Chars[$i] = decode $Chars[$i] $keyChars[$i] $map}
                else {$Chars[$i] = encode $Chars[$i] $keyChars[$i] $map}

                $Chars[$i] = [char]$Chars[$i]
                [string]$OutText += $Chars[$i]
            }

        }

        $OutText
        $OutText = $null
    }
}

Encode:
PS C:\> Get-VigenereCipher 'We attack at dawn.' 'lemon'
HIMHGLGWOGOEIB

Decode:
PS C:\> Get-VigenereCipher 'HIMHGLGWOGOEIB' 'lemon' -Decode
WEATTACKATDAWN

Implement and decrypt a Vigenère cipher. The code handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. If non-alphabetic characters are handled differently, a note is made.


demonstrate a for-loop with a step-value greater than one.


function  order($as,$bs) {
    if($as -and $bs) {
        $a, $as = $as
        $b, $bs = $bs
        if($a -eq $b) {order $as $bs}
        else{$a -lt $b}
    } elseif ($bs) {$true} else {$false}
}
"$(order @(1,2,1,3,2) @(1,2,0,4,4,0,0,0))"

False

Non-Recursive Version[edit]
function Test-Order ([int[]]$ReferenceArray, [int[]]$DifferenceArray)
{
    for ($i = 0; $i -lt $ReferenceArray.Count; $i++)
    {
        if ($ReferenceArray[$i] -lt $DifferenceArray[$i])
        {
            return $true
        }
        elseif ($ReferenceArray[$i] -gt $DifferenceArray[$i])
        {
            return $false
        }
    }

    return ($ReferenceArray.Count -lt $DifferenceArray.Count) -or (Compare-Object $ReferenceArray $DifferenceArray) -eq $null
}

Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 0, 4, 4, 0, 0, 0
Test-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 2, 4, 4, 0, 0, 0
Test-Order -ReferenceArray 1, 2, 3       -DifferenceArray 1, 2
Test-Order -ReferenceArray 1, 2          -DifferenceArray 1, 2, 3
Test-Order -ReferenceArray 1, 2          -DifferenceArray 1, 2

"Function to compare two numerical lists in lexicographic order and return true if the first list should be ordered before the second, false otherwise."


Translation of: PHP
function ackermann ([long] $m, [long] $n) {
    if ($m -eq 0) {
        return $n + 1
    }

    if ($n -eq 0) {
        return (ackermann ($m - 1) 1)
    }

    return (ackermann ($m - 1) (ackermann $m ($n - 1)))
}

foreach ($m in 0..3) {
    foreach ($n in 0..6) {
        Write-Host -NoNewline ("{0,5}" -f (ackermann $m $n))
    }
    Write-Host
}

The code implements the Ackermann function, a non-primitive recursive function. It takes two non-negative arguments and returns their Ackermann value. The function grows quickly in value and its call tree size. It also includes a feature to save the result to an array for future use and display it using the Format-Wide cmdlet. The code handles arbitrary precision but it's not mandatory.


Add-Type -Path "C:\Program Files (x86)\Math\MathNet.Numerics.3.12.0\lib\net40\MathNet.Numerics.dll"

1..20 | ForEach-Object {[MathNet.Numerics.SpecialFunctions]::Gamma($_ / 10)}

The code implements an algorithm to compute the Gamma function in the real field. It compares the results of this implementation with built-in/library functions. The Gamma function is computed using numerical integration, Lanczos approximation, and Stirling's approximation. The code also involves the use of Math.NET Numerics dll(s).


Works with: PowerShell version 2
function PlaceQueen ( [ref]$Board, $Row, $N )
    {
    #  For the current row, start with the first column
    $Board.Value[$Row] = 0

    #  While haven't exhausted all columns in the current row...
    While ( $Board.Value[$Row] -lt $N )
        {
        #  If not the first row, check for conflicts
        $Conflict = $Row -and
                    (   (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] }.Count -or
                        (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] - $Row + $_ }.Count -or
                        (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] + $Row - $_ }.Count )

        #  If no conflicts and the current column is a valid column...
        If ( -not $Conflict -and $Board.Value[$Row] -lt $N )
            {

            #  If this is the last row
            #    Board completed successfully
            If ( $Row -eq ( $N - 1 ) )
                {
                return $True
                }

            #  Recurse
            #  If all nested recursions were successful
            #    Board completed successfully
            If ( PlaceQueen $Board ( $Row + 1 ) $N )
                {
                return $True
                }
            }

        #  Try the next column
        $Board.Value[$Row]++
        }

    #  Everything was tried, nothing worked
    Return $False
    }

function Get-NQueensBoard ( $N )
    {
    #  Start with a default board (array of column positions for each row)
    $Board = @( 0 ) * $N

    #  Place queens on board
    #  If successful...
    If ( PlaceQueen -Board ([ref]$Board) -Row 0 -N $N )
        {
        #  Convert board to strings for display
        $Board | ForEach { ( @( "" ) + @(" ") * $_ + "Q" + @(" ") * ( $N - $_ ) ) -join "|" }
        }
    Else
        {
        "There is no solution for N = $N"
        }
    }

Get-NQueensBoard 8
''
Get-NQueensBoard 3
''
Get-NQueensBoard 4
''
Get-NQueensBoard 14

"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N."


demonstrate how to concatenate two arrays.


using namespace System.Collections.Generic
$ErrorActionPreference = 'Stop'
class Person{
    #private
    hidden [int] $_candidateIndex;
    [string] $Name
    #[System.Collections.Generic.List[Person]] $Prefs
    [List[Person]] $Prefs
    [Person] $Fiance

    Person([string] $name) {
            $this.Name = $name;
            $this.Prefs = $null;
            $this.Fiance = $null;
            $this._candidateIndex = 0;
        }
    [bool] Prefers([Person] $p) {
            return $this.Prefs.FindIndex({ param($o) $o -eq $p }) -lt $this.Prefs.FindIndex({ param($o) $o -eq $this.Fiance });
        }

    [Person] NextCandidateNotYetProposedTo() {
            if ($this._candidateIndex -ge $this.Prefs.Count) {return $null;}
            return $this.Prefs[$this._candidateIndex++];
        }

    [void] EngageTo([Person] $p) {
            if ($p.Fiance -ne $null) {$p.Fiance.Fiance = $null};
            $p.Fiance = $this;
            if ($this.Fiance -ne $null){$this.Fiance.Fiance = $null};
            $this.Fiance = $p;
        }

    }

    class MainClass
    {
        static  [bool] IsStable([List[Person]] $men) {
            [List[Person]] $women = $men[0].Prefs;
            foreach ($guy in $men){
                foreach ($gal in $women) {
                    if ($guy.Prefers($gal) -and $gal.Prefers($guy))
                        {return $false};
                }
            }
            return $true;
        }

        static [void] DoMarriage() {
            [Person] $abe  = [Person]::new("abe");
            [Person] $bob  = [Person]::new("bob");
            [Person] $col  = [Person]::new("col");
            [Person] $dan  = [Person]::new("dan");
            [Person] $ed   = [Person]::new("ed");
            [Person] $fred = [Person]::new("fred");
            [Person] $gav  = [Person]::new("gav");
            [Person] $hal  = [Person]::new("hal");
            [Person] $ian  = [Person]::new("ian");
            [Person] $jon  = [Person]::new("jon");
            [Person] $abi  = [Person]::new("abi");
            [Person] $bea  = [Person]::new("bea");
            [Person] $cath = [Person]::new("cath");
            [Person] $dee  = [Person]::new("dee");
            [Person] $eve  = [Person]::new("eve");
            [Person] $fay  = [Person]::new("fay");
            [Person] $gay  = [Person]::new("gay");
            [Person] $hope = [Person]::new("hope");
            [Person] $ivy  = [Person]::new("ivy");
            [Person] $jan  = [Person]::new("jan");

            $abe.Prefs =[Person[]]@($abi, $eve, $cath, $ivy, $jan, $dee, $fay, $bea, $hope, $gay)
            $bob.Prefs  = [Person[]] @($cath, $hope, $abi, $dee, $eve, $fay, $bea, $jan, $ivy, $gay);
            $col.Prefs  = [Person[]] @($hope, $eve, $abi, $dee, $bea, $fay, $ivy, $gay, $cath, $jan);
            $dan.Prefs  = [Person[]] @($ivy, $fay, $dee, $gay, $hope, $eve, $jan, $bea, $cath, $abi);
            $ed.Prefs   = [Person[]] @($jan, $dee, $bea, $cath, $fay, $eve, $abi, $ivy, $hope, $gay);
            $fred.Prefs = [Person[]] @($bea, $abi, $dee, $gay, $eve, $ivy, $cath, $jan, $hope, $fay);
            $gav.Prefs  = [Person[]] @($gay, $eve, $ivy, $bea, $cath, $abi, $dee, $hope, $jan, $fay);
            $hal.Prefs  = [Person[]] @($abi, $eve, $hope, $fay, $ivy, $cath, $jan, $bea, $gay, $dee);
            $ian.Prefs  = [Person[]] @($hope, $cath, $dee, $gay, $bea, $abi, $fay, $ivy, $jan, $eve);
            $jon.Prefs  = [Person[]] @($abi, $fay, $jan, $gay, $eve, $bea, $dee, $cath, $ivy, $hope);
            $abi.Prefs  = [Person[]] @($bob, $fred, $jon, $gav, $ian, $abe, $dan, $ed, $col, $hal);
            $bea.Prefs  = [Person[]] @($bob, $abe, $col, $fred, $gav, $dan, $ian, $ed, $jon, $hal);
            $cath.Prefs = [Person[]] @($fred, $bob, $ed, $gav, $hal, $col, $ian, $abe, $dan, $jon);
            $dee.Prefs  = [Person[]] @($fred, $jon, $col, $abe, $ian, $hal, $gav, $dan, $bob, $ed);
            $eve.Prefs  = [Person[]] @($jon, $hal, $fred, $dan, $abe, $gav, $col, $ed, $ian, $bob);
            $fay.Prefs  = [Person[]] @($bob, $abe, $ed, $ian, $jon, $dan, $fred, $gav, $col, $hal);
            $gay.Prefs  = [Person[]] @($jon, $gav, $hal, $fred, $bob, $abe, $col, $ed, $dan, $ian);
            $hope.Prefs = [Person[]] @($gav, $jon, $bob, $abe, $ian, $dan, $hal, $ed, $col, $fred);
            $ivy.Prefs  = [Person[]] @($ian, $col, $hal, $gav, $fred, $bob, $abe, $ed, $jon, $dan);
            $jan.Prefs  = [Person[]] @($ed, $hal, $gav, $abe, $bob, $jon, $col, $ian, $fred, $dan);

            [List[Person]] $men = [List[Person]]::new($abi.Prefs);

            [int] $freeMenCount = $men.Count;
            while ($freeMenCount -gt 0) {
                foreach ($guy in $men) {
                    if ($guy.Fiance -eq $null) {
                        [Person]$gal = $guy.NextCandidateNotYetProposedTo();
                        if ($gal.Fiance -eq $null) {
                            $guy.EngageTo($gal);
                            $freeMenCount--;
                        }
                        else{
                            if ($gal.Prefers($guy)) {
                                $guy.EngageTo($gal);
                            }
                        }

                    }
                }
            }

            foreach ($guy in $men) {
                write-host $guy.Name " is engaged to " $guy.Fiance.Name

            }
            write-host "Stable = " ([MainClass]::IsStable($men))

            write-host "Switching fred & jon's partners";
            [Person] $jonsFiance = $jon.Fiance;
            [Person] $fredsFiance = $fred.Fiance;
            $fred.EngageTo($jonsFiance);
            $jon.EngageTo($fredsFiance);
            write-host "Stable = " ([MainClass]::IsStable($men));

        }
     static [void] Main([string[]] $args)
        {
            [MainClass]::DoMarriage();
        }

    }

[MainClass]::DoMarriage()

The code implements the Gale-Shapley algorithm to solve the Stable Marriage Problem. It takes as input the preferences of ten males and ten females for potential partners. The algorithm generates a stable set of engagements where no individual prefers someone else over their current partner, who also prefers them over their current partner. The code also perturbs this stable set to create an unstable set and checks its stability.


#  Simulated fast function
function a ( [boolean]$J ) { return $J }

#  Simulated slow function
function b ( [boolean]$J ) { Sleep -Seconds 2; return $J }

#  These all short-circuit and do not evaluate the right hand function
( a $True  ) -or  ( b $False )
( a $True  ) -or  ( b $True  )
( a $False ) -and ( b $False )
( a $False ) -and ( b $True  )

#  Measure of execution time
Measure-Command {
( a $True  ) -or  ( b $False )
( a $True  ) -or  ( b $True  )
( a $False ) -and ( b $False )
( a $False ) -and ( b $True  )
} | Select TotalMilliseconds

#  These all appropriately do evaluate the right hand function
( a $False ) -or  ( b $False )
( a $False ) -or  ( b $True  )
( a $True  ) -and ( b $False )
( a $True  ) -and ( b $True  )

#  Measure of execution time
Measure-Command {
( a $False ) -or  ( b $False )
( a $False ) -or  ( b $True  )
( a $True  ) -and ( b $False )
( a $True  ) -and ( b $True  )
} | Select TotalMilliseconds

The code defines two functions, 'a' and 'b', both of which take a boolean value as input, return the same value, and print their name when called. The code then calculates the values of two boolean expressions 'x' and 'y' using these functions. The calculation is done in such a way that function 'b' is only called when necessary, utilizing the concept of short-circuit evaluation. If the language does not support short-circuit evaluation, nested 'if' statements are used instead. PowerShell natively supports this feature.


function Send-MorseCode
{
    [CmdletBinding()]
    [OutputType([string])]
    Param
    (
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   Position=0)]
        [string]
        $Message,

        [switch]
        $ShowCode
    )

    Begin
    {
        $morseCode = @{
            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 = "--.." ; 0 = "-----"; 1 = ".----"
            2 = "..---"; 3 = "...--"; 4 = "....-"; 5 = "....."
            6 = "-...."; 7 = "--..."; 8 = "---.."; 9 = "----."
        }
    }
    Process
    {
        foreach ($word in $Message)
        {
            $word.Split(" ",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object {

                foreach ($char in $_.ToCharArray())
                {
                    if ($char -in $morseCode.Keys)
                    {
                        foreach ($code in ($morseCode."$char").ToCharArray())
                        {
                            if ($code -eq ".") {$duration = 250} else {$duration = 750}

                            [System.Console]::Beep(1000, $duration)
                            Start-Sleep -Milliseconds 50
                        }

                        if ($ShowCode) {Write-Host ("{0,-6}" -f ("{0,6}" -f $morseCode."$char")) -NoNewLine}
                    }
                }

                if ($ShowCode) {Write-Host}
            }

            if ($ShowCode) {Write-Host}
        }
    }
}

Send-MorseCode -Message "S.O.S" -ShowCode

"Function to convert a given string into Morse code and play it as audible sound through an audio device. It handles unknown characters by either ignoring them or indicating them with a different pitch. The function is case insensitive and can optionally display the Morse code."


<#
.Synopsis
  ABC Problem
.DESCRIPTION
   You are given a collection of ABC blocks. Just like the ones you had when you were a kid.
   There are twenty blocks with two letters on each block. You are guaranteed to have a
   complete alphabet amongst all sides of the blocks
   blocks = "BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"
   The goal of this task is to write a function that takes a string and can determine whether
   you can spell the word with the given collection of blocks.

   The rules are simple:
        1.Once a letter on a block is used that block cannot be used again
        2.The function should be case-insensitive
        3. Show your output on this page for the following words:
        >>> can_make_word("A")
        True
        >>> can_make_word("BARK")
        True
        >>> can_make_word("BOOK")
        False
        >>> can_make_word("TREAT")
        True
        >>> can_make_word("COMMON")
        False
        >>> can_make_word("SQUAD")
        True
        >>> can_make_word("CONFUSE")
        True

   Using the examples below  you can either see just the value or
   status and the values using the verbose switch

.EXAMPLE
   test-blocks -testword confuse

.EXAMPLE
   test-blocks -testword confuse -verbose

#>

function test-blocks
{
	[CmdletBinding()]
	#  [OutputType([int])]
	Param
	(
		# word to test against blocks
		[Parameter(Mandatory = $true,
				   ValueFromPipelineByPropertyName = $true)]
		$testword

	)

	$word = $testword

	#define array of blocks
	[System.Collections.ArrayList]$blockarray = "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"

	#send word to chararray
	$chararray = $word.ToCharArray()
	$chars = $chararray

	#get the character count
	$charscount = $chars.count

	#get the initial count of the blocks
	$blockcount = $blockarray.Count

	#find out how many blocks should be left from the difference
	#of the blocks and characters in the word - 1 letter/1 block
	$correctblockcount = $blockcount - $charscount

	#loop through the characters in the word
	foreach ($char in $chars)
	{

		#loop through the blocks
		foreach ($block in $blockarray)
		{

			#check the current character against each letter on the current block
			#and break if found so the array can reload
			if ($char -in $block[0] -or $char -in $block[1])
			{

				write-verbose "match for letter - $char - removing block $block"
				$blockarray.Remove($block)
				break

			}

		}

	}
	#get final count of blocks left in array to determine if the word was
	#correctly made
	$finalblockcount = $blockarray.count
	if ($finalblockcount -ne $correctblockcount)
	{
		write-verbose "$word : $false "
		return $false
	}
	else
	{
		write-verbose "$word : $true "
		return $true
	}

}

#loop all the words and pass them to the function
$wordlist = "a", "bark", "book", "treat", "common", "squad", "confuse"
foreach ($word in $wordlist)
{
	test-blocks -testword $word -Verbose
}

"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed."


Translation of: C#
$string = "The quick brown fox jumped over the lazy dog's back"
$data = [Text.Encoding]::UTF8.GetBytes($string)
$hash = [Security.Cryptography.MD5]::Create().ComputeHash($data)
([BitConverter]::ToString($hash) -replace '-').ToLower()

implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5/Implementation for a scratch implementation.


[hashtable]$mailMessage = @{
    From = "weirdBoy@gmail.com"
    To = "anudderBoy@YourDomain.com"
    Cc = "daWaghBoss@YourDomain.com"
    Attachment = "C:\temp\Waggghhhh!_plan.txt"
    Subject = "Waggghhhh!"
    Body = "Wagggghhhhhh!"
    SMTPServer = "smtp.gmail.com"
    SMTPPort = "587"
    UseSsl = $true
    ErrorAction = "SilentlyContinue"
}

Send-MailMessage @mailMessage

implement a function to send an email using PowerShell's 'Send-MailMessage' cmdlet. The function includes parameters for setting 'From', 'To', 'Cc' addresses, 'Subject', and 'message text'. Optional fields for server name and login details are also included. The solution is portable across different operating systems.


[int64]$i = 0
While ( $True )
    {
    [Convert]::ToString( ++$i, 8 )
    }

generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.


$b, $a = $a, $b

function swap ([ref] $a, [ref] $b) {
    $a.Value, $b.Value = $b.Value, $a.Value
}

swap ([ref] $a) ([ref] $b)

define a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. This function should work in both statically and dynamically typed languages, with certain constraints for type compatibility. In functional languages, the function may not allow destructive operations. The function should also handle issues related to parametric polymorphism in static languages. In PowerShell, the function can use tuple assignment for swapping.


Function Test-Palindrome( [String] $Text ){
    $CharArray = $Text.ToCharArray()
    [Array]::Reverse($CharArray)
    $Text -eq [string]::join('', $CharArray)
}
PowerShell (Regex Version)[edit]

function Test-Palindrome
{
  <#
    .SYNOPSIS
        Tests if a string is a palindrome.
    .DESCRIPTION
        Tests if a string is a true palindrome or, optionally, an inexact palindrome.
    .EXAMPLE
        Test-Palindrome -Text "racecar"
    .EXAMPLE
        Test-Palindrome -Text '"Deliver desserts," demanded Nemesis, "emended, named, stressed, reviled."' -Inexact
  #>
    [CmdletBinding()]
    [OutputType([bool])]
    Param
    (
        # The string to test for palindrominity.
        [Parameter(Mandatory=$true)]
        [string]
        $Text,

        # When specified, detects an inexact palindrome.
        [switch]
        $Inexact
    )

    if ($Inexact)
    {
        # Strip all punctuation and spaces
        $Text = [Regex]::Replace("$Text($7&","[^1-9a-zA-Z]","")
    }

    $Text -match "^(?'char'[a-z])+[a-z]?(?:\k'char'(?'-char'))+(?(char)(?!))$"
}
Test-Palindrome -Text 'radar'

The code defines a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and also includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case. The code uses string reversal and Unicode categories for character identification.


demonstrate how to access a process's environment variables such as PATH, HOME, and USER, which are commonly found on Unix systems. The environment variables are located in the Env: drive and can be retrieved using a specific variable syntax. The code also includes a feature to list all environment variables by querying the drive's contents.


type Stack a = [a]

create :: Stack a
create = []

push :: a -> Stack a -> Stack a
push = (:)

pop :: Stack a -> (a, Stack a)
pop []     = error "Stack empty"
pop (x:xs) = (x,xs)

empty :: Stack a -> Bool
empty = null

peek :: Stack a -> a
peek []    = error "Stack empty"
peek (x:_) = x

import Control.Monad.State

type Stack a b = State [a] b

push :: a -> Stack a ()
push = modify . (:)

pop :: Stack a a
pop = do
    nonEmpty
    x <- peek
    modify tail
    return x

empty :: Stack a Bool
empty = gets null

peek :: Stack a a
peek = nonEmpty >> gets head

nonEmpty :: Stack a ()
nonEmpty = empty >>= flip when (fail "Stack empty")

implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and is accessed through its top. The 'push' operation stores a new element onto the stack top, 'pop' returns and removes the last pushed stack element, and 'empty' checks if the stack contains no elements. The topmost element can be accessed for read or write without modifying the stack. The implementation also supports a purely functional approach where pop returns both the element and the changed stack.


The code defines a function to generate the nth Fibonacci number, either iteratively or recursively. It optionally supports negative numbers using an inverse definition. The function can also use Binet's formula and an exact real arithmetic library for precise calculations, even for large numbers. It includes an optimized version using a memoizer for faster execution. The code also demonstrates the use of lazy lists to generate an infinite list of all Fibonacci numbers. It includes a version that supports negative numbers and uses accumulator to hold the last two members of the series. The code also uses Fibonacci recurrence identities for efficient calculation of large Fibonacci numbers.


ary = [1..10]
evens = [x | x <- ary, even x]

evens = filter even ary

import Data.Array

ary = listArray (1,10) [1..10]
evens = listArray (1,n) l where
  n = length l
  l = [x | x <- elems ary, even x]

select specific elements from an array, in this case, even numbers, and place them into a new array. Alternatively, the code can modify the original array directly. In Haskell, this operation is typically done on a list, but it can also be done on an array by converting it into a list. The bounds of the array must be known before its creation.


Strings[edit]
Works with: Haskell version 6.10.4

The first three tasks are simply:
*Main> take 3 $ drop 2 "1234567890"
"345"

*Main> drop 2 "1234567890"
"34567890"

*Main> init "1234567890"
"123456789"

The last two can be formulated with the following function:
t45 n c s | null sub = []
          | otherwise = take n. head $ sub
  where sub = filter(isPrefixOf c) $ tails s

*Main> t45 3 "4" "1234567890"
"456"

*Main> t45 3 "45" "1234567890"
"456"

*Main> t45 3 "31" "1234567890"
""
Data.Text[edit]

Works with: Haskell version 8.0.2
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Text as T (Text, take, drop, init, breakOn)
import qualified Data.Text.IO as O (putStrLn)

fromMforN :: Int -> Int -> T.Text -> T.Text
fromMforN n m s = T.take m (T.drop n s)

fromNtoEnd :: Int -> T.Text -> T.Text
fromNtoEnd = T.drop

allButLast :: T.Text -> T.Text
allButLast = T.init

fromCharForN, fromStringForN :: Int -> T.Text -> T.Text -> T.Text
fromCharForN m needle haystack = T.take m $ snd $ T.breakOn needle haystack

fromStringForN = fromCharForN

-- TEST ---------------------------------------------------
main :: IO ()
main =
  mapM_
    O.putStrLn
    ([ fromMforN 9 10
     , fromNtoEnd 20
     , allButLast
     , fromCharForN 6 "话"
     , fromStringForN 6 "大势"
     ] <*>
     ["天地不仁仁者人也🐒话说天下大势分久必合🍑合久必分🔥"])

The code performs the following tasks:
1. Displays a substring starting from 'n' characters in and of 'm' length.
2. Displays a substring starting from 'n' characters in, up to the end of the string.
3. Displays the whole string minus the last character.
4. Displays a substring starting from a known character within the string and of 'm' length.
5. Displays a substring starting from a known substring within the string and of 'm' length.
The code is compatible with any valid Unicode code point, including UTF-8 or UTF-16, and references logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. It is not required to handle all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP. In Haskell, the string is represented as a list of chars: [Char]. The code also includes tests with an extended set of characters using Data.Text functions, including breakOn.


reverse = foldl (flip (:)) []

accumulatingReverse :: [a] -> [a]
accumulatingReverse lst =
  let rev xs a = foldl (flip (:)) a xs
  in rev lst []

Supporting combining characters[edit]
import Data.Char (isMark)
import Data.List (groupBy)
myReverse = concat . reverse . groupBy (const isMark)

"Function to reverse a string while preserving Unicode combining characters. For instance, it transforms 'asdf' into 'fdsa' and 'as⃝df̅' into 'f̅ds⃝a'. The function is optimized using a helper function with an accumulator argument, and it uses 'groupBy (const isMark)' for splitting a string into its combined characters."