【二维数组】声明一个二维数组,为该数组随机赋值,并输出该数组

package com.qianfeng.demo2;

import java.util.Random;

public class Test3 {
    
    public static void main(String[] args) {
        int[][] array2 =get2Array(10,10);
        printArray(array2);
    }

    
    //为一个二维数组随机赋值    
    
    public static int[][] get2Array(int num, int max){
    int[][] array = new int[num][num];
    
    Random random = new Random();     //使用Random随机生成一个数s
    
    for(int i = 0; i < array.length; i++){
        for(int j = 0; j < array[i].length; j++){
            array[i][j] = random.nextInt(max);     //返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括)和指定值(不包括)之间均匀分布的 int 值。
        }
    }
    return array;
}

    
    //循环输出一个二维数组
    public static void printArray(int[][] array){
        for(int i = 0; i < array.length; i++){
            for(int j = 0; j < array[i].length; j++){
                
                System.out.print(array[i][j] + " ");
                //System.out.print ("长度=="+array[i].length);
                //System.out.print("--------");
            }
            System.out.println();
        }
    }
        
    }
    
    
    
    

### 如何使用 Python 对二维数组进行随机赋值 对于给定的任务,可以利用 `numpy` 库来创建操作二维数组。下面展示了一种方法,通过该方法可以在指定范围内为二维数组中的每一个元素赋予随机整数值。 ```python import numpy as np # 定义一个两行三列的二维数组初始化为全零矩阵 array_shape = (2, 3) min_value = 0 # 随机数最小值(含) max_value = 10 # 随机数最大值(不含) # 使用np.random.randint函数生成满足条件的随机整数填充到二维数组中 random_array = np.random.randint(min_value, max_value, size=array_shape) print("Randomly assigned array:") print(random_array) ``` 如果目标是在特定位置设置固定数量的非零值而其余部分保持为零,则可以根据需求调整上述逻辑: - 创建一个全部为零的初始数组。 - 确定要放置非零值的位置索引列表。 - 将这些选定位置上的值设为所需的非零值[^1]。 例如,在已有的代码片段基础上修改得到如下实现方式,这里假设只希望前两个不等于零的位置被保留下来且重新分配至其他地方: ```python import numpy as np import matplotlib.pyplot as plt a = np.array([[6, 0, 2], [3, 4, 0], [0, 0, 5]]) idx, idy = np.where(a != 0) state = np.random.get_state() np.random.shuffle(idx) np.random.set_state(state) np.random.shuffle(idy) b = np.zeros_like(a) non_zero_count = min(len(idx), 2) # 只取前两个非零项 if non_zero_count > 0: b[idx[:non_zero_count], idy[:non_zero_count]] = a[idx[:non_zero_count], idy[:non_zero_count]] print('Original array:\n', a) print('Modified array with random placement of up to two non-zero elements:\n', b) plt.subplot(1, 2, 1) plt.title("Original Array") plt.imshow(a, cmap='jet') plt.colorbar() plt.subplot(1, 2, 2) plt.title("Modified Array") plt.imshow(b, cmap='jet') plt.colorbar() plt.tight_layout() plt.show() ``` 此段代码不仅实现了对原始数组中最多两个非零元素的新定位,还展示了如何借助 Matplotlib 来可视化对比原图与处理后的图像效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值