exercism / powershell

Exercism exercises in Windows PowerShell.
https://exercism.org/tracks/powershell
MIT License
39 stars 47 forks source link

Building a training set of tags for powershell #304

Closed ErikSchierboom closed 11 months ago

ErikSchierboom commented 11 months ago

Hello lovely maintainers :wave:

We've recently added "tags" to student's solutions. These express the constructs, paradigms and techniques that a solution uses. We are going to be using these tags for lots of things including filtering, pointing a student to alternative approaches, and much more.

In order to do this, we've built out a full AST-based tagger in C#, which has allowed us to do things like detect recursion or bit shifting. We've set things up so other tracks can do the same for their languages, but its a lot of work, and we've determined that actually it may be unnecessary. Instead we think that we can use machine learning to achieve tagging with good enough results. We've fine-tuned a model that can determine the correct tags for C# from the examples with a high success rate. It's also doing reasonably well in an untrained state for other languages. We think that with only a few examples per language, we can potentially get some quite good results, and that we can then refine things further as we go.

I released a new video on the Insiders page that talks through this in more detail.

We're going to be adding a fully-fledged UI in the coming weeks that allow maintainers and mentors to tag solutions and create training sets for the neural networks, but to start with, we're hoping you would be willing to manually tag 20 solutions for this track. In this post we'll add 20 comments, each with a student's solution, and the tags our model has generated. Your mission (should you choose to accept it) is to edit the tags on each issue, removing any incorrect ones, and add any that are missing. In order to build one model that performs well across languages, it's best if you stick as closely as possible to the C# tags as you can. Those are listed here. If you want to add extra tags, that's totally fine, but please don't arbitrarily reword existing tags, even if you don't like what Erik's chosen, as it'll just make it less likely that your language gets the correct tags assigned by the neural network.


To summarise - there are two paths forward for this issue:

  1. You're up for helping: Add a comment saying you're up for helping. Update the tags some time in the next few days. Add a comment when you're done. We'll then add them to our training set and move forward.
  2. You not up for helping: No problem! Just please add a comment letting us know :)

If you tell us you're not able/wanting to help or there's no comment added, we'll automatically crowd-source this in a week or so.

Finally, if you have questions or want to discuss things, it would be best done on the forum, so the knowledge can be shared across all maintainers in all tracks.

Thanks for your help! :blue_heart:


Note: Meta discussion on the forum

ErikSchierboom commented 11 months ago

Exercise: hello-world

Code

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "HelloWorldTest" {
    It "Outputs: 'Hello, World!'" {
        Get-HelloWorld | Should be 'Hello, World!'
    }

    It "Outputs: Hello, Alice!" {
        Get-HelloWorld 'Alice' | Should be 'Hello, Alice!'
    }

    It "Outputs: Hello, Bob!" {
        Get-HelloWorld -person 'Bob' | Should be 'Hello, Bob!'
    }
}

Tags:

construct:assignment
construct:backtick-escape
construct:command
construct:invocation
construct:method
construct:pipeline
construct:string
construct:variable
paradigm:imperative
technique:regular-expressions
uses:Regex
ErikSchierboom commented 11 months ago

Exercise: reverse-string

Code


$global:text = $null

function Get-reverseString {

    $global:text = Read-Host "What string are we reversing?"

    $text = $text.ToCharArray()
    [array]::reverse($text)
    -join $text
}

Tags:

construct:array
construct:assignment
construct:explicit-conversion
construct:function
construct:global-variable
construct:invocation
construct:method
construct:null
construct:nullability
construct:parameter
construct:string
construct:variable
construct:visibility-modifiers
paradigm:imperative
technique:type-conversion
ErikSchierboom commented 11 months ago

Exercise: reverse-string

Code

Function Get-ReverseString {
    <#
    .SYNOPSIS
    Reverse a string

    .DESCRIPTION
    Reverses the string in its entirety. That is it does not reverse each word in a string individually.

    .PARAMETER Forward
    The string to be reversed

    .EXAMPLE
    Get-ReverseString "PowerShell"

    This will return llehSrewoP

    .EXAMPLE
    Get-ReverseString "racecar"

    This will return racecar as it is a palindrome
    #>
    [CmdletBinding()]
    Param(
        [Parameter(Position=1, ValueFromPipeline=$true)]
        [string]$Forward
    )

    Throw "Function not implemented"
}

