adding an array table (bidimensional) to a List (Java) - arrays

I am doing a Bingo program and now, the section of the bingoCard, to do this I am using an a bidimensional array but I need to shuffle the numbers of each row. For the shuffle part I saw that the setList is much better, but I don't know how to relate the List with the array here is a part of the code:
public static Integer[][] bingoCard(){
Integer [][] bingoCard= new Integer[3][9];
for(int x =0; x<bingoCard.length; x++){
for(int y =0; y<bingoCard[x].length; y++){
if(y <5){
int random = (int)(Math.random()*90+1);
System.out.print((bingoCard[0][y] = random) + " ");
}
if(y >4 && y <9){
System.out.print((bingoCard[0][y] = 0) + " ");
}
}
System.out.println();
}
List<Integer[]> list =Arrays.asList(bingoCard);
Collections.shuffle(list);
list.toArray(bingoCard);
return bingoCard;
}
Any question please ask me!!
Thanks.

In your code, when you do List<Integer[]> list = Arrays.asList(bingoCard), you are converting the outer array into a List and then shuffling its contents. The effect of this will be that the order of the 3 rows are shuffled rather than the contents of the 3 rows which is what you want. You could achieve this by shuffling the contents of each row within your for-loop. Or, after constructing the 2D array, you can loop over each row again and shuffle them.
Also, you have another small bug. When you assign the value, you are doing bingoCard[0][y] = ... but it should be bingoCard[x][y]. Otherwise, you are only assigning the first row new values on each iteration.
I would recommend not converting the array to a List just to shuffle it and then converting it back. Instead, you can use Random.nextInt to pick indexes of the array to assign. That would look something like this:
public static Integer[][] bingoCard(){
int numRows = 3;
int numCols = 9;
int randomNumbersPerRow = 5;
int randomNumberBound = 90;
Random random = new Random();
Integer[][] bingoCard = new Integer[numRows][numCols];
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
// Initialize all spots to 0
bingoCard[row][col] = 0;
}
for (int i = 0; i < randomNumbersPerRow; i++) {
// Choose a spot to assign a random number
int indexToAssign = random.nextInt(numCols);
// Make sure we haven't already chosen it
while (bingoCard[row][indexToAssign] != 0) {
indexToAssign = random.nextInt(numCols);
}
int numToAssign = random.nextInt(randomNumberBound) + 1;
bingoCard[row][indexToAssign] = numToAssign;
}
}
// Print the bingo card
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
System.out.printf("%2d ", bingoCard[row][col]);
}
System.out.println();
}
return bingoCard;
}

Related

how to append an element in the smallest available index in a 2D array in c?

I am trying to append value to the end of the 2D array say, ABC in a pointer A to the index with the smallest row index, and then the smallest col index e.g. if both indices [3][15] and [5][1] are empty, we append the value to [3][15], since it has the smaller row index.
imgr_result_t imgr_append(imgr_t* im, int expand_row, int val)
{
for(int i = 0; i < im->rows; i++)
{
for(int j = 0; j < im->cols; j++)
{
if(im->pixels[i][j] == 0)
{
im->pixels[i][j] = val;
}
}
}
}
I have written this snippet so far but I am unsure about what I am doing:/

How to store multiple 2D array locations in C?

