use*_*560 1 c# linq-to-objects
首先,我要向Marc Gravel,Dahlbyk和其他人表示衷心的感谢,帮助我实际应用linq.
以下是我在面试中遇到的几个问题,以解决应用Linq问题.因为我不熟悉Linq,所以我在不使用Linq的情况下解决了它.
我很欣赏能帮助我使用Linq解决问题的答案
提前致谢.
3,5,7,11,13或17.
为了确保没有任何矛盾,假设三个数字是a,b和c.然后,没有数字的组合:
说abc,acb,bac,bca,cab和cba将除以3,5,7,11,13或17.
示例:
当我拿248时,它的任何组合(284,428,482,842,824)都不会被3,5,7,11,13或17整除.
public void FindingRareNumbers()
{
for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
for (int k = 1; k <= 9; k++)
{
//to form the three digit
string digit = i.ToString() + j.ToString() + k.ToString();
//converting to integer
int StrToDigit = Convert.ToInt32(digit);
char[] digitcombination = digit.ToCharArray();
string PossibleCombination = "";
bool testpassed = false;
int dcount = 0;
#region different possible combinations
for (int p = 0; p <= 2; p++)
{
for (int q = 0; q <= 2; q++)
{
for (int r = 0; r <= 2; r++)
{
// The following condition avoid the repeatance
// of digit like 111,111,111
if (p != q && p != r && r != q)
{
PossibleCombination =
digitcombination[p].ToString() +
digitcombination[q].ToString() +
digitcombination[r].ToString();
int num = Convert.ToInt32(PossibleCombination);
if (num % 3 != 0 && num % 5 != 0 && num % 7 != 0
&& num % 11 != 0 && num % 11 != 0
&& num % 13 != 0 && num % 17 != 0)
{
//count is increment for 6 times
// it satisfies the condition
dcount++;
testpassed = true;
}
}
}
}
}
#endregion combination
if (testpassed && dcount==6)
{
Console.WriteLine(StrToDigit);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
(编码工作)
问题2:
任务是将元素排列在矩阵中,以便所有行,列和对角线加起来相同的总数.(编码中的位问题,我试图解决它).
------------------
1 2 3
-----------------
4 5 6
-----------------
7 8 9
-----------------
Run Code Online (Sandbox Code Playgroud)
例如:
解决方案之一如下:
-----------
2 9 4
-----------
7 5 3
----------
6 1 8
----------
Run Code Online (Sandbox Code Playgroud)
我同意Marc对你的第一个问题的解决方案是一种合理的方法.但我认为这里有一个更大的问题,那就是"如何以LINQ-ish的方式解决这样的问题呢?"
请注意您的解决方案是完全"程序性的"和"必要的".您的代码指定了一系列步骤,您将使用深循环一个接一个地执行这些步骤.除非你了解它在更大的整体中的位置,否则沿途的每一步都是毫无意义的.
在解决LINQ问题时,我喜欢使用两个想法:
那么,我们的数据集是什么?我们希望从三位数的所有组合的集合中过滤掉一些元素.
我们如何过滤它们?置换数字,然后对每个排列执行可分性检查.
好的,现在我们的程序结构如下:
var query = from c in ThreeDigitCombinations()
where DivisibilityCheckPasses(c)
select c;
foreach(Combination result in query) Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)
现在你可以继续分解每一个,依次使用LINQ解决每个子问题.
你的"魔方"问题也是如此; 你正在寻找具有某种属性的排列,所以编写一个排列生成器,编写一个过滤器,然后执行它.
| 归档时间: |
|
| 查看次数: |
703 次 |
| 最近记录: |