2008脚本大赛PowerShell高级组Event 1解题及分析

来源:互联网 发布:三级卫生网络 编辑:程序博客网 时间:2024/05/17 00:50

中文题目位置: http://www.microsoft.com/technet/scriptcenter/funzone/games/games08/chs/aevent1.mspx

英文解题: http://www.microsoft.com/technet/scriptcenter/funzone/games/solutions08/apssol01.mspx

题目比较容易, 官方解题思路很好. 我的办法

Map-WordToDigit可以将一组字符映射为键盘上的数字. 然后将wordlist.txt中符合要求的单词(长度为7, 并且只包含规定的字符)利用Map-WordToDigit变换为对应的电话号码. 这样hash表的键是电话号码, 而值是单词. 最后利用用户输入的电话直接在hash表中查找即可. 唯一注意的就是PowerShell中对字符串的迭代要求显示取得迭代器.

$ofs = ''
$hash = @{}
$maps = @{
= 2;b = 2; c = 2;
= 3;e = 3;f = 3;
= 4;h = 4;i = 4;
= 5;k = 5;l = 5;
= 6;n = 6;o = 6;
= 7;r = 7;s = 7;
= 7;u = 8;v = 8;
= 9;x = 9;y = 9;
}
# construct a regular expression characters range
$charRange = "[$($maps.keys)]"
function 
Map-WordToDigit ($word)
{
$digits = $word.GetEnumerator() | % { $maps[$_.ToString()] };
"$digits";
}
# dirty pipeline to cache all of valid words in wordlist.txt. 
Get-Content -Path C:Scriptswordlist.txt | ? { (($_.length -eq 7-and ($_ -imatch "^$charRange+`$")) } | `
%{$key = Map-WordToDigit $_$hash[$key= $_}
$phoneNumber = Read-Host "Please enter your phone number"
$hash[$phoneNumber]

原创粉丝点击