在正方形或矩形矩阵上添加对角线的算法,从右侧开始
我想在正方形或矩形矩阵中添加对角线,以模拟在乘法算法中添加部分结果的过程。
像这样:
2412
x 3231
---------
2412
7236
4824
+ 7236
---------
7793172
我需要一步一步地运行它,以满足在线判断程序的要求。我已经弄清楚如何获得乘法的部分结果(humbers 2412、7236、4824、7236),并将它们放在方阵上。
我意识到我可以通过考虑正方形或矩形来获得该矩阵的加法结果:
2 4 1 2
7 2 3 6
4 8 2 4
7 2 3 6
并通过添加每个对角线(从右上角开始)并考虑加法的进位并使用辅助来获得加法的结果与 number_of_digits_in_operand_a + number_of_digits_in_operand_b 具有相同位数的数组(在本例中,操作数 a 为 2412,操作数 b 为 3231)。
例如,数组结果在其最右边的位置应该是:
result[(digits_a+digits_b)-1] = partialResult[0][3];
next:
result[digits_a+digits_b]=(partialResult[0][2] + partialResult[1][3] + carry) %10;
newCarry = (partialResult[0][2] + partialResult[1][3] + carry) / 10;
好吧,我一直在编写双重嵌套循环,该循环应该从右上角开始添加这些对角线。帮助。请。
I want to add the diagonals in a square or rectangular matrix to emulate the process of adding the partial results in a multiplying algorithm.
Like this:
2412
x 3231
---------
2412
7236
4824
+ 7236
---------
7793172
I need to run this, step by step, to satisfy the requirements of an online judge program. I have already figured out how to get the partial results of the multiplications (the humbers 2412, 7236, 4824, 7236) and I have placed them on a square matrix.
I realized I can get the addition result of this matrix by considering square or rectangular like:
2 4 1 2
7 2 3 6
4 8 2 4
7 2 3 6
and get the result of the addition by adding each diagonal (starting with the upper right one) and taking into account the carry of the addition and using an auxiliary array that has the same number of digits as number_of_digits_in_operand_a + number_of_digits_in_operand_b (operand a being 2412 and operand b being 3231, in this case).
For example, the array result, on its rightmost position should be:
result[(digits_a+digits_b)-1] = partialResult[0][3];
next:
result[digits_a+digits_b]=(partialResult[0][2] + partialResult[1][3] + carry) %10;
newCarry = (partialResult[0][2] + partialResult[1][3] + carry) / 10;
Well, I'm stuck writing the double nested loop that's supposed to add these diagonals starting with the upper right one. Help. Please.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最终使用了这个(不要问为什么它将 BigInteger 转换为 ArrayList,反之亦然,这是一个奇怪的家庭作业要求)。
I ended up using this (don't ask why it converts a BigInteger to an ArrayList and viceversa, it's a bizarre homework requirement).
假设您的
partialResult
尺寸为width
和height
,您可以通过以下两个循环添加(请参阅此处 实际操作):注意:末尾进位可能不为空,这意味着结果中第一个数字之前还有一个数字。
Assume your
partialResult
dimensions arewidth
andheight
you can add by the following two loops (see it here in action):Note: Carry may be non-empty at the end meaning another digit before the first one in result.