我有一個連續的 N 個固定尺寸的垂直和水平部分的串列,以一系列方向的形式(右→;左←;下↓;上↑)。如果這些部分相交,程式應該回傳 true。例如:N = 6: { 上、左、下、下、右、上} - 回傳 True。我得到了每個部分的坐標,但我真的不知道如何完成這個。有什么想法嗎?
static (int, int) GetCoordinates(string[] sectionDirection, int numberOfSections)
{
(int X, int Y) pos = (0, 0);
foreach (string move in sectionDirection)
{
switch (move)
{
case "left":
pos = (0, 0);
pos.X--;
break;
case "right":
pos = (0, 0);
pos.X ;
break;
case "down":
pos = (0, 0);
pos.Y--;
break;
case "up":
pos = (0, 0);
pos.Y ;
break;
}
}
return (pos.X, pos.Y);
}
static bool CheckSectionsIntersect(string[] sectionDirection, int numberOfSections)
{
// I need help here.
}
uj5u.com熱心網友回復:
我能想到的最簡單的代碼更改是使用能夠記住所有訪問過的位置并且可以告訴您之前是否訪問過某個位置的東西。這樣的物件需要一種將位置添加到其記憶體中的方法,并且需要一種方法來測驗是否記住了某個位置。
信不信由你,你可以用它string來做到這一點。因為元組將轉換為字串,就像(0, 0)用括號和逗號分隔欄位一樣,可以將它們全部連接成一個字串,然后用于string.Contains查看位置是否存在。(這有點愚蠢,為了提高效率,我更喜歡 HashSet 而不是字串,但你在評論中說你不能。)
它將建立一個看起來像這樣的字串:
(0, 0)(0, 1)(-1, 1)(-1, 0)...
要記住一個位置,請使用運算子將??其附加到字串的末尾 =。當您這樣做時memory = pos,pos將自動使用ToString().
要檢查位置是否存在,請使用memory.Contains(pos.ToString()). 在這種情況下,您必須將元組顯式轉換為字串,.ToString()以將其作為引數傳遞給.Contains.
private static bool CheckForIntersections(string[] sectionDirection)
{
string memory = "";
(int X, int Y) pos = (0, 0);
memory = pos;
foreach (string move in sectionDirection)
{
switch (move)
{
case "left":
pos.X--;
break;
case "right":
pos.X ;
break;
case "down":
pos.Y--;
break;
case "up":
pos.Y ;
break;
}
if (memory.Contains(pos.ToString())) return true; // It was revisited
memory = pos;
}
return false;
}
uj5u.com熱心網友回復:
這就是我基本上在一行中完成的方式。
public static (int x, int y)[] GetCoordinates(Directions directions)
{
// accumulate a list with coordinates here
}
public static bool Intersect(params Direction[] directions)
{
var coord = GetCoordinates(directions);
return coord.Distinct().Count() < coord.Count();
}
通過查看不同值集的元素是否少于完整坐標集,檢查是否有任何坐標重復。
PS。我更喜歡enum用于具有有限值的事物,例如方向
public enum Direction
{
None,
Left,
Right,
Up,
Down,
}
uj5u.com熱心網友回復:
想象一下自己在一個無限大的棋盤上,有人告訴你朝著他告訴你的任何方向邁出一步。知道你是否已經越過一個點的唯一方法是在你通過的每個點上放一些東西,如果你得到命令去這個點,你喊“相交!” :-)
如果只是回到你的起點,你只需計算你收到的命令數量:如果“up”的數量等于“down”的數量,“left”的數量等于數量的“正確”,你知道你已經到達你的起點。
如果不允許保留四個計數器,則可以使用兩個變數“hor”(用于水平)和“ver”(用于垂直):
up means ver
down means ver--
left means hor--
right means hor
如果最后,“hor”和“ver”都歸零,那么你又回到了起點。
玩得開心 :-)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496460.html
上一篇:不能在BMI計算器中使用浮點數