Tags:

construct:assignment
construct:boolean
construct:comment
construct:custom-attribute
construct:function
construct:multiline-comment
construct:parameter
construct:position
construct:throw
construct:throw-expression
construct:variable
construct:visibility-modifiers
paradigm:imperative
technique:exceptions
ErikSchierboom commented 11 months ago

Exercise: reverse-string

Code

Function Get-ReverseString {
    <#
    .SYNOPSIS
    Reverse a string

    .DESCRIPTION
    Reverses the string in its entirety. That is it does not reverse each word in a string individually.

    .PARAMETER Forward
    The string to be reversed

    .EXAMPLE
    Get-ReverseString "PowerShell"

    This will return llehSrewoP

    .EXAMPLE
    Get-ReverseString "racecar"

    This will return racecar as it is a palindrome
    #>
    [CmdletBinding()]
    Param(
        [Parameter(Position=1, ValueFromPipeline=$true)]
        [string]$Forward
    )

    For ($i = $Forward.Length - 1; $i -ge 0; $i--) {
        $Reversed = $Reversed + $Forward[$i]
    }

    $Reversed
}

Tags:

construct:add
construct:assignment
construct:attribute
construct:comment
construct:for-loop
construct:function
construct:parameter
construct:position
construct:string
construct:subtract
construct:variable
construct:visibility-modifiers
paradigm:imperative
technique:looping
ErikSchierboom commented 11 months ago

Exercise: leap

Code

function leap-year {
    do
    {
          $year = read-host "What year would you like to test?"
          write-host "To end session at any time type 'end'"

             if ($year % 4 -eq 0) 
             {
                write-host "$year is a leap year; divisible by 4"
             }
             elseif (($year % 400 -eq 0) -and ($year % 100 -eq 0))
             {
                write-host "$year is a leap year; divisible by 400 and 100"
             }
             else
             {
                Write-Host "$year is not a leap year"
             }
    } until ($year -like "end")
}Clear-host

Tags:

construct:boolean
construct:clear-host
construct:do-until-loop
construct:function
construct:if
construct:invocation
construct:logical-and
construct:number
construct:divide
construct:read-host
construct:string
construct:variable
construct:write-host
construct:pattern-matching
paradigm:imperative
paradigm:looping
technique:boolean-logic
technique:looping
ErikSchierboom commented 11 months ago

Exercise: leap

Code

function Test-LeapYear {
    <#
    .SYNOPSIS
    Given a year, report if it is a leap year.

    .DESCRIPTION
    Calculate whether the supplied year is a leap year. A leap year is determined from the following
    calculation:

    on every year that is evenly divisible by 4
    except every year that is evenly divisible by 100
    unless the year is also evenly divisible by 400

    .PARAMETER year
    The year to test

    .EXAMPLE
    Test-LeapYear -year 2018

    Returns false

    .EXAMPLE
    Test-LeapYear -year 2020

    Returns True
    #>
    param( [int]$year )

    if(($year %4) -eq 0 -and ($year%100) -ne 0 -or ($year%400) -eq 0){
    return "$year is a leapyear"
    }else{
    return "$year is not a leapyear"
    }
}

Tags:

construct:and
construct:boolean
construct:comment
construct:divide
construct:else
construct:expression
construct:function
construct:if
construct:int
construct:integral-number
construct:logical-and
construct:logical-or
construct:number
construct:parameter
construct:return
construct:string
construct:year
paradigm:imperative
technique:boolean-logic
ErikSchierboom commented 11 months ago

Exercise: bob

Code

function get-bobresponse{

param([string] $answer)

$isquestion = $answer.EndsWith("?")
$isyelling = $answer.ToUpper() -ceq $answer
$isnothing = (([System.String]))::IsNullOrWhiteSpace($answer)

if ($isquestion -and $isyelling )
{
Write-Host "shutup"
}

elseif ($isquestion)
{
Write-Host "sure"
}

elseif ($isnothing)
{
Write-Host "Fine, be that way"
}
elseif($isyelling)
{
Write-Host "Whoa, chill out"
}

else
{ write-host "method not found"

}

}

