【问题标题】:How to continue providing method on array until it's become equal to other array如何继续在数组上提供方法,直到它与其他数组相等
【发布时间】:2019-05-23 08:02:22
【问题描述】:

我有 int1[k] 数组,其值等于它的索引 {0,1,2,3...}

我还有一个方法 1,它接受该数组并返回另一个 int2[k],其中的值以这种方式洗牌:

初始牌组:0 1 2 3 4 5 6 7

洗牌:4 0 5 1 6 2 7 3

最后我有一个接受任何 int[k] 数组的方法 2,并计算方法 1 的洗牌次数以使其恢复到原始状态:

Shuffles    Deck Order  
    0       0, 1, 2, 3, 4, 5, 6, 7  
    1       4, 0, 5, 1, 6, 2, 7, 3  
    2       6, 4, 2, 0, 7, 5, 3, 1  
    3       7, 6, 5, 4, 3, 2, 1, 0  
    4       3, 7, 2, 6, 1, 5, 0, 4   
    5       1, 3, 5, 7, 0, 2, 4, 6  
    6       0, 1, 2, 3, 4, 5, 6, 7 

这里有 6 次。

在最后一种方法中,我想运行 do{}while() 循环,条件是“直到新数组不等于原始数组本身”,尽管 System.out.printing 显示数组在每次迭代中都在变化(并且变得等于原始状态) 条件上的平等永远不会成为真的。

public class PerfectShuffle {
private int[] deck;
public PerfectShuffle(int size) {
        this.deck = new int[size];
        for (int i = 0; i < size; i++) {
            this.deck[i] = i;
        }
    }

public int[] method1(int[] input) {
        int[] newDeck = new int[input.length];
        int[] input1 = new int[input.length/2];
        int[] input2 = new int[input.length/2];
        System.arraycopy(input, 0, input1, 0, input.length/2);
        System.arraycopy(input, input.length/2 - 1, input2, 0, input.length/2);
        for (int i = 0; i < input.length/2; i++){
            newDeck[i*2 + 1] = input1[i];
            newDeck[i*2] = input2[i];
        }
        return newDeck;
    }

 public int method2() {
        int[] tempDeck = this.deck;
        int count = 0;
        do {
            tempDeck = this.method1(tempDeck);
            count++;
            System.out.println(Arrays.toString(tempDeck));
        } while (!Arrays.equals(tempDeck, this.deck));
        return count;
    }
}
public class Main {

    public static void main(String[] args) {
        PerfectShuffle s = new PerfectShuffle(52);
        System.out.println( s.method2() );
    }
}

我期待一个数字,但它只是“思考”了很长时间。

【问题讨论】:

  • tempDeck = this.inShuffle(tempDeck);做什么?
  • 对不起。我可怜的原始程序版本。将在一分钟内编辑。
  • @FullStackly 您的程序是否正在向控制台打印任何内容?
  • 我打印了 tempDeck 和 deck。 -> [7, 15, 23, 31, 39, 47, 4, 12, 20, 28, 36, 44, 1, 9, 17, 25, 33, 41, 49, 6, 14, 22, 30, 38, 46, 3, 11, 19, 27, 35, 43, 0, 8, 16, 24, 32, 40, 48, 5, 13, 21, 29, 37, 45, 2, 10, 18, 26, 34, 42, 50, 7] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51] 你的洗牌后的牌组有两次零,最高可达 50,而原来的牌是 0 到 51

标签: java arrays int equals


【解决方案1】:

这一行是错误的:System.arraycopy(input, input.length/2 - 1, input2, 0, input.length/2);。它有一个错误。

源数组起始索引应该是input.length/2

【讨论】:

  • 我认为这是错误,因为牌组从 0 变为 51,而洗牌后的牌从 0 变为 50,而 int 为 0 两次
  • 哇。你的建议有助于得到答案。这是我的一个非常尴尬的错误。我是一个早起的学习者。非常感谢。
  • 我将 input.length/2 - 1 更改为 input.length/2 并得到正确答案 52。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
相关资源
最近更新 更多