[英]How can I Achieve the following output with dynamic input values?
在我的辦公室進行了一次大獎編程活動,在那次活動中,他們問了 3 個問題,但其中一個謎題對我們來說真的很難,我只是為了自己的利益而嘗試
問題:
A = {10, 15, 25}
B = {1, 5, 20, 30}
預期輸出:
10 20
10 20 25 30
10 30
15 20
15 20 25 30
15 30
25 30
在輸出中:
10 20 --> A 的第一個元素和 B 的第一個最小元素,大於 A 的第一個元素
10 20 25 30 --> A的第一個元素檢查B數組,它大於A,然后再次檢查A,重復它直到B沒有比A更大的元素,如果B不需要以之前的 B 值結束。
10 30 --> A 的第一個元素和 B 的大於 A 的第一個元素的最大元素
上述方法將遍歷所有 A 元素。
這是我的解決方案,唯一沒有意義的是為什么他在第一組中跳過了 15 個,並且由於您沒有更多信息,我不得不假設跳過它的原因(稱之為例外)
int[] A = { 10, 15, 25 };
int[] B = { 1, 5, 20, 30 };
//10 20
//10 20 25 30
//10 30
//15 20
//15 20 25 30
//15 30
//25 30
var result = A.SelectMany(x => GetIllogicalPermutations(x, A, B)).DistinctBy(x => x.Sum());
for (int i = 0; i < result.Count(); i++)
{
Console.WriteLine(string.Join(' ', result.ElementAt(i).Select(x => x.ToString())));
}
Console.ReadLine();
static IEnumerable<int[]> GetIllogicalPermutations(int item, int[] setA, int[] setB)
{
yield return new int[] { item, setB.Where(x => x > item).Min() };
yield return setA.Where(x => x > item && x != (setA.Max() - setA.Min())).Concat(setB.Where(x => x > item)).Prepend(item).OrderBy(x => x).ToArray();
yield return new int[] { item, setB.Where(x => x > item).Max() };
}
如果我正確理解了您的問題,就像這樣
class Solution
{
int[] a;
int[] b;
public Solution(int[] a, int[] b)
{
this.a = a;
this.b = b;
}
void InterateA(int min, string output)
{
foreach (var a in a.OrderBy(n => n).SkipWhile(n => n <= min))
{
InterateB(a, $"{output}\t{a}");
}
}
void InterateB(int min, string output)
{
foreach (var b in b.OrderBy(n => n).SkipWhile(n => n <= min))
{
var str = $"{output} {b}";
Console.WriteLine(str);
InterateA(b, str);
}
output = null;
}
public void Print()
{
InterateA(a.OrderBy(n => n).First() - 1, null);
}
}
測試代碼
static void Main(string[] args)
{
var a = new int[] { 10, 15, 25, 35 };
var b = new int[] { 1, 5, 20, 30, 40 };
var solution = new Solution(a, b);
solution.Print();
Console.ReadKey();
}
性能是最低的,因為這是最初的微不足道的解決方案,如果它正確地完成了工作,可以對其進行優化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.