Skip to content

Instantly share code, notes, and snippets.

@k2works
Created May 9, 2020 01:17
Show Gist options
  • Save k2works/d5751e6bb933c8fc5c53690d1f7889d0 to your computer and use it in GitHub Desktop.
Save k2works/d5751e6bb933c8fc5c53690d1f7889d0 to your computer and use it in GitHub Desktop.
PowerShellで学ぶアルゴリズムとデータ構造-データ構造と配列
# https://qiita.com/opengl-8080/items/bb0f5e4f1c7ce045cc57
# データ構造と配列
Describe "TestTotal" {
It "5人の点数を読み込んで合計点・平均点を返す" {
Total 32 68 72 54 92 | Should Be '318,63.6'
}
}
function Total {
param (
[int] $tensu1,
[int] $tensu2,
[int] $tensu3,
[int] $tensu4,
[int] $tensu5
)
$result = ''
$total = 0
$total += $tensu1
$total += $tensu2
$total += $tensu3
$total += $tensu4
$total += $tensu5
$result = $total.ToString()
$result += ','
$result += ($total/5).ToString()
return $result
}
# 配列
Describe "TextMax" {
It "シーケンスaの要素の最大値を返却する" {
MaxOf @(172, 153, 192, 140, 165) | Should Be 192
}
}
function MaxOf {
param (
[array] $a
)
$maximum = $a[0]
foreach ($i in 1..$a.Length) {
if ($a[$i] -gt $maximum) {
$maximum = $a[$i]
}
}
return $maximum
}
Describe "TestReverseArray" {
It "ミュータブルなシーケンスaの要素の並びを反転" {
$a = @(2, 5, 1, 3, 9, 6, 7)
ReverseArray $a
$a | Should Be @(7, 6, 9, 3, 1, 5, 2)
}
}
function ReverseArray {
param (
[array] $a
)
$n = $a.Length - 1
foreach ($i in 0..($n / 2)) {
$a[$i], $a[$n - $i] = $a[$n - $i], $a[$i]
}
}
Describe "TestCardConv" {
It "整数値xをr進数に変換した数値を表す文字列を返却" {
CardConv 29 2 | Should Be '11101'
}
}
function CardConv {
param (
[int] $x,
[int] $r
)
$d = ''
$dchar = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
while ($x -gt 0) {
$d += $dchar[$x % $r]
$x = [Math]::Floor($x / $r)
}
return [string]::join("", $d[($d.Length - 1)..0])
}
Describe "TestChange" {
It "lst[idx]の値をvalに更新" {
$x = @(11, 22, 33, 44, 55)
Change $x 2 99
$x | Should Be @(11, 22, 99, 44, 55)
}
}
function Change {
param (
[array] $lst,
[int] $idx,
[int] $val
)
$lst[$idx] = $val
}
# 素数の列挙
Describe 'TestPrime' {
It 'x以下の素数を列挙(第1版)' {
Prime1 1000 | Should Be 77191
}
It 'x以下の素数を列挙(第2版)' {
Prime2 3 | Should Be @(2, 3)
Prime2 5 | Should Be @(2, 3, 5)
Prime2 7 | Should Be @(2, 3, 5, 7)
Prime2 9 | Should Be @(2, 3, 5, 7)
Prime2 11 | Should Be @(2, 3, 5, 7, 11)
Prime2 13 | Should Be @(2, 3, 5, 7, 11, 13)
}
}
function Prime1 {
param (
[int] $x
)
$counter = 0
foreach ($n in 2..$x) {
foreach ($i in 2..$n) {
if (($n % $i) -eq 0) {
break
}
$counter += 1
}
}
return $counter
}
function Prime2 {
param (
[int] $x
)
$prime = @()
$oddArray = 2..$x | % { if ($_ % 2 -ne 0) { @($_) } }
$checkArray = @()
if ($oddArray -is [array]) {
$checkArray = $oddArray + 2 | Sort-Object
}
else {
$checkArray = @(2, $oddArray)
}
foreach ($n in $checkArray) {
foreach ($i in 2..$n) {
if (($n % $i) -eq 0) {
if (!$prime.Contains($i)) { $prime += $i }
break
}
}
}
return $prime
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment