I'm having a very big problem, and it is because I need to remove any duplicate number in a random X x Y array. I tried to do it by writing four "fors" one inside the other, but it didn't work. Can someone help me?
Let's say that there's 34 three times in the array, so the first one will remain 34 and the others will be set to 0, and the other 0's will remain 0.
for (int linha = 0; linha < tamanhoLinhas; linha++) {
for (int coluna = 0; coluna < tamanhoColunas; coluna++) {
matriz[linha][coluna] = rand.nextInt(100);
}
}
for (int linha = 0; linha < tamanhoLinhas; linha++) {
for (int coluna = 0; coluna < tamanhoColunas; coluna++) {
int numeroAtual = matriz[linha][coluna];
for (int linha2 = 0; linha2 < tamanhoLinhas; linha2++) {
for (int coluna2 = 0; coluna2 < tamanhoColunas; coluna2++) {
if (numeroAtual == matriz[linha][coluna]){
matriz[linha][coluna] = 0;
}
}
}
}
}
for (int i = 0; i < tamanhoLinhas; i++) {
for (int j = 0; j < tamanhoColunas; j++) {
System.out.print(matriz[i][j] + " ");
}
System.out.println();
}
}
for (int linha = 0; linha < tamanhoLinhas; linha++) {
for (int coluna = 0; coluna < tamanhoColunas; coluna++) {
int numeroAtual = matriz[linha][coluna];
for (int linha2 = 0; linha2 < tamanhoLinhas; linha2++) {
for (int coluna2 = 0; coluna2 < tamanhoColunas; coluna2++) {
if (numeroAtual == matriz[linha][coluna]){
matriz[linha][coluna] = 0;
}
}
}
}
}
This code results in setting every element of the array to zero. As an example, let's say
linha == 3, coluna == 3
upon entering the third for loop, and numeroAtual == 22. The inner loops will scan the entire array and at some point will get to [3,3], which will be equal to numeroAtual; this will cause the value of matriz[3,3] to be set to zero.
That will repeat for every element in the matrix.
Well, I did it, but it's a little different now.
Initially, the program would modify all of the repeated numbers, but now the user chooses only one, and the program creates a random two dimensional array and find the repeated numbers and switch them for 0.
Here is how I did it:
public void questao7(int numeroSelecionado) {
int tamanhoLinhas = (rand.nextInt(9) + 1);
int tamanhoColunas = (rand.nextInt(9) + 1);
int matriz[][] = new int[tamanhoLinhas][tamanhoColunas];
boolean duplicado = false;
for (int linha = 0; linha < tamanhoLinhas; linha++) {
for (int coluna = 0; coluna < tamanhoColunas; coluna++) {
matriz[linha][coluna] = rand.nextInt(100);
}
}
System.out.println("Matriz original: ");
for (int i = 0; i < tamanhoLinhas; i++) {
for (int j = 0; j < tamanhoColunas; j++) {
System.out.print(matriz[i][j] + " ");
}
System.out.println();
}
for (int linha = 0; linha < tamanhoLinhas; linha++) {
for (int coluna = 0; coluna < tamanhoColunas; coluna++) {
if (!duplicado) {
if (matriz[linha][coluna] == numeroSelecionado){
duplicado = true;
}
} else if (matriz[linha][coluna] == numeroSelecionado) {
matriz[linha][coluna] = 0;
}
}
}
System.out.println("Matriz modificada: ");
for (int i = 0; i < tamanhoLinhas; i++) {
for (int j = 0; j < tamanhoColunas; j++) {
System.out.print(matriz[i][j] + " ");
}
System.out.println();
}
}
Related
i have to check the validity of a sudoku as a homework. the rows and cols were no big deal, but i'm stuck at checking the boxes.
i want to loop through the 3x3 sub-boxes and check them for duplicates, with copying the numbers into a smaller 3x3 array, flattening it and then checking it for duplicates.
my while loop doesn't seem to make sense tho, the first iteration works but the second one writes wrong values into my new array. i just don't know where to add my boxcount.
i feel like a noob, if someone can help i'd be thankful
private static boolean isValidSudokuSolution(int[][] sudokuField) {
// TODO: Implementieren Sie hier Ihre Lösung für die Methode
//rows
int row = 0;
while (row < sudokuField.length) {
for (int i = 0; i < sudokuField[row].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[row][i] == sudokuField[row][j]) {
return false;
}
}
}
row++;
}
//cols
int col = 0;
while (col < sudokuField.length) {
for (int i = 0; i < sudokuField[col].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[i][col] == sudokuField[j][col]) {
return false;
}
}
}
col++;
}
//box
int boxCount = 0;
while (boxCount < sudokuField.length) {
//create box array
int[][] box = new int[3][3];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
box[i][j] = sudokuField[i + boxCount][j];
}
}
//flatten box
int[] flattenedBox = new int[sSize];
int counter = 0;
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int num = box[i][j];
flattenedBox[counter + j] = num;
}
counter += 3;
}
//look for duplicates
for (int i = 0; i < flattenedBox.length; i++) {
for (int j = 0; j < i; j++) {
if (flattenedBox[i] == flattenedBox[j]) {
return false;
}
}
}
boxCount += 3;
}
return true;
}
I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
for(j=0;j
{
if(j>i)
d1+=a[i][j];. // Above the diagon
else
if(i>j)
d2+=a[i][j];. // Below the diagonal
}
I have a two dimensional array and I fill it with scanner. I want to copy the elements that start with letter 'a' to a new one dimensional array without using ArrayList. Please advise on what I can do to get this code functioning properly. the question is how can I know the new array size while I don't know how many words start with letter a
Here is what I have so far:
import java.util.Scanner;
class Untitled {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[][] name = new String[2][2];
for (int i = 0; i < name.length; i++) {
for (int j = 0; j < name[i].length; j++) {
name[i][j] = input.next();
}
}
student(name);
}
public static void student(String[][] arr) {
int count = 0;
int c2 = -1;
String[] name2 = new String[count];
String temp = "";
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
c2++;
temp = arr[i][j];
name2[c2] = temp;
count++;
temp = "";
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
}
}
A two dimensional arrray of size [n][n] is equal to one dimensional array of size n. If you want to copy them on proper place then you can use this formula, it is useful if you later want to copy these elements back to twodimensional array at proper places:
int v = i * n + j; // i and j your loops and n is length of rows or colums.
array[v] = array[i][j];
for in your codes it's like:
int v = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
v = i * arra.length +j;
name2[v] = arr[i][j];
count++;
Ok here is a working code:
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String[][] name = new String[2][2];
System.out.println("Enter the name: ");
for (int i = 0; i < name.length; i++) {
for (int j = 0; j < name[i].length; j++) {
name[i][j] = input.next();
}
}
student(name);
}
public static void student(String[][] arr) {
int count = 0;
int v = 0;
String[] name2 = new String[arr.length*arr[0].length];
String temp = "";
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
v = i *+arr[0].length + j;
name2[v] = arr[i][j];
count++;
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
System.out.println("printing without nulls");
//if you don't want null to be printed then do this:
for (int i = 0; i < name2.length; i++) {
if(name2[i] != null)
System.out.println(name2[i]);
}
}
I did it with two nested for loop one for indicating the array size and the other for filling the elements into the array, it does the work but is there any way to do this better
public static void student(String[][] arr) {
int size = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
size++;
}
}//inner
}//outer
String[] name2 = new String[size];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j].charAt(0) == 'a') {
name2[count] = arr[i][j];
count++;
}
}//inner
}//outer
for (int i = 0; i < name2.length; i++) {
System.out.println(name2[i]);
}
Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.
For example, if I have the following 2d array:
int [][] array = {4,5,6},{3,4,5},{2,3,4};
I would want it to output an array as so:
{2 3 4}, {3 4 5}, {4 5 6}
Methodology:
a.) take the sums of each row and make a 1D array of the sums
b.) do a bubble sort on rowSum array
c.) swap the rows of the original array based on the bubble sort swaps made
d.) then print the newly row sorted array.
Here's my code so far:
public void sortedArrayByRowTot() {
int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
int [] rowSums = new int [tempArray2.length];
int sum = 0;
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
sum += tempArray2[i][j];
}
rowSums[i] = sum;
sum = 0;
}
int temp;
int i = -1;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
}
}
if(!isSwap){
break;
}
}
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
}
Not sure if I am doing part c of my methodology correctly?
It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"
As #shmosel said, you can do it like this:
public static void sortedArrayByRowTot() {
int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}
I was able to solve my question. Thanks.
public void sortedArrayByRowTot() {
//Creates tempArray2 to copy salaryArray into
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
//Copies salaryArray into tempArray2
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
//Creates rowSum array to store sum of each row
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Modified Bubble Sort of rowSum array (highest to lowest values)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] < rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
//Prints sorted array
System.out.println("Sorted array: ");
for (i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[i].length; j++) {
System.out.print("$"+ tempArray2[i][j] + " ");
}
System.out.println();
}
}
You may try this way. That I have solved.
public class Solution{
public static void sortedArrayByRowTot() {
int [][] salaryArray = { {4,5,6},{3,4,5},{2,3,4} };
int [][] tempArray2 = new int [salaryArray.length][salaryArray[0].length];
for (int i = 0; i < salaryArray.length; i++) {
for (int j = 0; j < salaryArray[i].length; j++) {
tempArray2[i][j] = salaryArray[i][j];
}
}
// Buble Sort to store rowSums
int [] rowSums = new int [tempArray2.length];
for (int i = 0; i < tempArray2.length; i++) {
for (int j = 0; j < tempArray2[0].length; j++) {
rowSums[i] += tempArray2[i][j];
}
}
//Buble Sort by Rows Sum (Lowest Value to Highest)
int temp;
int i = 0;
for(int j = rowSums.length; j > 0; j--){
boolean isSwap = false;
for (i = 1; i < j; i++) {
if(rowSums[i-1] > rowSums[i]) {
temp = rowSums[i-1];
rowSums[i-1] = rowSums[i];
rowSums[i] = temp;
isSwap = true;
//swaps rows in corresponding tempArray2
int [] temp2 = tempArray2[i-1];
tempArray2[i-1] = tempArray2[i];
tempArray2[i] = temp2;
}
}
if(!isSwap){
break;
}
}
/** No Need.
for (int k = 0; k < tempArray2.length; k++) {
temp = tempArray2[i-1][k];
tempArray2[i-1][k] = tempArray2[i][k];
tempArray2[i][k] = temp;
}
*/
for (int b = 0; b < tempArray2.length; b++) {
for (int c = 0; c < tempArray2[b].length; c++) {
System.out.print(tempArray2[b][c] + " ");
}
}
}
public static void main(String[] args) {
sortedArrayByRowTot();
}
}
Examples of input:
3
4
Examples of output (assume that spaces = new lines.)
QQQH
QQHH
QHHH
QQQQH
QQQHH
QQHHH
QHHHH
So far, the fragment of code that attempts to print this is (Assume that all variables are pre-defined):
public int getSize()
{
for (int i = size; i > 0; i--){
for (int j = 1; j < size; j++){
out.print("Q");
out.print("H");
}
out.println("");
}
return 0;
}
It just prints: (assume that spaces = new lines.)
QHQHQHQHQH
QHQHQHQHQH
QHQHQHQHQH
QHQHQHQHQH
QHQHQHQHQH
For input of 5. I'm not quite sure how to make it print only the number of times of its respective integer value. Can someone explain?
You could break the inner loop it two, like this:
for (int i = size; i > 0; i--) {
for (int j = 0; j < i; j++) {
out.print("Q");
}
for (int j = i; j < size + 1; j++) {
out.print("H");
}
out.println();
}
Output:
QQQH
QQHH
QHHH
QQQQH
QQQHH
QQHHH
QHHHH
Or if you don't want to break the loop, you can use the ternary operator:
for (int i = size; i > 0; i--) {
for (int j = 0; j < size + 1; j++) {
out.print(j < i ? 'Q' : 'H');
}
out.println();
}
Try this
for (int i = 0; i < size; i++) {
for (int j = 1; j <= size-i; j++) {
System.out.print("Q");
}
for (int k = 0; k <= i; k++) {
System.out.print("H");
}
System.out.println("");
}
try this code block instead:
int j=0;
for (int i = size; i > 0; i--)
{
j=0;
while(j < i)
{
out.print("Q");
j++;
}
j=i;
while(j < size+ 1)
{
out.print("H");
j++;
}
out.println();
}
Tested with sample inputs. Working fine
public int getSize() {
for (int i = 1; i < size+1; i++) {
for (int j = 0; j < size+1; j++) {
int Qtimes = size-i;
if(j <= Qtimes) {
System.out.print("Q");
} else{
System.out.print("H");
}
}
System.out.println("");
}
return 0;
}
This works if the input is 4 - for example -change it to any number
public int getSize()
{
int cnt = 0;
int i,j,k = 0;
for ( i = 4; i > 0; i--){
for ( j = 0; j < i; j++){
System.out.print("Q");
}
cnt ++;
for( k = 0 ; k <cnt ; k++) {
System.out.print("H");
}
System.out.println("");
}
return 0;
}
output is
QQQQH
QQQHH
QQHHH
QHHHH