Tags:

construct:boolean
construct:class
construct:constructor
construct:downcast
construct:elseif
construct:function
construct:if
construct:invocation
construct:method
construct:parameter
construct:string
construct:throw
construct:try
construct:variable
construct:visibility-modifiers
paradigm:object-oriented
technique:exceptions
technique:inheritance
ErikSchierboom commented 11 months ago

Exercise: bob

Code

Function Get-BobResponse() {

[CmdletBinding()]
Param([string]$HeyBob)
$isEmptyOrWhitespace = (([System.String]::IsNullOrWhiteSpace($HeyBob) -eq $HeyBob) -or ([System.String]::Empty -eq $HeyBob))
$isUpper = $HeyBob.ToUpper() -ceq $HeyBob
$isQuestion = $HeyBob.EndsWith("?") -or $HeyBob.Contains("?")
$isYelling = $HeyBob.EndsWith("!")

   if ($isUpper -and $isQuestion) {$result = "Calm down, I know what I'm doing!"}
   elseif ($isQuestion) {$result = "Sure"}
   elseif ($isYelling -and $isUpper) {$result = "Whoa, chill out!"}
   elseif ($isEmptyOrWhitespace) {$result = "Fine. Be that way!"}
   else {$result = "Whatever"}

Return write-host ($result)
Throw "Function not implemented"
}

Tags:

construct:boolean
construct:cmdlet
construct:constructor
construct:method
construct:parameter
construct:powershell
construct:string
construct:throw
construct:throw-statement
construct:visibility-modifiers
paradigm:object-oriented
technique:exceptions
ErikSchierboom commented 11 months ago

Exercise: sum-of-multiples

Code

Function Get-SumOfMultiples {
    <#
    .SYNOPSIS
    Given a number, find the sum of all the unique multiples of particular numbers up to
    but not including that number.

    .DESCRIPTION
    If we list all the natural numbers below 20 that are multiples of 3 or 5,
    we get 3, 5, 6, 9, 10, 12, 15, and 18.

    .PARAMETER Multiples
    An array of the factors 

    .PARAMETER Limit
    The value BELOW which we test for

    .EXAMPLE
    Get-SumOfMultiples -Multiples @(3, 5) -Limit 10

    Returns 23
    #>
    [CmdletBinding()]
    Param(
        [int[]]$Multiples,
        [int]$Limit
    )

    if ($Multiples.Length -eq 0) {
        return 0
    }

    $Multiples = $Multiples | Sort-Object
    $Sum = 0
    for ($i = $Multiples[0]; $i -lt $Limit; $i++) {
        foreach ($Number in $Multiples) {
            if ($i % $Number -eq 0) {
                $Sum += $i
                break
            }
        }
    }

    return $Sum
}

Tags:

construct:assignment
construct:break
construct:cmdlet
construct:comment
construct:for-loop
construct:foreach
construct:function
construct:if
construct:indexer
construct:invocation
construct:method
construct:number
construct:parameter
construct:pipeline
construct:return
construct:subtract
construct:variable
construct:visibility-modifier
paradigm:imperative
paradigm:functional
paradigm:object-oriented
technique:looping
ErikSchierboom commented 11 months ago

Exercise: sum-of-multiples

Code

Function Get-SumOfMultiples {
    <#
    .SYNOPSIS
    Given a number, find the sum of all the unique multiples of particular numbers up to
    but not including that number.

    .DESCRIPTION
    If we list all the natural numbers below 20 that are multiples of 3 or 5,
    we get 3, 5, 6, 9, 10, 12, 15, and 18.

    .PARAMETER Multiples
    An array of the factors 

    .PARAMETER Limit
    The value BELOW which we test for

    .EXAMPLE
    Get-SumOfMultiples -Multiples @(3, 5) -Limit 10

    Returns 23
    #>
    [CmdletBinding()]
    Param(
        [int[]]$Multiples,
        [int]$Limit

    )

    $res = 0;

    for ($i = 1; $i -lt $Limit; $i++) {    #goes through all numbers smaller than the Limit
        for ($m = 0; $m -lt $Multiples.Length; $m++){   #goes through all Numbers of $Multiples
            if ($i % $Multiples[$m] -eq 0){     #checks if the number is a multiple of one of the given in $Multiples
                $res = $res + $i;   
                break;      #go out of the Loop, so if the number is an muliple of more than one number it doesn't get counted twice
            }
        }

    }
    return $res;

    Throw "Function not implemented"
}