I'm trying to make a simple program, that generates random numbers into a 15x15 2D array and then works with the array later on.
This function finds the largest value in the array and then prints out the value and its location.
void maxValue(int array[ROWS][COLUMNS]){
int maxNum = array[0][0];
int rowMaxLocation;
int columnMaxLocation;
for(int c = 0; c < ROWS; c++) {
for(int d = 0; d < COLUMNS; d++) {
if(maxNum < array[c][d]) {
maxNum = array[c][d];
rowMaxLocation = c;
columnMaxLocation = d;
}
}
}
printf("Largest value in the array is %d, located in [%d][%d]", maxNum, rowMaxLocation, columnMaxLocation);
return;
What I can't figure out is how to store multiple locations of the same maximal value, e.g. "Largest value in the array is 99, located in [1][3] and [5][12]".
Thanks in advance.
you can follow a two pass approach:
First pass: Find maximum element in array
Second pass: Find all indices where array value is equal to maximum element
In order to store multiple locations you can have arrays of rowMaxLocations[] or columnMaxLocations[] and store values in them accordingly as you scan the array during second pass. If you don't need these values, you can simply skip storing them in some array and just do printing in second pass as well.
I would recommend having a Location struct for storing location values like this:
typedef struct Location {
int row;
int column;
} Location;
Here is how this two pass approach would look like:
void maxValue(int array[ROWS][COLUMNS]){
int maxNum = array[0][0];
// Array of locations to store max locations
Location maxLocations[ROWS * COLUMNS];
// Index of max locations array
int maxLocationIndex = 0;
// First pass; Get Max value
for(int c = 0; c < ROWS; c++) {
for(int d = 0; d < COLUMNS; d++) {
if(maxNum < array[c][d]) {
maxNum = array[c][d];
}
}
}
// Seconds pass; Get all values equal to max value
for (int c = 0; c < ROWS; c++) {
for (int d = 0; d < COLUMNS; d++) {
if (array[c][d] == maxNum) {
maxLocations[maxLocationIndex].row = c;
maxLocations[maxLocationIndex].column = d;
maxLocationIndex++;
}
}
}
// Print the max locations array
printf("Largest value in the array is %d\n", maxNum);
for (int i = 0; i < maxLocationIndex; i++) {
printf("[%d][%d] \n", maxLocations[i].row, maxLocations[i].column);
}
}
Update:
Thanks to suggestion from #Ian Abbott, there is also a way to do all this in one pass. We would just need to reset the maxLocationIndex whenever we find a new max value:
for(int c = 0; c < ROWS; c++) {
for(int d = 0; d < COLUMNS; d++) {
if(maxNum < array[c][d]) {
maxNum = array[c][d];
// Reset Max locations index
maxLocationIndex = 0;
}
if (array[c][d] == maxNum) {
maxLocations[maxLocationIndex].row = c;
maxLocations[maxLocationIndex].column = d;
maxLocationIndex++;
}
}
}

Neighbours algorithm

Hi a have a code like these:
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[row].length; col++) {
// Do something with a[row][col];
}
}
But i want to make an operation in a grid (8-neighbours) for every a[row][col] , however when im at the corners i will have problems (i don't know how to check if im in a corner), i was thinking in code a lot of if - conditionals, but i dont know the effective way to do this..
If there is a perse method for do this types of traversal neighbours arrays i would very greatful if you could give me a link, I've spent all day looking for information and I can't find anything.
You can use these arrays which represent the changes in the indexes when you look at the neighbors from a given position:
int dx[] = {-1,0,1,1,1,0,-1,-1};
int dy[] = {-1,-1,-1,0,1,1,1,0};
At position (row, col), dx[i] represents a change in row and dy[i] represents a change in col. You can use each position in the array to look at the neighbors.
Make a helper function that checks if a position is safe:
boolean isValidPosition(int x, int y) {
return 0 <= x && x < a.length && 0 <= y && y < a[x].length;
}
Then iterate over all 8 positions and you will have access to the neighbors via a[row + dx[i]][col + dy[i]].
for (int row = 0; row < a.length; row++) {
for (int col = 0; col < a[row].length; col++) {
for (int i = 0; i < 8; i++) {
if (isValidPosition(row + dx[i], col + dy[i])) {
// Do something with a[row + dx[i]][col + dy[i]];
}
}
}
}

C 2D Arrays removing certain predetermined rows by shifting the ones below it

This is my first post here.
An assignment of my online course in C asked me to remove each row in a real(non dynamically allocated, pointers are not used) whose average sum is greater than the average sum of the whole matrix. The rows should be "removed" by shifting the ones below it up by one position.
I have set up a matrix with the following code:
int matrix[100][100]
Now, my idea was to create a regular 1D array which stores the indexes of the rows to-be-removed.
This is how I did it:
k = 0;
for (i = 0; i < no_of_rows; i++) {
average_sum_of_row = 0;
for (j = 0; j < no_of_columns; j++) {
average_sum_of_row += matrix[i][j];
}
average_sum_of_row = average_sum_of_row / no_of_columns;
if (average_sum_of_row > average_sum_of_matrix) {
indexes_of_rows_to_remove[k] = i;
k++;
l++;
}
}
Which works just fine! I get an array whose elements are the indexes of the rows which need to be removed. However, while implementing my code into the following:
m = 0;
for (i = 0; i < V; i++) {
if (indexes_of_rows_to_remove[m] == i) {
for (k = i; k < no_of_rows - 1; k++) {
for (j = 0; j < no_of_columns; j++) {
matrix[k][j] = matrix[k + 1][j];
}
}
i--;
no_of_rows--;
}
m++;
}
It does not work. What I used is my existing code of removing a row by shifting the ones below it up and decreasing the number of rows by one, but this simply doesn't work and I don't know why.
I tried using a separate integer(m) to go through all elements of the array of indexes, but for some reason it does not work.
Thanks all!
You can use this algorithm, which skips the rows to be deleted:
k = 0
For i in number of rows:
If i not to be deleted:
matrix[k] = matrix[i] # copy the whole row here
k++
The algorithm you are trying to implement is complicated and very inefficient.

bitwise | in a 2d-array C

I haven't used C for quite a long time.
I have a 2d array, where each element is 1 or 0. I want to know for each line whether there is 1 or not. I am doing so :
for (row = xa; row < 50; row++) {
// need to know first if there is any '1' in the next line
if (|schemaArray[row] == 1) {
printf("1 found in row %d\n",row );
}
}
Am I using it wrong?
schemaArray is an argument in my parameter list :
int findPerimeter(int schemaArray[50][50]) {
You will have to iterate over all columns of the row to check if there exists a 1.
Sample code:
for (int row = xa; row < 50; row++ ) {
int bIsOne = 0;
for (int i = 0;i < col_size && !bIsOne; i++ ) {
bIsOne = bIsOne | schemaArray[row][i];
}
if( bIsOne )
printf("1 found in row %d\n",row );
}
This can't be done using bit-wise operators unless you construct a bitmap for the schemaArray. In that case, you could check the entire row at once.
This is mostly an overkill. Do it only if your piece of code is performance critical.
Preprocessing step: Construct a bitmap array for schemaArray
long long bitMapSchemaArray[ROW_SIZE];
for (int i = 0; i < row_count; i++) {
long long columnBitMap = 0;
for (int j = 0; j < col_count; j++ ) {
columnBitMap <<= 1; // Multiplies by 2
columnBitMap = columnBitMap | schemaArray[i][j]; // Add a 1 if schemaArray[i][j]=1 else 0
}
bitMapSchemaArray[i] = columnBitMap;
}
In your function, you could then use the bitmap as:
for (int i = 0; i < row_count; i++) {
if( bitMapSchemaArray[i] )
printf("There is a 1 in %d row\n", i+1);
}
However, at most, you will be able to have 64 columns in 2-D array assuming we use an array of 64 bit integers. Of course, you can also extrapolate this to have more than 64 columns by using ceil(column_count)/64 64 bit integers. In that case, bitwise OR each column to check if the cumulative result is still non-zero.
Simple just iterate over the entire row and find out
for (row = 0; row < 50; row++) {
for (col= 0; row < 50; col++) {
if (schemaArray[row][col] == 1){
printf("1 found in row %d\n",row );
break;
}
}
}

Resources