單元測(cè)試 - 自動(dòng)生成數(shù)組或其它數(shù)據(jù)的java庫?
問題描述
比如說, 我希望驗(yàn)證一個(gè)排序算法是否正確. 我不想自己去寫測(cè)試數(shù)據(jù), 有沒有什么庫能夠自動(dòng)生成包含數(shù)據(jù)的數(shù)組或其它的容器類.
比如能夠自動(dòng)生成一個(gè)長(zhǎng)度為100的有序int數(shù)組等等.
問題解答
回答1:關(guān)鍵詞,shuffle
public static List<Integer> generateRandomArray(int len) {if(len <= 0){ throw new IllegalArgumentException(len + ' can not be negitive.');}List<Integer> arr = new ArrayList<>(len);for(int i = 0; i < len; i++){ arr.add(i);}Collections.shuffle(arr);return arr; }回答2:
這樣的庫,還真沒有聽說過 —— 但是這類簡(jiǎn)單的方法,我建議 “自己動(dòng)手,豐衣足食”。以你現(xiàn)在的基礎(chǔ)而言,你應(yīng)該多思考,多寫多練 —— 自己去實(shí)現(xiàn)這類方法,就是很好的打基礎(chǔ)的過程。
你現(xiàn)在需要的并不是一個(gè)生成有序數(shù)組的方法。你需要的是下面兩個(gè)方法:
生成一個(gè)長(zhǎng)度為 n 的無序整數(shù)數(shù)組,數(shù)組元素的范圍為 0 ~ bound:
public int[] randomArray(int n, int bound) { Random random = new Random(); int[] array = new int[n]; for (int i = 0; i < n; i++) {array[i] = random.nextInt(bound); } return array;}
判斷 array 是否是升序排序:
public boolean isAscending(int[] array) { for (int i = 1; i < array.length; i++) {if (array[i - 1] > array[i]) { // 判斷降序的話,將 > 改成 < return false;} } return true;}
有了這兩個(gè)方法,便可以生成用于排序的整數(shù)數(shù)組和對(duì)整數(shù)數(shù)組是否有序進(jìn)行判斷。
相關(guān)文章:
1. mysql - 一個(gè)表和多個(gè)表是多對(duì)多的關(guān)系,該怎么設(shè)計(jì)2. html5 - h5寫的app用的webview,用手機(jī)瀏覽器打開不顯示?3. javascript - webpack --hot 熱重載無效的問題4. php - 第三方支付平臺(tái)在很短時(shí)間內(nèi)多次異步通知,訂單多次確認(rèn)收款5. javascript - 百度echarts series數(shù)據(jù)更新問題6. css3 - css before 中文亂碼?7. mysql新建字段時(shí) timestamp NOT NULL DEFAULT ’0000-00-00 00:00:00’ 報(bào)錯(cuò)8. mysql scripts提示 /usr/bin/perl: bad interpreter9. javascript - node服務(wù)端渲染的困惑10. python - django 按日歸檔統(tǒng)計(jì)訂單求解
