I have little problem , im starting learn java .
I need to create 2dimensional array , and i need fill this array in 10% only int 1 of course my code need fill this array randomly .
Need some hints how to fill in 10% .
public static void main(String[] args) {
int maxX = 10;
int maxY = 10;
int[][] Arr = new int[maxX][maxY];
Random r = new Random();
// random ints
for (int x = 0; x < maxX; x++) {
for (int y = 0; y < maxY; y++) {
Arr[x][y] = r.nextInt(2);
}
}
// printing Arr
for (int i = 0; i < Arr.length; i++) {
for (int j = 0; j < Arr[i].length; j++) {
System.out.print(Arr[i][j] + " ");
}
System.out.println();
}
}
Make the array, take a random row and column, while the percentage is not exceeded, check if the position has 0, if yes fill it with 1.
int[][] array = new int[N][N];
int percentage = N*N/10;
int filled = 0;
while(filled <= percentage)
{
Random rand = new Random();
int i = rand.nextInt(N+1);
int j = rand.nextInt(N+1);
if(array[i][j] == 0)
{
filled++;
array[i][j] = 1;
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println();
}
You can take the following steps:
Suppose you need to fill an N * N array.
Create a List and add to it (N * N) / 10 1s and (N * N * 9) / 10 0s. list.addAll(Collections.nCopies(count,1 or 0)) can help you here.
Run Collections.shuffle on that List to obtain random order.
Iterate over the elements of the List. The first N elements will become the first row the the 2D array, the next N elements will become the second row of the array, and so on...
An alternative to shuffling is to pick 10% x N random positions and put a 1 (if a 0 was in the position, otherwise pick another position). In pseudo code:
int[][] array = new int[N][N]
apply N * N / 10 times {
index = random(0 .. N * N)
if array(index) = 0 then array(index) = 1
else retry with another index
}
You will need to convert the index from 0 to N*N into a pair of i,j in the 2D array.
I would use "double random = Math.random();"
And then an if to check if the variable random is less or equal to 0.1
Related
A brief explanation: With the code below it will make a randomly generated Square and some code below would make sure that it was a Magic Square, in which the sum of the elements in each row, column, and the two diagonals are the same value.
My teacher said at maximum it should take three minutes to generate a magic square. So all I ask is there anything that can be done to improve or fix this code, please?
import java.util.ArrayList;
import java.util.Random;
class Main {
public static void main(String[] args) {
int size = 9;
int N = 3;
boolean result = true;
ArrayList<Integer> list = new ArrayList<Integer>(size);
int[][] mat = new int[N][N];
while (result) {
for (int i = 1; i <= size; i++) {
list.add(i);
}
Random rand = new Random();
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
int index = rand.nextInt(list.size());
System.out.print(list.remove(index)+" ");
}
System.out.println();
}
System.out.println();
// Checking process
// sumd1 and sumd2 are the sum of the two diagonals
int sumd1 = 0, sumd2 = 0;
for (int i = 0; i < N; i++) {
// (i, i) is the diagonal from top-left -> bottom-right
// (i, N - i - 1) is the diagonal from top-right -> bottom-left
sumd1 += mat[i][i];
sumd2 += mat[i][N - 1 - i];
}
// if the two diagonal sums are unequal then it is not a magic square
if (sumd1 != sumd2)
result = false;
// calculating sums of Rows and columns and checking if they are equal to each other,as well as equal to diagonal sum or not
for (int i = 0; i < N; i++) {
int rowSum = 0, colSum = 0;
for (int j = 0; j < N; j++) {
rowSum += mat[i][j];
colSum += mat[j][i];
}
if (rowSum != colSum || colSum != sumd1)
result=false;
}
result = true;
}
}
}
Trying with random numbers to coincidentally find a solution is deadly slow.
If you have the numbers 1 to 9, its entire sum 1+2+3+...+8+9 is 9*(1+9)/2 = 45.
As you have 3 rows and 3 colums, a row and column must sum upto 45/3 = 15.
Now that should restrict the number of possibilities.
So you must build in some intelligence in the code. Avoid random numbers as they do not even guarantee you'll find a solution in hundred years.
If you already treated recursion, that would be the easiest way to try all possibly valid combinations.
If you already treated Set, a BitSet maybe might be useful for a row, column or diagonal.
If you find it hard to code walking through all possibilities, you might hold the 2 dimensional matrix in a 1 dimensional array int[N*N], and have N (rows) + N (columns) + 2 (diagonals) arrays of N indices.
And of course I will not spoil your fun and satisfaction finding a smart solution.
Work it out on paper first.
//so basically for all that is below, I'm trying to sort the random numbers that have been generated, and then 'sort' then into bins, and then for how many numbers there are in the bin, a star * will print out for every number. it will look like a histogram at the end. like this:
12 random integers in [0, 10) sorted into 2 bins:
******* 7 0.5833333 [5.0, 10.0)
***** 5 0.41666666 [0.0, 5.0)
but its like its skips that last two methods - generateBins, and printBins. how would i sort the random numbers into bins depending on the number (like above) and print a * for every number in that array bin?
public class BinSort {
final int totalBins;
final int totalRandom;
final float widthBin;
int [] storeNumbers;
int [] binCount;
public BinSort (int nBins, int nSamples, int max) {
totalBins = nBins; //total # of bins, ie 2
totalRandom = nSamples; //total random number generated, ie 12
widthBin = (float) (max/totalBins); ie 2
int [] storeNumbers = new int [max];
for (int i = 0; i < totalRandom-1; i++) {
storeNumbers[i] = Random.rand(i, max);
System.out.println(storeNumbers[i]);
}
}
void generateBins () {
int [] binCount = new int [totalBins];
for (int i=0; i < totalRandom-1; i++) {
int bin = (int)(storeNumbers[i]/ totalBins);
Math.floor(bin);
bin = binCount [i];
}
}
void printBins () {
for (int i = 0; i < binCount.length - 1; i++) {
for (int j=0; j < binCount[j]; j ++) {
System.out.print("*");
System.out.println(); }
float freq = (binCount[i]/totalRandom);
float binMin = (i * widthBin);
float binMax = (binMin * widthBin);
System.out.print(binCount[i] + freq + binMin + binMax);
System.out.println();
}
}
}
In your constructor you have
int [] storeNumbers = new int [max];
The problem here is that this will create a new local variable with the same name as your instance variable, storeNumbers. Also, the size should be totalRandom, not max. You need to create a Random object that you'll use to generate random numbers. Putting this together we get:
public BinSort (int nBins, int nSamples, int max) {
totalBins = nBins; //total # of bins, ie 2
totalRandom = nSamples; //total random number generated, ie 12
widthBin = (float) (max/totalBins); //ie 2
storeNumbers = new int [totalRandom];
Random rand = new Random();
for (int i = 0; i < totalRandom; i++) {
storeNumbers[i] = rand.nextInt(max);
}
}
This will generate totalRandom random numbers between 0 and max(exclusive) and store them the instance variable storeNumbers.
Next, in generateBins you have the same issue with
int [] binCount = new int [totalBins];
Which again will hide your instance variable binCount. The bin that a storeNumber falls into will be given by (int)(storeNumbers[i] / widthBin), and you need to increment the resulting bin by 1.
void generateBins()
{
binCount = new int[totalBins];
for (int i = 0; i < totalRandom; i++)
{
int bin = (int)(storeNumbers[i] / widthBin);
binCount[bin] += 1;
}
}
Finally, to the printing of the bins. This line
for (int j=0; j < binCount[j]; j ++)
should be
for (int j=0; j < binCount[i]; j ++)
Also, you should use printf to format the numbers you want to print.
void printBins()
{
for (int i = 0; i < binCount.length; i++)
{
for (int j = 0; j < binCount[i]; j++)
{
System.out.print("*");
}
float freq = (float)binCount[i] / totalRandom;
float binMin = i * widthBin;
float binMax = (i+1) * widthBin;
System.out.printf(" %d %.3f %.3f %.3f\n", binCount[i], freq, binMin, binMax);
}
}
Test:
public static void main(String[] args)
{
BinSort bs = new BinSort(2, 12, 10);
bs.generateBins();
bs.printBins();
}
Output:
***** 5 0.417 0.000 5.000
******* 7 0.583 5.000 10.000
Which I think is what you were looking for.
Be sure to compare your original code with the changes above and make sure you understand what the issues were and why the changes work.
I was trying to do a 2D array program to demonstrate a TRANSPOSE but I am getting error .. here is my code.
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
EDIT: My error during runtime (Solved)
EDIT 2: Solved
EDIT 3: The loop is in infinity ..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity..
There are several errors in your code, also it is recommend that the dimensions of the array is to be declared as a final int, so your code works for all matrix sizes and that debugging is easier. In your original code, the errors are:
At the input step, you are printing one element of myArray[2] before you perform the transpose. That means, you are getting your array is0.
In the section commented "After transposing", you are outputting your array wrong. Namely, for each entry, you call System.out.print("Your array is as follow" + myArray2[i][j]);, and that you forgot to add a new line after each row (when inner loop is finished).
"..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity.." There are 81 entries for the 9-by-9 case and you did not output which i,j index to be applied. You probably mistaken an infinite loop with a long but terminating loop.
Your transpose step is good.
Here is a refined version of your code which allows you to input array (in reading order, or more technically, row-major order), create a transposed array. You can copy and compare your current code with this code directly to test it.
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
For an array with three rows (m = 3) and four columns (n = 4), I inputted the numbers from 0 to 9, and then 0, 1, 2. As expected, the output should be:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1
You define your matrix as 9x9
int myArray1[][] = new int[9][9];
But actually you want to insert 10x10 items:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
So either:
Redefine your arrays to store 10x10 items
int myArray1[][] = new int[10][10];
Only read and store 9x9 items in your defined array
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
You haven't close your first outer for loop i.e in line 17 and change your array size to 10,as you wanted take 10 input (for 0 to 9 = 10 values).
Please dont let the length of this post scare you! Okay so here is the prompt I am currently working on:
"Write a class named BucketSort containing a method called sort that:
a) Place each value of the one-dimensional array into a row of the bucket array, based on the value’s “ones” (rightmost) digit. For example, 97 is placed in row 7, 3 is placed in row 3 an 100 is placed in row 0. This procedure is called a distribution pass.
b) Loop through the bucket array row by row, and copy the values back to the original array. This procedure is called a gathering pass. The new order of the preceding values in the one-dimensional array is 100, 3 and 97.
c) Repeat this process for each subsequent digit position (tens, hundreds, thousands, etc.) On the second (tens digit) pass, 100 is placed in row 0, 3 is placed in row 0 (because 3 has no tens digit) and 97 is placed in row 9. After the gathering pass, the order of the values in the one-dimensional array is 100, 3 and 97. On the third (hundreds digit) pass, 100 is placed in row 1, 3 is placed in row 0 and 97 is placed in row 0 (after the 3) After this last gathering pass, the original array is in sorted order. being sorted.
This sorting technique provides better performance than a bubble sort,but requires much more memory—the bubble sort requires space for only one additional element of data. This comparison is an example of the space/time trade-off: The bucket sort uses more memory than the bubble sort, but performs better. This version of the bucket sort requires copying all the data back to the original array on each pass. Another possibility is to create a second two-dimensional bucket array and repeatedly swap the data between the two bucket arrays. The two-dimensional array of buckets is 10 times the length of the integer array"
A bit of a mouth full I know. Below is my code thus far, but I can't figure out why it will not print in the correct order and I think it is time for fresh eyes. Any ideas are appreciated, thanks!
import java.util.Arrays;
public class BucketSort_main {
public static void main(String[] args)
{
int[] numbers = new int [5];
int[] tnumbers = new int [500];
int [][] bucket = new int [10][numbers.length];
int [] a = new int [10];
int count = 0;
int divisor = 1;
int cnt = 1;
boolean moreDigits = true;
for (int s = 0; s < 10; s++)
{
a[s] = 0;
}
for (int b = 0; b < numbers.length; b++)
{
numbers [b] = (int)(Math.random()*2000);
tnumbers [b] = numbers [b];
}
int[] tmpSort = new int[10];
while (moreDigits)
{
moreDigits = false;
for (int i = 0; i < tmpSort.length; i++)
{
tmpSort[i]= -1; // hint hint
}
for (int i = 0; i < numbers.length; i++)
{
int tmp = tnumbers[i] / divisor;
if (tmp/10 != 0)
{
moreDigits = true;
}
int digit = tmp % 10;
tmpSort[digit] = tnumbers[i]; // hint hint
System.out.println("Number["+i+"], Digit "+cnt+" is "+digit + ". Full number = " + tnumbers[i]);
bucket [digit][a[digit]] = tnumbers[i];
System.out.println ("Digit " + digit + " going to slot " + a[digit] + ". " + bucket[digit][a[digit]]);
System.out.println (" ");
a[digit]++;
}
cnt++;
divisor *= 10;
for (int x = 0; x < 10; x++)
{
a [x] = 0;
for (int y = 0; y < numbers.length; y++)
{
if (bucket[x][y] != 0)
{
tnumbers [y] = 0;
tnumbers [y] = bucket[x][y];
bucket[x][y] = 0;
}
}
}
}
for (int o = 0; o < numbers.length; o++)
{
System.out.println (tnumbers[o]);
}
}
}
The Problem is here:
for (int x = 0; x < 10; x++)
{
a [x] = 0;
for (int y = 0; y < numbers.length; y++)
{
if (bucket[x][y] != 0)
{
tnumbers [y] = 0;
tnumbers [y] = bucket[x][y];
bucket[x][y] = 0;
}
}
}
You are using the same y to get values from the bucket and assign values to tnumbers. So, when you loop through y the second time you are starting over again at tnumbers[0], tnumbers[1], etc...
Fix this issue and your code works fine.
So, I generate a 100 numbers between the range of 0 and 9. I store these 100 numbers in an array called 'array'. Then I have the array called 'count'. It has 10 elements, and I wanted to check the following: for each element in 'array' if it equals to 0-9 then count[0-9] increments by 1, count[0] = how many times number 0 appears and so on count[1] = 1, count[2] = 2... . I just keep getting the output of around 20k numbers and i suppose? the sum of each element?, no idea why. I was wondering if there is something major wrong with my for loop?
import java.util.*;
class RandomInt {
public static void main(String[] args) {
int size = 100;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]);
for (int x = 0; x < size; x++) {// loop through 10 elements in count
for(int j = 0; j < 10; j++){ //loop through 100 elements in array
if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
System.out.print(count[j]);
}
}
}
}
System.out.println("0 appears " + count[0] + " times.");
}
}
Your Login is Perfect only mistake which i found u made is with the brackets........!
Generate the numbers using first loop and then count the number of occurrence using different for loop.
Here is your code's modified version which generates 10 numbers and counts the individual number occurrence count.....
public class RandomInt {
public static void main(String[] args) {
int size = 10;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++)
{
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]+" ");
}
for (int x = 0; x < size; x++)
{// loop through 10 elements in count
for(int j = 0; j < 10; j++)
{ //loop through 100 elements in array
if (array[x] == j)
{// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
//System.out.print(count[j]);
}
}
}
System.out.println("3 appears " + count[3] + " times.");
}
}
There's a simpler way to do this without nested loops, so forgive me for suggesting this as a fix rather than finding the issue in the loop.
for(int i=0; i<size; i++){
int num = generator.nextInt(max);
array[i] = num;
count[num]++;
}
One loop, incrementing the count for each number as it appears. You may need to ensure all the entries in count start at 0, but even then an additional loop through 10 entries is MUCH faster.
To increment your counter, you don't need to have two nested for loops. Instead, you can use the value of array[x] as your counter.
for (int i = 0; i < size; i++) {
count[array[i]]++
}
You've nested your counting loop inside of your random number generating loop. Move the counting part outside.
Edit: The reason you're getting like 20k or whatever instances of zero is because when you set array[0] with a random value, you also check how many instances of 0 are in array[1] to array[99].
You probably shouldn't do your count until you have finished assigning your numbers, but here is how you could. Note that you want the value at array[i] to be your index to count.
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates random numbers
count[array[i]]++;
}
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(count));