Tags:

construct:add
construct:assignment
construct:attribute
construct:break
construct:cmdlet
construct:comment
construct:for-loop
construct:function
construct:if
construct:indexer
construct:int
construct:integral-number
construct:invocation
construct:loop
construct:number
construct:parameter
construct:return
construct:string
construct:throw
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:looping
ErikSchierboom commented 11 months ago

Exercise: raindrops

Code

Function Get-Raindrops() {
    <#
    .SYNOPSIS
    Given a number convert it to Pling, Plang, Plong if it has factors of 3, 5 or 7.

    .DESCRIPTION
    Convert a number to a string, the contents of which depend on the number's factors.

    - If the number has 3 as a factor, output 'Pling'.
    - If the number has 5 as a factor, output 'Plang'.
    - If the number has 7 as a factor, output 'Plong'.
    - If the number does not have 3, 5, or 7 as a factor, just pass the number's digits straight through.

    .PARAMETER Rain
    The number to evaluate

    .EXAMPLE
    Get-Raindrops -Rain 35

    This will return PlangPlong as it has factors of 5 and 7

    .EXAMPLE
    Get-Raindrops -Rain 12121

    This will return 12121 as it does not contain factors of 3, 5 or 7 so the value is passed through.
    #>
    [CmdletBinding()]
    Param(
        [int]$Rain
    )

    # Initialize the result
    [string]$Result = ""

    # Use a hashtable to list the factors and what they are replaced with
    $factorRain = @{
        3 = "Pling";
        5 = "Plang";
        7 = "Plong";
    }

    # Loop over the hashtable testing the factors and building up the result.
    # NOTE: You must sort hashtables if order is important. See: https://blogs.technet.microsoft.com/heyscriptingguy/2014/09/28/weekend-scripter-sorting-powershell-hash-tables/
    Foreach($factor in ($factorRain.GetEnumerator() | Sort-Object -Property Name)){
        If($Rain % $factor.Name -eq 0){
            $Result += $factor.Value
        }
    }

    # Deal with the case that no factors are found so passthrough the original value
    If ([string]::IsNullOrEmpty($Result)){
        $Result = $Rain.ToString()
    }

    # Return the resulting string
    Return $Result
}

Tags:

construct:assignment
construct:attribute
construct:bitwise-and
construct:cmdlet
construct:comment
construct:constructor
construct:explicit-conversion
construct:expression
construct:foreach
construct:function
construct:hashtable
construct:if
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:bit-manipulation
technique:bit-shifting
technique:enumeration
technique:higher-order-functions
technique:looping
technique:type-conversion
uses:Hashtable
ErikSchierboom commented 11 months ago

Exercise: raindrops

Code

Function Get-Raindrops() {
    <#
    .SYNOPSIS
    Given a number convert it to Pling, Plang, Plong if it has factors of 3, 5 or 7.

    .DESCRIPTION
    Convert a number to a string, the contents of which depend on the number's factors.

    - If the number has 3 as a factor, output 'Pling'.
    - If the number has 5 as a factor, output 'Plang'.
    - If the number has 7 as a factor, output 'Plong'.
    - If the number does not have 3, 5, or 7 as a factor, just pass the number's digits straight through.

    .PARAMETER Rain
    The number to evaluate

    .EXAMPLE
    Get-Raindrops -Rain 35

    This will return PlangPlong as it has factors of 5 and 7

    .EXAMPLE
    Get-Raindrops -Rain 12121

    This will return 12121 as it does not contain factors of 3, 5 or 7 so the value is passed through.
    #>
    [CmdletBinding()]
    Param(
        [int]$Rain
    )
   #$asounds = [system.collections.arraylist]@('Pling','Plang''Plong')

   $rem = ($rain % 3)
   if($rem -eq 0){
   $result += 'Pling'
   }
   $rem2 =($rain % 5)
   if($rem2 -eq 0){
   $result += 'Plang'
   }
     $rem3 =($rain % 7)
   if($rem3 -eq 0){
   $result += 'Plong'
   }
   return $result
    Throw "Not implemented exception"
}

