how to assign random number with range to 2D array dimensions - java

In main, assign 2 random numbers (ints between 3 and 10) for the first dimension and the second dimension
I had this but the Math.random() method doesn;t work
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
double doubMatrix1[][] = (int) (Math.random()*(10-3+1)+3);
double doubMatrix2[][];
double doubMatrix3[][];
}
}

The problem in your code is that you are trying to initialize a matrix of double with an int
Types must be equals!
Here are your code fixed.
import java.lang.Math;
public class Homework2 {
public static void main(String[] args){
int d1 = (int) (Math.random()*(10-3+1)+3);
int d2 = (int) (Math.random()*(10-3+1)+3);
double doubMatrix1[][] = new double[d1][d2];
double doubMatrix2[][];
double doubMatrix3[][];
}
}
hope this help

To create a multidimensional array in Java, use new <type>[dim1][dim2], as in the following code:
Random rand = new Random();
int r1 = rand.nextInt(8) + 3;
int r2 = rand.nextInt(8) + 3;
double doubMatrix[][] = new double[r1][r2];

Math.random() returns fraction between 0.0 and 1.0. So with (int) (Math.random()*(10-3+1)+3) you are getting only one random number between 3 and 10 inclusive. But you are assigning it to double doubMatrix1[][]. So probably you are calling constructor in wrong way. You are supposed to generate two distinct random number r1, r2 according to the method taught by your teacher then call constructor like double doubMatrix1[][] = double[r1][r2]

check this out, this might be helpful:
// DMA of 2D array in C++
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int x = 3, y = 3;
int **ptr = new int *[x];
for(int i = 0; i<y; i++)
{
ptr[i] = new int[y];
}
srand(time(0));
for(int j = 0; j<x; j++)
{
for(int k = 0; k<y; k++)
{
int a = rand()%5;
ptr[j][k] = a;
cout<<ptr[j][k]<<" ";
}
cout<<endl;
}
}
we used a pointer and deal it just like 2D array here, use % for limit

Related

math.sqrt gives me incorrect result (double)

I am writing a program that prints 100 random coordinates within a circle. The circle has the radius 10 and its center is located at (0,0). However, some of the coordinates y:value is incorrectly calculated when I'm using: y = Math.sqrt(100 -x^2) The result is like off... Why is that ? (See picture) For positive y:values, they get too big sometimes and its because of the math.sqrt calculation with doubles.
package RKap14;
import ZindansMethods.ZindanRandom;
public class Dot {
public double x;
public double y;
public static void main(String[] arg)throws Exception {
//Create the array with null fields?
Coord[] c;
//Decide how many fields
c = new Coord[100];
//Create an object of class Coord in each slot of the array
for(int i = 0; i<c.length; i++) {
c[i] = new Coord();
}
//Assign random coordinates for each field x & y
for(int i = 0; i<c.length; i++) {
c[i].x = ZindanRandom.randomized(-10,10);
//Since sometimes Java calculates wrong and gives numbers above 10 and below -10...
while(c[i].x > 10 || c[i].x < -10)
c[i].x = ZindanRandom.randomized(-10,10);
c[i].y = ZindanRandom.randomized(-Math.sqrt(100-c[i].x*c[i].x), Math.sqrt(100-c[i].x*c[i].x));
}
//Print out the coordinates in form: (x,y),(x1,y1)...(x99,y99)
for (int i = 0; i<c.length; i++) {
System.out.print("(" + c[i].x + "," + c[i].y + ")" + ",");
}
}
}
class Coord {
double x;
double y;
}
The random method I am using:
//Gives random number a to b. For example -10 <= x <= 10
public static double randomized (double a, double b) {
return (a-1+Math.random()*Math.abs(b-a+1)+1);
}
I don't know what to try. I tried doing this program with a trigonometric approach but I'd rather understand why the calculator is doing its job wrongfully. Are there too many decimals? Can I do something about it ?
Circle test
your random function is generating numbers outside the given range
for example if you substitute the values into your equation and and use 1 as the value returned from Math.random() you will get 101.
Try the following random function instead:
public static double randomized(double min, double max)
return Math.random() * (max - min) + min;
}

How do I rerun a static integer array?

