How can I create xy matrix (where x <= y) with random integers (from 0 to 9) which has at least x zeros and max (xy)/2 in java?
Size of matrix (x,y) is given. Also I would like to know how to use this matrix with same integers with same index in other class (for example 'public class Game{...}'). I'm a beginner so please make it easy for me :)
My code so far:
import java.util.Random;
public class Solution {
int a[][];
public void P(int x, int y){
Random r = new Random();
a = new int[x][y];
for (int i=0; i<x; i++){
for (int j=0; j<y; j++){
a[i][j] = r.nextInt(10);
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println();
int zeros = 0;
for (int i=0; i<x; i++){
for (int j=0; j<y; j++){
if(a[i][j]==0){
zeros ++;
}
}
}
System.out.println(zeros);
}
public int[][] getA() {
return a;
}
}
Random r = new Random();
a = new int[x][y];
int noZeros = r.nextInt((y*x)/2-x) + x;
boolean z[][] = new boolean[x][y];
for (int i = 0; i < noZeros; i++) {
z[r.nextInt(x)][r.nextInt(y)] = true;
}
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (!z[i][j]) {
a[i][j] = r.nextInt(9) + 1;
}
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println();
int zeros = 0;
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (a[i][j] == 0) {
zeros++;
}
}
}
System.out.println(zeros);
In my solution I create first boolean matrix, which represents zeros, then I chose random number, but from 1 to 9.
I would first determine how many 0s you will have in the matrix, getting a random int from within your min/max bound. Then I would calculate the other xy - numZeros random integers. Finally, for each cell in the matrix, I would pick a random element from a combined list (your 0s + other random integers, removing the element when it is picked).
Related
I want to traverse a 3*3 submatrix within a large 7*7 matrix starting position from (1,1) that is middle element (2nd row , 2nd column).
The corresponding submatrix of position (1,1) will be
[(0,1),(0,2),(0,3)]
[(1,1),(1,2),(1,3)]
[(2,1),(2,2),(2,3)]
Like this traversing will go on.. and next submatrix starting posiion will be (1,2)
[(0,2),(0,3),(0,4)]
[(1,2),(1,3),(1,4)]
[(2,2),(2,3),(2,4)]
My Code
static int i;
static int j;
static int g;
static int h;
static void submatrix(int p,int q,int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(p+","+q);
shiftmatrix(p,q,mat);
}
static void shiftmatrix(int p,int q,int[][] mat) {
int m,n;
int[][] d = new int[3][3];
for( m=0;m<3;m++) {
for( n=0;n<3;n++) {
p=m+(p-1);
q=n+q;
d[m][n]=mat[p][q];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for ( m = 0; m < 3; m++){
for ( n = 0; n < 3; n++){
System.out.print(d[m][n]+"\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = new int[7][7];
int[][] mat = new int[7][7];
for ( i = 0; i < 7; i++)
{
for ( j = 0; j < 7; j++){
Random rand = new Random();
a[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (i = 0; i < 7; i++){
for (j = 0; j < 7; j++){
mat[g][h]=a[i][j];
System.out.print(mat[g][h]+"\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (i=1;i<6;i++) {
for (j=1;j<5;j++) {
int p=i;
int q=j;
submatrix(p,q,mat);
}
}
}
}
while running this code getting error as
ArrayIndexOutOfBoundsException: -1
Please help
The IndexOutOfBoundsException in your code was from you calling p = m + (p - 1). You don't need to change the p and q variables within every iteration of the loop.
In addition, you had several unnecessary variables, and had some of them static, something you should avoid when you're only using them in a loop like this. After cleaning up the code's formatting and deleting all unnecessary variables I believe the code functions as you want it to.
The code ignores the first row and column of your random matrix. Is this desired behavior?
import java.util.Random;
public class MatrixTest {
public static void subMatrix(int startRow, int startCol, int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(startRow + ", " + startCol);
shiftMatrix(startRow, startCol, mat);
}
public static void shiftMatrix(int startRow, int startCol, int[][] mat) {
int[][] d = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//to properly move within the 3x3 you only need to add a
//constant buffer to the indices of mat[][]
d[i][j] = mat[i + startRow][j + startCol];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(d[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] mat = new int[7][7];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++){
Random rand = new Random();
mat[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (int i = 0; i < 7; i++){
for (int j = 0; j < 7; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (int i = 1; i < 5; i++) { //changed from i < 6 to i < 5 to stay inside 7x7
for (int j = 1; j < 5; j++) {
subMatrix(i, j, mat);
}
}
}
}
I am trying to make a method which creates a 2D symetrix matrix that is generated randomly and it is of n size. The random numbers also have to be between 0 and 100.
Heres what i got so far;
public static void randomArray(int n)
{
Random random = new Random();
double[][] array = new double[n][n];
for( int i = 0 ; i < array.length ; i++ ) {
for ( int j = 0 ; j < array[i].length ; j++ ) {
array[i][j] = random.nextInt(101);
}
}
for( double[] a : array ) {
System.out.println( Arrays.toString( a ));
}
}//end of randomArray
This successfully generates a 2D array with random numbers, but the matrix is not symetric and i am confused as to how to make it symetrix.
For the random value that you assigned to array[i][j], you also assign it to array[j][i], except for the matrix diagonal of course.
Also, you change your inner loop stopping condition to be j<=i, so you don't iterate over the other side of the matrix.
for (int i = 0; i < array.length; i++) {
for (int j = 0; j <= i; j++) {
int x = random.nextInt(101);
array[i][j] = x;
if (i != j) {
array[j][i] = x;
}
}
}
Here is a complete solution. I assume from your description that 2D matrix is to represent a graph.
public static double[][] RandomArray(int n){
double [][] array = new double[n][n];
Random rand = new Random();
for(int i=0; i<n; i++) {
for(int j=0; j<=i; j++) {
Integer r = Math.abs(rand.nextInt(101));
array[i][j] = r;
if (i != j) {
array[j][i] = r;
}
else {
array[i][j] = 0;
}
}
}
return array;
}
How do I make it so that when I output the grid when I run the code, no two numbers or letters will be the same? When I currently run this code I could get 3x "L" or 2x "6", how do I make it so that they only appear once?
package polycipher;
import java.util.ArrayList;
public class Matrix {
private char[][] matrix = new char[6][6];
private int[] usedNumbers = new int[50];
{for(int x = 0; x < usedNumbers.length; x++) usedNumbers[x] = -1;}
private final char[] CIPHER_KEY = {'A','D','F','G','V','X'};
private final String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public Matrix() {
int random;
for(int i = 0; i < CIPHER_KEY.length; i++) {
for(int j = 0; j < CIPHER_KEY.length; j++) {
validation: while(true) {
random = (int)(Math.random()*validChars.length()-1);
for(int k = 0; k < usedNumbers.length; k++) {
if(random == usedNumbers[k]) continue validation;
else if(usedNumbers[k]==-1) usedNumbers[k] = random;
}
break;
}
matrix[i][j] = validChars.split("")[random].charAt(0);
}
}
}
public String toString() {
String output = " A D F G V X\n";
for(int i = 0; i < CIPHER_KEY.length; i++) {
output += CIPHER_KEY[i] + " ";
for(int j = 0; j < CIPHER_KEY.length; j++) {
output += matrix[i][j] + " ";
}
output += "\n";
}
return output;
}
}
This should be much faster than validating each random choice:
Store your valid chars into an array;
char[] valid = validChars.toCharArray();
Shuffle the array;
shuffle(valid)
Go through the positions in the matrix, storing the elements in the same order they appear in the shuffled array.
assert (CIPHER_KEY.length * CIPHER_KEY.length) <= valid.length;
int k = 0;
for (int i = 0; i < CIPHER_KEY.length; i++) {
for (int j = 0; j < CIPHER_KEY.length; j++) {
matrix[i][j] = valid[k++];
}
}
Use a set and generate a new random if the old random number is in the map:
Pseudocode:
Set<Integer> set = new HashSet<Integer>();
for () {
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
while (!set.contains(random)){
int random = (int)(Math.random()*validChars.length()-1);
//Your code for validation here (move it to a function)
}
//If we exit this loop it means the set doesn't contain the number
set.add(random);
//Insert your code here
}
This was assignment 1.
Now I have to create the same thing but use a random array of 1-100 values and i have no clue how implement that into what i already have.
public class Test {
public static void main(String a[]) {
int i;
int[] array = {9,1,5,8,7,2,1,5,5,6,8,15,3,9,19,18,88,10,1,100,4,8};
System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for (i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
}
public static void bubble_srt(int a[], int n) {
int i, j, t = 0;
for (i = 0; i < n; i++) {
for (j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
}
You need to use a random generator to get the numbers.
For an array of size X it would be something like this:
int[] array = new int[X];
Random random = new Random();
for (int i = 0; i < X; i++)
array[i] = random.nextInt(100) + 1;
You should take a look at the documentation for Random.
I'll echo what Jim has said in the comments. Being resourceful is an important skill as a software developer. A Google search would have quickly turned up a helpful article like this one.
You need to use the Random class to accomplish this.
Random randomGenerator = new Random();
int array = new int[100];
for (int idx = 0; idx < 100; ++idx){
array[idx] = randomGenerator.nextInt(100) + 1;
}
Note on the usage of the nextInt(int n) method:
It produces a pseudo-random integer between 0 (inclusive) and the specified integer (exclusive). That is the reason for adding 1 to the output of nextInt(100) as it shifts your output range from 0-99 to 1-100 as desired.
public void generateRandom()
{
int[] x = new int[100]; // This initializes an array of length 100
Random rand = new Random();
for(int i = 0; i < 100; i++)
{
x[i] = rand.nextInt(100); // Use the random class to generate random integers (and give boundaries)
}
}
So I am creating a program that rolls z die x times with y sides, and I keep getting an out of bounds error at the first line in the first for loop. However I'm not sure why this is, the loop counts from 0 to (z-1). I'm basically in the home stretch of this program and I need the help of the stackoverflow community.
public class Ass11f {
public static void main(String[] args) {
EasyReader console = new EasyReader();
System.out.print("Enter how many times you want to roll the die: ");
int x = console.readInt();
System.out.print("Enter the amount of sides: ");
int y = console.readInt();
System.out.print("Enter the amount of die: ");
int z = console.readInt();
int[][] dice = new int[x][z];
int row = 0;
for (int i = 0; i<z; ++i){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x)) {
i = 0;
++row;
}
}
row = 0;
int[] sum = new int[x];
for (int j = 0; j<z; ++j){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x)) {
j = 0;
++row;
}
}
int[] counter = new int[2*y];
int k = 0;
while (k<sum.length){
for (int l = 0;l<((2*y)-1);++l){
if (sum[k]==l) ++counter[l];
if (l==((2*y)-1)) {
++k;
}
}
}
for (int m = 0;m<sum.length;++m) System.out.println(sum[m]+"'s: "+counter[m]+"times, "+((((double)counter[m])/x)*100)+"%");
}
}
first loop:
for (int i = 0; i<z; i++){
dice[row][i] += ((int)(Math.random()*y)+1);
if ((i == z-1)&&(row!=x-1)) {
i = -1;
++row;
}
}
second loop:
for (int j = 0; j<z; j++){
sum[row]+=dice[j][row];
if ((j == z-1)&&(row!=x-1)) {
j = -1;
++row;
}
}
Third loop: runs forever. I'm not sure what this is trying to achieve, so I can't fix it for you...
There are x rows but you are using z as the row loop
int[][] dice = new int[x][z]; <-- x is the row count
int row = 0;
for (int i = 0; i < z; ++i){ <--- The outer loop is iterating the rows (x),
Here's how to iterate through a 2D array
int[][] dice = new int[x][z];
for (int i = 0; i < x; i++){
for (int j = 0; j < z; j++){
// do something with dice[i][j]
}
}