Tags:

construct:assignment
construct:attribute
construct:cmdlet
construct:comment
construct:function
construct:if
construct:int
construct:integral-number
construct:invocation
construct:parameter
construct:return
construct:string
construct:throw
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:exceptions
ErikSchierboom commented 11 months ago

Exercise: two-fer

Code

Function Get-TwoFer(){
    <#
    .SYNOPSIS
    "Two-fer" is short for two for one. One for you and one for me.

    .DESCRIPTION
    If the given name is "Alice", the result should be "One for Alice, one for me."
    If no name is given, the result should be "One for you, one for me."

    .PARAMETER Name
    The name to use.

    .EXAMPLE
    Get-TwoFer

    Will return: One for you, one for me

    .EXAMPLE
    Get-TwoFer -Name Alice

    Will return: One for Alice, one for me
    #>
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=0)]
        [AllowEmptyString()]
        [string]$Name
    )

    If ($Name -notlike $null) {
        return "One for $Name, one for me"
    }
    Else {
        return "One for you, one for me"
    }
}

Tags:

construct:boolean
construct:cmdlet
construct:comment
construct:function
construct:if
construct:invocation
construct:null
construct:null-literal
construct:parameter
construct:position
construct:return
construct:string
construct:template-string
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
ErikSchierboom commented 11 months ago

Exercise: two-fer

Code

Function Get-TwoFer([string]$name='you'){
$result='one for '+ $name+', one for me'
return $result
}

Tags:

construct:class
construct:method
construct:parameter
construct:return
construct:string
construct:throw
construct:using-directive
construct:visibility-modifiers
paradigm:object-oriented
technique:exceptions
ErikSchierboom commented 11 months ago

Exercise: nucleotide-count

Code

Function Get-NucleotideCount() {
    <#
    .SYNOPSIS
    Given a single stranded DNA string, compute how many times each nucleotide occurs in the string.

    .DESCRIPTION
    The genetic language of every living thing on the planet is DNA.
    DNA is a large molecule that is built from an extremely long sequence of individual elements called nucleotides.
    4 types exist in DNA and these differ only slightly and can be represented as the following symbols: 'A' for adenine, 'C' for cytosine, 'G' for guanine, and 'T' thymine.

    The function counts the occurances of A, C, G and T in the supplied strand. It then outputs in the format:

    A:0, C:0, G:0, T:0

    .PARAMETER Strand
    The DNA strand to count

    .EXAMPLE
    Get-NucleotideCount -Strand "ACGTAGCTT"

    Retuns: A:2 C:2 G:2 T:3
    #>
    [CmdletBinding()]
    Param(
        [string]$Strand
    )

    try {
        if ($Strand -match "^[ACGT]+$" -or $Strand -eq [String]::Empty) {
            $aCount = (Select-String -InputObject $Strand -Pattern "A" -AllMatches).Matches.Count
            $cCount = (Select-String -InputObject $Strand -Pattern "C" -AllMatches).Matches.Count
            $gCount = (Select-String -InputObject $Strand -Pattern "G" -AllMatches).Matches.Count
            $tCount = (Select-String -InputObject $Strand -Pattern "T" -AllMatches).Matches.Count

            return "A:$aCount C:$cCount G:$gCount T:$tCount"
        } else {
            throw "Invalid format"
        }
    }
    catch {
       throw
    }
}

Tags:

construct:assignment
construct:boolean
construct:catch
construct:class
construct:cmdlet
construct:comment
construct:constructor
construct:explicit-conversion
construct:function
construct:if
construct:implicit-conversion
construct:invocation
construct:logical-or
construct:method
construct:or
construct:parameter
construct:regex
construct:return
construct:string
construct:throw
construct:try
construct:try-catch
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:boolean-logic
technique:exceptions
technique:regular-expression
ErikSchierboom commented 11 months ago

Exercise: nucleotide-count

