增加像数字一样的数组元素 [英] Increasing the Elements of an Array Like a Number
问题描述
我正在尝试制作数独求解程序.为了达到难题的解决方案,程序将0解释为空槽,然后制作一个长度等于整个难题中零个数的数组.从那里开始,它将数组中的所有值都设置为1(Sudoku拼图中任何插槽可以具有的最小值).我想做的是从具有最大索引的元素开始,在数组中模拟数字的增量模式.
I'm attempting to make a Sudoku solving program. To reach the puzzle's solution, the program interprets 0's as empty slots, and then makes an array that has a length equivalent to the number of zeros in the entire puzzle. From there, it sets all of the values in the array to 1 (the minimum value any slot can have in a Sudoku puzzle). What I'm trying to do is simulate a number's incremental pattern in the array starting from the element with the greatest index.
例如,一个带有三个空位的拼图将导致由3个元素组成的数组.然后,阵列将根据上面提到的模式增加:
For example, a puzzle with three empty slots would result in an array of 3 elements. The array would then increase based on the pattern mention above:
0 0 0(启动)
1 1 1(设置为可能的值)
1 1 2
1 1 3
1 1 4
1 1 5
1 1 6
1 1 7
1 1 8
1 1 9
1 2 1(跳过1 2 0,因为它会包含0)
1 2 2
等
0 0 0 (Initiation)
1 1 1 (Set to possible values)
1 1 2
1 1 3
1 1 4
1 1 5
1 1 6
1 1 7
1 1 8
1 1 9
1 2 1 (Skips 1 2 0 since it would include a 0)
1 2 2
etc.
这是基数为10的增量的修改形式.而不是0-9,它使用1-9.我该如何构建将以这种方式增加数组的方法?
This is a modified form of a base 10 number increment. Instead of 0-9, it uses 1-9. How may I build a method that will increment the array in this manner?
推荐答案
此处的基本算法是递增最右边的数字,如果溢出,则递增左边的第二位,依此类推.递归是解决此问题的一种巧妙方法.我将用伪代码来完成它,然后让您转换为Java
The basic algorithm here is to increment the right most digit then, if it overflows, increment the next to the left and so on. Recursion is a neat way of solving this. I'll do it in pseudocode and leave you to convert to Java
function increment(array, digit)
if (array[digit] < 9)
array[digit] += 1
else if (digit > 0)
array[digit] == 1;
increment(array, digit - 1)
else
you are finished
然后每次您使用以下命令调用它:increment(array, array.length - 1)
Then each time you call this with: increment(array, array.length - 1)
这篇关于增加像数字一样的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!