Guest User

Reddit Daily Programmer - Gravitational Force

a guest
Jun 15th, 2014
437
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function New-Planet
  2. {
  3.     param
  4.     (
  5.         [string]$Name,
  6.         [int]$Density,
  7.         [int]$Radius
  8.     )
  9.  
  10.     $planet = New-Object -TypeName PSObject
  11.     $planet | Add-Member -MemberType NoteProperty -Name Name -Value $Name
  12.     $planet | Add-Member -MemberType NoteProperty -Name Density -Value $Density
  13.     $planet | Add-Member -MemberType NoteProperty -Name Radius -Value $Radius  
  14.     $planet | Add-Member -MemberType NoteProperty -Name Volume -Value ((4/3)  * [math]::pi * [math]::pow($radius, 3))  
  15.     $planet | Add-Member -MemberType NoteProperty -Name Mass -Value ($planet.Volume * $planet.Density)
  16.    
  17.     $planet
  18. }
  19.  
  20. Function Get-GravitationalForce
  21. {
  22.     param
  23.     (
  24.         [double]$G = 6.67E-11,
  25.         [Parameter(Mandatory=$true)][double]$mass,
  26.         [Parameter(Mandatory=$true, ValueFromPipeline=$true)][PSObject]$Planet
  27.     )
  28.    
  29.     # Format the result of the equation with no more than 3 decimal places
  30.     $gravitationalForce = "{0:N3}" -f
  31.       ($G * (($mass * $Planet.Mass) / [math]::pow($Planet.Radius, 2)))
  32.    
  33.     Write-Output "$($Planet.Name): $gravitationalForce"
  34. }
  35.  
  36. Function SolveForReddit
  37. {
  38.     param
  39.     (
  40.         $inputString
  41.     )
  42.    
  43.     $lines = $inputString -split '[\r\n]'
  44.        
  45.     if($lines.Count -lt 3)
  46.     {
  47.         Write-Error "Must have at least 3 lines."
  48.     }
  49.    
  50.     # Foreach planet line, split the inputs to create a new planet,
  51.     # and feed that planet into the gravitational force function.
  52.     $lines[2..$lines.Count] |
  53.     % {
  54.         $input = $_ -split ", "
  55.         New-Planet -Name $input[0] -Radius $input[1] -Density $input[2] |
  56.             % { Get-GravitationalForce -mass $lines[0] -Planet $_ }
  57.       }
  58. }
Add Comment
Please, Sign In to add comment