我想要做的是在兩側得到1到20之間的直角三角形的數量。C#比較列表對象和傳遞的參數
大部分的邏輯是好的,但是當我想檢查3,4和5時,這是一個三角形,而4,3和5將不是有效的,因爲它是3,4,5以不同的順序。
這裏是我剛纔的情況下,任何人的問題區域
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
bool breakLoop = false;
Int32 length = triangleList.Count;
for (int index = 0; index < length && breakLoop != false; index++)
{
//This is to compare an existing adjacent that is stored in the list to the
//supplied opposite, this is to prebent the 3, 4, 5 and 4, 3, 5 issue
var response = triangleList.Find(r => r.IntAdjacent == intOpp);
if (response !=null)
{
//This is to compare an existing opposite that is stored in the list to the
//supplied adjacent, this is to prebent the 3, 4, 5 and 4, 3, 5 issue
var otherResponse = triangleList.Find(r => r.IntOpposite == intAdj);
if (otherResponse != null)
{
breakLoop = true;
}
}
}
return breakLoop;
}
書面需要三角碼的代碼,這裏是
public class Triangle
{
private int intAdjacent;
private int intOpposite;
private int intHypotenuse;
public Triangle(int intAdjacent, int intOpposite, int intHypotenuse)
{
this.intAdjacent = intAdjacent;
this.intOpposite = intOpposite;
this.intHypotenuse = intHypotenuse;
}
public int IntAdjacent
{
get { return intAdjacent; }
}
public int IntOpposite
{
get { return intOpposite; }
}
public int IntHypotenuse
{
get { return intHypotenuse; }
}
}
可能有人當場看到我我在邏輯中犯了錯誤還是在代碼本身中犯了錯誤?如果他們不這樣做
public bool isAlreadyValidTriangle(int intAdj, int intOpp, List<Triangle> triangleList)
{
if(triangleList.Any(t => t.IntAdjacent == intAdj && t.IntOpposite == intOpp))
return true;
return triangleList.Any(t => t.IntAdjacent == intOpp && t.IntOpposite == intAdj);
}
它首先對於其中傳遞的值是符合的比賽,然後反轉搜索: 基思
「我想要做的是在兩側獲得1到20之間的直角三角形的數量。」回頭看看你自己,並認爲一個三角形有三面。這些都不能通過術語「兩者」來解決。您是否在尋找所有面短於20的三角形?列表不是無限的嗎? – spender
你能否澄清你的目標究竟是什麼,你期待什麼結果以及實際問題是什麼? – vesan
由於您的方法有點不對,代碼無法正確工作。說這個,因爲你正在搜索整個列表,可能包含許多帶有值加載的對象,所以Find方法在任何找到它的地方返回一個值,而不是在特定的索引中。您必須改爲比較列表中每個特定索引的值。 – Transcendent