The situation…
The fastest penguins in the world have just swum for the ultimate prize in professional penguin swimming.
The cameras that were capturing the race stopped recording half way through.
The athletes, and the fans are in disarray waiting for the results.
The challenge…
Given the last recorded frame of the race, and an array of penguin athletes, work out the gold, silver and bronze medal positions.
The rules…
Assume all penguins swim at the same speed.
Waves (~) take twice as long to swim through as smooth water (-).
Penguins (p or P) are racing from left to right.
There can be any number of lanes, and the race can be any length.
All Lanes in a single race will be the same length.
Penguin names are in the same order as the lanes.
Return a string in this format: “GOLD:
There will always be an equal amount of penguins and lanes.
There will always be a top three (no draws).
Examples…
Snapshot:
|—-p—~———|
|—-p———–|
|—-p—~~~——-|
Penguins:
[“Derek”, “Francis”, “Bob”]
Expected Output:
“GOLD: Derek, SILVER: Francis, BRONZE: Bob”
Snapshot:
|-————~–P——-|–~P————~——-|
|
|——–~-P—————|
|——–~-P—-~~~——–|
Penguins:
[“Joline”, “Abigail”, “Jane”, “Gerry”]
Expected Output:
“GOLD: Joline, SILVER: Jane, BRONZE: Gerry”
题目分析:
这道题目很可爱,是用字符串画出小企鹅们游泳的瞬间,然后计算谁游得最快,排列出一二三名!
我的思路是,先将字符串切割,把每只企鹅剩下的路程拿出来,然后算出要花多长时间,最后再找出时间最短的就可以了~
代码
c-sharp
using System;
using System.Linq;
using System.Collections.Generic;
namespace Solution
{
class SwimmingRace
{
public static string CalculateWinners(string snapshot, string[] penguins)
{
Dictionary<string,int> dict=new Dictionary<string,int>();
List<string> snapshots=snapshot.ToLower().Split("\n").ToList();
for(int i=0;i<snapshots.Count;i++)
{
string s = snapshots[i];
int index = s.IndexOf('p');
string remainder = s.Substring(index);
int time = remainder.Where(c=>c=='-').Count() + remainder.Where(c=>c=='~').Count()*2;
dict.Add(penguins[i], time);
}
List<string> names = dict.OrderBy(p=>p.Value).Select(p=>p.Key).ToList();
string s1=names[0];
string s2=names[1];
string s3=names[2];
string output=string.Format("GOLD: {0}, SILVER: {1}, BRONZE: {2}",s1,s2,s3);
return output;
}
}
}
知识点
1.IndexOf、Substring的用法
2.字典按值排序
3.注意select和where用法的区别