Code

Function Get-NucleotideCount() {
    <#
    .SYNOPSIS
    Given a single stranded DNA string, compute how many times each nucleotide occurs in the string.

    .DESCRIPTION
    The genetic language of every living thing on the planet is DNA.
    DNA is a large molecule that is built from an extremely long sequence of individual elements called nucleotides.
    4 types exist in DNA and these differ only slightly and can be represented as the following symbols: 'A' for adenine, 'C' for cytosine, 'G' for guanine, and 'T' thymine.

    The function counts the occurances of A, C, G and T in the supplied strand. It then outputs in the format:

    A:0, C:0, G:0, T:0

    .PARAMETER Strand
    The DNA strand to count

    .EXAMPLE
    Get-NucleotideCount -Strand "ACGTAGCTT"

    Retuns: A:2 C:2 G:2 T:3
    #>
    [CmdletBinding()]
    Param(
        [string]$Strand
    )

    $Adenine = 0
    $Cystosine = 0
    $Guanine = 0
    $Thymine = 0

    ForEach ($Character in $Strand.ToCharArray()){
        Switch ($Character){
            "A" {$Adenine++; Break}
            "C" {$Cystosine++; Break}
            "G" {$Guanine++; Break}
            "T" {$Thymine++; Break}
            Default {Throw}
        }
    }
    Return "A:$Adenine C:$Cystosine G:$Guanine T:$Thymine"
}

Tags:

construct:assignment
construct:attribute
construct:break
construct:char
construct:class
construct:comment
construct:for-loop
construct:foreach
construct:function
construct:implicit-conversion
construct:invocation
construct:method
construct:number
construct:parameter
construct:return
construct:string
construct:switch
construct:throw
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:looping
ErikSchierboom commented 11 months ago

Exercise: hamming

Code

function Compute ([string]$x, [string]$y) {
    if ($x.Length -NE $y.Length) {
        throw "Mismatching string lengths";
    }
    $distance=0;
    for ($i=0; $i -LT $x.Length; $i++) {
        if ($x[$i] -NE $y[$i]) {
            $distance++;
        }
    }
    return $distance;
}

Tags:

construct:assignment
construct:for-loop
construct:function
construct:if
construct:indexing
construct:int
construct:integral-number
construct:invocation
construct:parameter
construct:return
construct:string
construct:subtract
construct:throw
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:looping
ErikSchierboom commented 11 months ago

Exercise: grade-school

Code

<#
.SYNOPSIS
    Given students' names along with the grade that they are in, create a roster for the school.
