因缺乏看似合理的编程逻辑而感到困惑。
在SSIS的脚本任务中。需要做一些数据转换......如下..
switch(LeadTime)
{
case: 1
WM1 = DAY1
WM2 = DAY2
WM3 = DAY3
WM4 = DAY4
WM5 = DAY5
WM6 = DAY6
WM7 = DAY7
case: 2
WM1 = DAY1 + DAY2
WM2 = DAY2 + DAY3
WM3 = DAY3 + DAY4
WM4 = DAY4 + DAY5
WM5 = DAY5 + DAY6
WM6 = DAY6 + DAY7
WM7 = DAY7 + DAY1
case: 3
WM1 = DAY1 + DAY2 + DAY3
WM2 = DAY2 + DAY3 + DAY4
WM3 = DAY3 + DAY4 + DAY5
WM4 = DAY4 + DAY5 + DAY6
WM5 = DAY5 + DAY6 + DAY7
WM6 = DAY6 + DAY7 + DAY1
WM7 = DAY7 + DAY1 + DAY2
..................
case: 7
WM1 = DAY1 + DAY2 + DAY3 + DAY4 + DAY5 + DAY6 + DAY7
WM2 = DAY2 + DAY3 + DAY4 + DAY5 + DAY6 + DAY7 + DAY1
WM3 = DAY3 + DAY4 + DAY5 + DAY6 + DAY7 + DAY1 + DAY2
WM4 = DAY4 + DAY5 + DAY6 + DAY7 + DAY1 + DAY2 + DAY3
WM5 = DAY5 + DAY6 + DAY7 + DAY1 + DAY2 + DAY3 + DAY4
WM6 = DAY6 + DAY7 + DAY1 + DAY2 + DAY3 + DAY4 + DAY5
WM7 = DAY7 + DAY1 + DAY2 + DAY3 + DAY4 + DAY5 + DAY6
}
如何围绕此构建循环以使其成为良好的编程?我不知所措,因为它在中间价值之后从两端增加..
这就是我所能做的一切! :o
case: 7
for(int i=0;i<LeadTime;i++)
{
WM1 += Array[i];
WM2 += Array[i];
...
WM7 += Array[i];
}
答案 0 :(得分:6)
您可以使用modulo进行环绕。这应该适用于所有人:
WM = new int[7];
for (int i = 0; i < LeadTime; i++) {
for (int j = 0; j < WM.Length; j++) {
WM[j] += Array[(i + j) % 7];
}
}
答案 1 :(得分:4)
这样的事情应该适用于所有情况(假设数组基于零):
for(int i=0;i<LeadTime;i++)
{
WM1 += Array[(0+i)%7];
WM2 += Array[(1+i)%7];
...
WM7 += Array[(6+i)%7];
}
答案 2 :(得分:4)
您要做的是创建一个可以针对不同情况调用的函数。
function foo(int LeadTime) {
for(int i=0; i < LeadTime; i++){
int k = i;
for (int j = 0; j < LeadTime; j++){
if (k > 7) { k = 1; }
wm[i] += day[k];
k++;
}
}
}
答案 3 :(得分:2)
我很快就想出了这段代码。基本上你将不得不做一个嵌套循环
string[] days = new string[] { "DAY1", "DAY2", "DAY3", "DAY4", "DAY5", "DAY6", "DAY7" };
List<string> res = new List<string>();
res.Add(string.Empty);
int Leadtime = 7;
for (int i = 1; i <= Leadtime; i++)
{
res.Add(string.Empty);
int tmp = i + Leadtime - 1;
for (int x = i; x <= tmp; x++)
{
if (x > Leadtime) { x = 1; tmp = i-1; }
res[i] += " " + days[x-1];
}
}
foreach (string s in res)
{
Console.WriteLine(s);
}
Console.ReadKey();
结果:
DAY1 DAY2 DAY3 DAY4 DAY5 DAY6 DAY7
DAY2 DAY3 DAY4 DAY5 DAY6 DAY7 DAY1
DAY3 DAY4 DAY5 DAY6 DAY7 DAY1 DAY2
DAY4 DAY5 DAY6 DAY7 DAY1 DAY2 DAY3
DAY5 DAY6 DAY7 DAY1 DAY2 DAY3 DAY4
DAY6 DAY7 DAY1 DAY2 DAY3 DAY4 DAY5
DAY7 DAY1 DAY2 DAY3 DAY4 DAY5 DAY6