其他分享
首页 > 其他分享> > 数组实现双色球彩票

数组实现双色球彩票

作者:互联网

数组相关问题

1、如何把数组中的元素逆序?

/*
    思路:逆序就是把数组的元素前后倒置。
    我们可以把前后两个数 i 和 arr.length-1-i 位置上的数进⾏交换,
    但是⼀定注意交换次数是⻓度的⼀半。
*/

function reverseArray1(arr) {
    for (var i = 0; i < arr.length / 2; i++) {
        var temp = arr[i];
        arr[i] = arr[arr.length - 1 - i];
        arr[arr.length - 1 - i] = temp;
    }
}


function reverseArray2(arr) {
    for (var begin = 0, end = arr.length - 1; begin <= end; begin++, end--) {
        var temp = arr[begin];
        arr[begin] = arr[end];
        arr[end] = temp;
    }
}

2、用递归实现字符串的逆序?

package com.m.sort;


import java.util.Arrays;
import java.util.Random;
import java.util.Stack;

public class Test2 {
    public static void main(String[] args) {
        System.out.println(test2("hello"));
    }
	//0
    public static String test(String str) {
        if(str == null || str.length() == 1){
            return str;
        }
        return test(str.substring(1))+str.charAt(0);
    }
	//1
    public static String test1(String str) {
        Stack<String> stack = new Stack<>();
        StringBuilder stringBuilder = new StringBuilder();
        stack.push(str);
        while(!stack.isEmpty()){
            str = stack.pop();
            if(str == null || str.length() == 1){
               stringBuilder.append(str);
            }else{
                stringBuilder.append(str.charAt(str.length()-1));
                stack.push(str.substring(0,str.length()-1));
            }
        }
        return stringBuilder.toString();
    }
    //2
    public static String test2(String str){
        char[] chars = str.toCharArray();
        //"hello"
        for (int start = 0,end = str.length()-1; start <=end ; start++,end--) {
            char temp = chars[start];
            chars[start] = chars[end];
            chars[end] = temp;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            stringBuilder.append(chars[i]);
        }
        return stringBuilder.toString();
    }
}

3、实现双色球彩票随机出号,六个红球,⼀个篮球,并顺序输出

package com.m.sort;


import java.util.Arrays;
import java.util.Random;

public class Test2 {
    //双色球
    public static void main(String[] args) {
        test();
    }

    public static void test() {
        int [] arr = new int[6];
        Random random = new Random();
        boolean flag;
        int n;
        for (int i = 0; i < arr.length;) {
            n = random.nextInt(33);
            flag = false;
            //顺序查找
            for (int j = 0; j <= i; j++) {
                if(n == arr[j]){
                    flag = true;
                    break;
                }
            }
            if(flag == false){
                arr[i] = n;
                i++;
            }
        }
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

标签:双色球,数组,arr,彩票,length,static,str,public,String
来源: https://www.cnblogs.com/k-class/p/14193243.html