第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

避免在java中以隨機(jī)排列重復(fù)數(shù)組

避免在java中以隨機(jī)排列重復(fù)數(shù)組

富國滬深 2022-01-06 17:00:03
我有以下代碼:public static void nextPermutationArray(int[] v) {    int x = 1;    int y;    Random r = new Random();    while (x < v.length) {        y = x + r.nextInt(v.length - x);        int temp = v[x];        v[x] = v[y];        v[y] = temp;        x++;    }}public static void main(String[] args) {    int[] a = new int[]{0, 1, 2, 3};    nextPermutationArray(a);    System.out.println(Arrays.toString(a));    nextPermutationArray(a);    System.out.println(Arrays.toString(a));    nextPermutationArray(a);    System.out.println(Arrays.toString(a));    nextPermutationArray(a);    System.out.println(Arrays.toString(a));}該程序返回給我:0321023102310132我的問題是:有什么方法可以編輯方法nextPermutationArray來避免像0231. 換句話說,該方法應(yīng)該返回 4 個不可重復(fù)的元素。
查看完整描述

2 回答

?
陪伴而非守候

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超8個贊

這應(yīng)該打印出所有排列而不將它們存儲在 HashMap 或列表中


public static boolean nextPermutationArray(int[] a) {

    int i = a.length - 2;

    while (i >= 0 && a[i] >= a[i + 1]) {

        i--;

    }

    if (i < 0) {

        return false;

    }

    int j = a.length - 1;

    while (a[i] >= a[j]) {

        j--;

    }

    int t = a[i];

    a[i] = a[j];

    a[j] = t;

    Collections.reverse(Arrays.asList(Arrays.copyOfRange(a, i + 1, a.length)));

    return true;

}

它將返回真,直到有一個使用它的前突變運(yùn)行此代碼


public static void main(String[] args) {

    int[] a = new int[]{0, 1, 2, 3};

    do {

        System.out.println(Arrays.toString(a));

    } while (nextPermutationArray(a));

}

輸出是


[0, 1, 2, 3]

[0, 1, 3, 2]

[0, 2, 3, 1]

[0, 3, 2, 1]

[1, 3, 2, 0]

[2, 3, 1, 0]

[3, 2, 1, 0]


查看完整回答
反對 回復(fù) 2022-01-06
?
犯罪嫌疑人X

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個贊

您可以將已返回的每個排列存儲在 int[][] 類型的靜態(tài)變量中。如果得到的結(jié)果已經(jīng)在數(shù)組中,則可以進(jìn)行另一個排列。重復(fù)直到你有一個新的排列。但是要小心,如果您想產(chǎn)生比可能更多的排列,這可能會造成無限循環(huán)!


查看完整回答
反對 回復(fù) 2022-01-06
  • 2 回答
  • 0 關(guān)注
  • 153 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號