To fill an array with random numbers, you can use the random
module in Python. Here is an example of how to do this:
import random # Set the size of the arrayarray_size = 10 # Create an empty arrayarray = [] # Fill the array with random numbers for i in range(array_size): array.append(random.randint(0, 100)) print(array)
This code will create an array of size 10 and fill it with random integers between 0 and 100 (inclusive).
You can also use the random.sample
function to fill an array with a specified number of unique random numbers:
import random # Set the size of the array and the range of numbers to choose fromarray_size = 10num_range = 100 # Fill the array with random numbersarray = random.sample(range(num_range), array_size) print(array)
This code will create an array of size 10 and fill it with 10 unique random integers between 0 and 99 (inclusive).
You can also use the numpy
module to fill an array with random numbers. For example:
eimport numpy as np # Set the size of the arrayarray_size = 10 # Fill the array with random numbersarray = np.random.randint(0, 100, size=array_size) print(array)
This code will create an array of size 10 and fill it with random integers between 0 and 100 (inclusive).
I hope these examples are helpful! Let me know if you have any questions.
How to fill an array with random numbers in java?
To fill an array with random numbers in Java, you can use the java.util.Random
class. Here is an example of how to do this:
import java.util.Random; public class Main { public static void main(String[] args) { // Set the size of the array int arraySize = 10; // Create an empty array int[] array = new int[arraySize]; // Create a Random object Random random = new Random(); // Fill the array with random numbers for (int i = 0; i < arraySize; i++) { array[i] = random.nextInt(100); } // Print the array for (int i = 0; i < arraySize; i++) { System.out.println(array[i]); } } }
This code will create an array of size 10 and fill it with random integers between 0 and 99 (inclusive).
You can also use the java.util.Random.ints
method to fill an array with a specified number of random integers:
import java.util.Random; public class Main { public static void main(String[] args) { // Set the size of the array and the range of numbers to choose from int arraySize = 10; int numRange = 100; // Create an array of random numbers int[] array = new Random().ints(arraySize, 0, numRange).toArray(); // Print the array for (int i = 0; i < arraySize; i++) { System.out.println(array[i]); } } }
This code will create an array of size 10 and fill it with 10 random integers between 0 and 99 (inclusive).
I hope these examples are helpful! Let me know if you have any questions.