.DESCRIPTION
    In the end, you should be able to:

    Add a student's name to the roster for a grade
    "Add Jim to grade 2."
    "OK."
    Get a list of all students enrolled in a grade
    "Which students are in grade 2?"
    "We've only got Jim just now."
    Get a sorted list of all students in all grades. Grades should sort as 1, 2, 3, etc., and students within a grade should be sorted alphabetically by name.
    "Who all is enrolled in school right now?"
    "Grade 1: Anna, Barb, and Charlie. Grade 2: Alex, Peter, and Zoe. Grade 3…"
    Note that all our students only have one name. (It's a small town, what do you want?)
.EXAMPLE
    PS C:\> $roster = [Roster]::new()
            $roster.AddStudent(1,'Billy')
            $roster.AddStudent(1,'Josh')
            $roster.AddStudent(2,'Allison')
            $roster.GetRoster()
            $roster.GetRoster(2)

            This will create a new roster and add 3 students to it.
            When no arguments are supplied to the GetRoster method, all students will be returned.
            When a grade number is supplied to the GetRoster method, students from that grade will be returned.
#>

class Student {
    [int]$Grade
    [string]$Name

    Student([int]$Grade, [string]$Name) {
        $this.Grade = $Grade
        $this.Name = $Name
    }
}

class Roster {    
    [student[]]$Student

    Roster() {
    }

    AddStudent([int]$Grade, [string]$Name){
        $this.Student += [student]::New($Grade, $Name)
    }

    [student[]] GetRoster(){
        return $this.Student | Sort-Object -Property Grade,Name
    }

    [student[]] GetRoster([int]$Grade){
        return $this.Student | Where-Object -Property Grade -EQ $Grade | Sort-Object -Property Name
    }
}

Tags:

construct:assignment
construct:class
construct:constructor
construct:explicit-conversion
construct:field
construct:implicit-conversion
construct:int
construct:integral-number
construct:invocation
construct:lambda
construct:method
construct:parameter
construct:property
construct:return
construct:string
construct:throw
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
technique:sorting
technique:types
uses:Student
ErikSchierboom commented 11 months ago

Exercise: grade-school

Code

<#
.SYNOPSIS
    Given students' names along with the grade that they are in, create a roster for the school.
.DESCRIPTION
    In the end, you should be able to:

    Add a student's name to the roster for a grade
    "Add Jim to grade 2."
    "OK."
    Get a list of all students enrolled in a grade
    "Which students are in grade 2?"
    "We've only got Jim just now."
    Get a sorted list of all students in all grades. Grades should sort as 1, 2, 3, etc., and students within a grade should be sorted alphabetically by name.
    "Who all is enrolled in school right now?"
    "Grade 1: Anna, Barb, and Charlie. Grade 2: Alex, Peter, and Zoe. Grade 3…"
    Note that all our students only have one name. (It's a small town, what do you want?)
.EXAMPLE
    PS C:\> $roster = [Roster]::new()
            $roster.AddStudent(1,'Billy')
            $roster.AddStudent(1,'Josh')
            $roster.AddStudent(2,'Allison')
            $roster.GetRoster()
            $roster.GetRoster(2)

            This will create a new roster and add 3 students to it.
            When no arguments are supplied to the GetRoster method, all students will be returned.
            When a grade number is supplied to the GetRoster method, students from that grade will be returned.
#>

class Student {
    [int] $Grade
    [string] $Name

    Student($grade, $name) {
        $this.Grade = $grade
        $this.Name = $name
    }
}

class Roster {
    [array] $Student

    AddStudent($grade, $name) {
        $this.Student += [Student]::new($grade, $name)
    }

    [Array] GetRoster() {
        Return $this.Student | Sort-Object -Property Grade, Name
    }
    [Array] GetRoster($grade) {
        Return $this.Student | Where-Object {$_.Grade -eq $grade} | Sort-Object -Property Name
    }
}

Tags:

construct:assignment
construct:class
construct:comment
construct:constructor
construct:explicit-conversion
construct:field
construct:generic-type
construct:invocation
construct:lambda
construct:method
construct:parameter
construct:pipe
construct:property
construct:return
construct:string
construct:throw
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
technique:sorting
technique:type-conversion
ErikSchierboom commented 11 months ago

Exercise: grade-school

Code

class Student {
    $Grade
    $Name 
}

class Roster {
        $student
        Roster() {
        $this.student=New-Object System.Collections.ArrayList($null)
        }
            addstudent([int]$grade,[string]$name){
            $studentv = [Student]::new()
            $studentv.grade = $grade
            $studentv.name = $Name
            $this.student += $studentv            
        }
    [array]GetRoster(){
            return $this.student | sort-object -Property Grade, Name
        }
    [array]GetRoster([int]$num){

    return $this.student | Where-Object -FilterScript { $_.grade -eq $num } | sort-object Name
        }
}

Tags:

construct:assignment
construct:class
construct:constructor
construct:explicit-conversion
construct:field
construct:invocation
construct:lambda
construct:method
construct:parameter
construct:property
construct:return
construct:string
construct:throw
construct:using-directive
construct:variable
construct:visibility-modifiers
paradigm:functional
paradigm:imperative
paradigm:object-oriented
technique:exceptions
technique:higher-order-functions
technique:sorting
technique:type-conversion
uses:ArrayList
uses:IComparer<T>
uses:Student
ErikSchierboom commented 11 months ago

This is an automated comment

Hello :wave: Next week we're going to start using the tagging work people are doing on these. If you've already completed the work, thank you! If you've not, but intend to this week, that's great! If you're not going to get round to doing it, and you've not yet posted a comment letting us know, could you please do so, so that we can find other people to do it. Thanks!

ErikSchierboom commented 11 months ago

Thanks for the help! We've updated the tags.