here's the array I want to rerun:
public static int[] rollDice(int dice[]) {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
If I want to reset this array and find new random numbers how would I do that? I tried rollDice() only to get an error.
There is no point in returning the array, since you already have a reference to the array when you call the method rollDice().
Arrays are sent by reference and not by value, which means you are not working with a copy like you do with ints, instead you are modifing the original array.
Change the return type to void and remove the return and your code should work as intended.
You can get every time a new dynamic length array with random numbers, and you can access by call rollDice(integer value).
public static int[] rollDice(int length) {
final int dice[] = new int [length];
// generate array with random values
for (int i = 0; i < length; i++) {
dice[i] = (int)(Math.random() * length + 1);
}
return dice;
}
You would have to have a class member like this:
public static final int[] dice = new int[5];
Then to roll/reroll the dice use your method, else just access dice.
public static void rollDice() {
// generate 5 random numbers / update dice array
for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
}
Interesting fact: Java has no static function variables as C and C++ does. In those languages it could look like this:
(I wrote it like a java Function for you Java guys)
public static int[5] rollDice(boolean reroll) {
static final int[] dice = new int[5];
if (reroll) for (int i = 0; i < dice.length; i++) {
dice[i] = (int)(Math.random() * 6 + 1);
}
return dice;
}
As you can see, static variables can be embedded into those functions. If you ask me, it's a huge minus, Java doesn't support this as I use it all the time to hide those from the class namespace.

Not getting right output for natural log formula

I'm trying to get my program to out the first 500 values for this formula: -12*ln(1-x) where x is the return of double next(). I don't know what I'm doing wrong because I can't get the right output. The random number uses this formula x(i+1) = (a * x(i) + c) mod k
public class myRnd {
// Linear values for x(i+1) = (a * x(i) + c) % k
final static int a = 7893;
final static int c = 3517;
final static int k = 8192;
// Current value for returning
int x;
int y;
int z;
public myRnd() {
// Constructor simply sets value to half of k
x = (125*k) /1024;
//y = (125*k) /1024;
}
double next() {
// Calculate next value in sequence
x = (a * x + c) % k;
// Return its 0 to 1 value
return (double)x / k;
}
public static void main(String[] args) {
int situation;
double sec_answer;
// Create a new myRnd instance
myRnd r = new myRnd();
// Output 53 random numbers from it
for (int i = 0; i < 53; i++) {
System.out.println (r.next());
}
System.out.println("random variable");
for(int b = 0; b < 500; b++){
sec_answer = (-12)*Math.log(1- r.next());
System.out.println(sec_answer);
}
}
}
I suppose these are the first 5 values you're expecting from your program in each loop!
0.9302978515625
0.270263671875
0.6204833984375
0.90478515625
0.8985595703125
random variable
31.962289651479345
3.78086405322487
11.626283246646423
28.21943313114782
27.45940262908609
In your main method you have only one instance of the class:
// Create a new myRnd instance
myRnd r = new myRnd();
This initialization is propagated to both for loops.
Simple Solution: Add another instance / initialization of myRnd for the second for loop, as an example you could reuse the same variable as r = new myRnd(); before the second loop.

Calling a method and returning to an array

I'm working on a program and it involves arrays. I'm new to this so I keep writing code and deleting it over and over.
I need to ask the user to input a number from 1 to 99.
Their input should allocate the size of a single dim array.
Then I have to send that array to a method that randomly chooses DOUBLES from 55 to 100 and place them into the array.
This is what I'm playing around with now. I'm starting to confuse myself!
public static void main(String[] args) {
int scores = 0;
int numberOfGrades;
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number of grades from 1 to 99: ");
numberOfGrades = input.nextInt();
int[] amountOfGrades = new int[numberOfGrades];
randomGrades(amountOfGrades);
System.out.print("The letter grades for each score are: ");
} //End Method
/**
*
* #param array
* #return
*/
public static int randomGrades(int[] array) {
for (int cntr = 55; cntr < 100; cntr++) {
int rndm = new Random().nextInt(array.length);
return array[rndm];
}//End Main Method
Try the following code:
package eu.webfarmr;
import java.util.Random;
public class DoubleArray {
public static void main(String[] args) {
int numberOfGrades = 10;
int[] grades = generateRandomGrades(numberOfGrades);
for (int grade : grades){
System.out.println(grade);
}
}
private static int[] generateRandomGrades(int numberOfGrades) {
int[] grades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++){
grades[i] = new Random().nextInt(45)+55;
}
return grades;
}
}
It generates an array of size 10 and stores a new random value between 55 inclusive and 100 exclusive inside each element of the array.
Solution:
public static double[] randomGrades(double[] array) {
Random rndm = new Random(); // creating Random outside of the for loop, not in each iteration in for-loop to save memory
for (int i = 0; i < array.length; i++) { // for each element of an array
array[i] = (double) (rndm.nextInt(45) + rndm.nextDouble() + 55);
}
return array; // return array of doubles
}
Also change the following line in the main() method, from:
int[] amountOfGrades = new int[numberOfGrades];
to:
double[] amountOfGrades = new double[numberOfGrades];
as you said in question that you want to store double valuees instead of ints.
Explanation of the for-loop:
array[i] = (double) (rndm.nextInt(45) + rndm.nextDouble() + 55);
rndm.nextInt(45) returns int from 0(inclusive) to 45(exclusive),
rndm.nextDouble() returns double from 0.0(inclusive) to 1.0(exclusive)
Min possible value: 0 + 0.0 + 55 = 55
Max possible value: 44 + 1.0 + 55 = 100 (note that random double is not exactly 1.0 as it's exclusive, but it's any other possible double value close to 1.0 due to huge double precision
Edit:
With line randomGrades(amountOfGrades);, you create random double values and store them in an array, but you neither print these values to the console nor assign these values to an array:
You might want to consider changing this line:
randomGrades(amountOfGrades);
to:
amountOfGrades = randomGrades(amountOfGrades); // that way you have access to result doubke values later
System.out.println(Arrays.toString(amountOfGrades));
Whole working program:
Ok, I include whole solution for your convenience, but try not to copy it blindly, try to understand what's happening here (if you need to pass int value to randomGrades() instead of double[] as argument, uncomment all comments that I included and delete parts that are not necessary):
import java.util.*;
public class Test {
public static void main(String[] args) {
int scores = 0;
int numberOfGrades;
Scanner input = new Scanner(System.in);
System.out.println("Enter amount:");
numberOfGrades = input.nextInt();
double[] amountOfGrades = new double[numberOfGrades];
amountOfGrades = randomGrades(amountOfGrades /* or: amountOfGrades.length */);
System.out.println(Arrays.toString(amountOfGrades));
System.out.println("Letter grades...");
}
public static double[] randomGrades(double[] array /* or: int amount */) {
Random rndm = new Random();
// add this line if you use int argument: double[] array = new double[amount];
for(int i = 0; i < array.length; i++) {
array[i] = (double)(rndm.nextInt(45) + rndm.nextDouble() + 55);
}
return array;
}
}

Java Loops and Random numbers

Hi I am having some problems with using random numbers inside of loops.
private void SetMines()
{
Random randRowGen = new Random();
Random randColGen = new Random();
int mineCount = 0;
int numMines = (ROWS * COLUMNS)* (int)0.156;
while(mineCount <= numMines)
{
int randRow = randRowGen.nextInt(ROWS)+1;
int randCol = randColGen.nextInt(COLUMNS)+1;
grid[randRow][randCol] = new Character('*');
mineCount++;
}
}
Here is my method it is going through an array size 25 * 25 and picking random spots and putting "mines" there. The only problem is it only selects one location to put a "mine" in and it needs to put 97 mines in random spots.
Any help will be appreciated thanks!!
Your numMines calculation will always return 0, because when you cast a double that is less than 1 to an int, it will be set to 0, which means that the statement in your while loop will only be run a single time, hence only a single mine being placed.
The problem isn't Random, it's int numMines = (ROWS * COLUMNS)* (int)0.156;. Have you checked what that value is? It's 0, because (int) 0.156 equals 0.
Perhaps you want int numMines = (int) ((double) 0.156 * ROWS * COLUMNS);. The problem with integer maths is that you can lose a LOT of precision.
Make your computer suffer and make it drop all those mines.
Remember. The definition of "computation" is "to force a machine do a boring job that nobody else would like to do" :-)
public static void main(String[] args) {
int rows = 25;
int cols = 25;
boolean[][] mines = new boolean[rows][cols];
while(mineCount(mines) < 97){
dropMine(mines);
}
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
System.out.print("[");
if (mines[i][j]){
System.out.print("*");
}else{
System.out.print(" ");
}
System.out.print("] ");
}
System.out.println();
}
}
private static void dropMine(boolean[][] mines) {
int x = (int)(Math.random()*25);
int y = (int)(Math.random()*25);
mines[x][y] = true;
}
private static int mineCount(boolean[][] mines) {
int count = 0;
for(int i=0;i<25;i++){
for(int j=0;j<25;j++){
if (mines[i][j]){
count++;
}
}
}
return count;
}

Categories

Resources