Skip to main content
freelanceshack.com

Back to all posts

How to Fill 2D Array With Random Numbers In Kotlin?

Published on
5 min read
How to Fill 2D Array With Random Numbers In Kotlin? image

Best Kotlin Programming Books to Buy in October 2025

1 Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

BUY & SAVE
$29.95 $32.95
Save 9%
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)
2 Kotlin in Action, Second Edition

Kotlin in Action, Second Edition

BUY & SAVE
$45.98 $59.99
Save 23%
Kotlin in Action, Second Edition
3 Head First Kotlin: A Brain-Friendly Guide

Head First Kotlin: A Brain-Friendly Guide

BUY & SAVE
$50.36 $79.99
Save 37%
Head First Kotlin: A Brain-Friendly Guide
4 Kotlin: An Illustrated Guide

Kotlin: An Illustrated Guide

BUY & SAVE
$49.53
Kotlin: An Illustrated Guide
5 Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

BUY & SAVE
$48.00 $65.99
Save 27%
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines
6 Functional Programming in Kotlin

Functional Programming in Kotlin

BUY & SAVE
$46.16 $49.99
Save 8%
Functional Programming in Kotlin
7 Atomic Kotlin

Atomic Kotlin

BUY & SAVE
$44.91 $49.00
Save 8%
Atomic Kotlin
8 Kotlin Design Patterns and Best Practices: Elevate your Kotlin skills with classical and modern design patterns, coroutines, and microservices

Kotlin Design Patterns and Best Practices: Elevate your Kotlin skills with classical and modern design patterns, coroutines, and microservices

BUY & SAVE
$30.53 $44.99
Save 32%
Kotlin Design Patterns and Best Practices: Elevate your Kotlin skills with classical and modern design patterns, coroutines, and microservices
+
ONE MORE?

To fill a 2D array with random numbers in Kotlin, you can use nested loops to iterate over each row and column of the array. Within the loops, you can generate a random number using the Random class from the kotlin.random package. Then, you can assign this random number to the corresponding element in the 2D array. Here's an example code snippet:

import kotlin.random.Random

fun main() { val rows = 3 val cols = 3 val matrix = Array(rows) { IntArray(cols) }

val random = Random(System.currentTimeMillis())

for (i in 0 until rows) {
    for (j in 0 until cols) {
        matrix\[i\]\[j\] = random.nextInt(100) // Generate random number between 0 and 99
    }
}

for (row in matrix) {
    println(row.joinToString())
}

}

In this code snippet, we first define the number of rows and columns for the 2D array. We then create the 2D array using the Array constructor. We initialize a Random instance with the current system time to seed the random number generation.

Next, we iterate over each element in the 2D array using nested loops and generate a random number using random.nextInt(100), which generates a random number between 0 and 99. Finally, we print out the filled 2D array to the console.

How to fill a 2D array with a specific value in Kotlin?

You can fill a 2D array with a specific value in Kotlin by using nested loops. Here's an example code snippet that fills a 2D array with a specific value (let's say the value is 0):

fun main() { val numRows = 3 val numCols = 3 val specificValue = 0

val matrix = Array(numRows) { Array(numCols) { specificValue } }

// Print the filled 2D array
for (i in 0 until numRows) {
    for (j in 0 until numCols) {
        print("${matrix\[i\]\[j\]} ")
    }
    println()
}

}

In this code snippet, we first specify the number of rows and columns for the 2D array, as well as the specific value we want to fill it with. We then create a 2D array using the Array constructor with initial values set to the specific value. Finally, we loop through the 2D array and print out each element to confirm that it has been filled with the specific value.

What is the purpose of shuffling a list of random numbers?

The purpose of shuffling a list of random numbers is to randomize the order of the numbers in the list. This ensures that the numbers are not biased or predictable in any way, making them suitable for use in statistical analysis, gaming, cryptography, and other applications where randomness is important. Shuffling helps create a fair and impartial distribution of numbers, removing any patterns or sequences that may have been present in the original list.

What is the benefit of displaying the output for debugging purposes?

Displaying the output for debugging purposes allows developers to quickly identify and fix issues in their code. By seeing the output of their code at different stages of execution, developers can trace the flow of data and identify any errors or unexpected results. This can help them pinpoint the root cause of a problem and make the necessary corrections, leading to more efficient and effective debugging. Additionally, displaying output can also help developers gain a better understanding of how their code is functioning and ensure that it is producing the desired results.

What is the difference between a 1D and a 2D array in Kotlin?

In Kotlin, a 1D array is a collection of elements arranged in a single linear structure, while a 2D array is a collection of elements arranged in rows and columns, forming a grid-like structure.

A 1D array is accessed using a single index, while a 2D array is accessed using two indices to specify the row and column.

For example, a 1D array of integers could be defined as follows:

val numbers = intArrayOf(1, 2, 3, 4, 5)

And a 2D array of integers could be defined as follows:

val matrix = arrayOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9) )

Overall, the main difference between a 1D and a 2D array in Kotlin is the way the elements are organized and accessed.

How to export the filled 2D array with random numbers to a file in Kotlin?

To export a filled 2D array with random numbers to a file in Kotlin, you can use the following code:

import java.io.File

fun main() { val rows = 5 val cols = 5 val array = Array(rows) { Array(cols) { (0..100).random() } }

File("output.txt").printWriter().use { out ->
    for (i in 0 until rows) {
        for (j in 0 until cols) {
            out.print("${array\[i\]\[j\]} ")
        }
        out.println()
    }
}

println("Array has been exported to output.txt")

}

In this code snippet, we first create a 2D array array with random numbers. We then create a new File object with the file name output.txt and use a PrintWriter to write the array elements to the file. Finally, we print a message to the console indicating that the array has been exported successfully.

When you run this code, a file named output.txt will be created in the same directory as your Kotlin file, containing the filled 2D array with random numbers.