I have to segregate the even and odd numbers in a 2D array in java in two different rows (even in row 1 and odd in row two). I have included the output of my code bellow here is what I have:
class TwoDimensionArrays {
public static void main(String[] args) {
int sum = 0;
int row = 2;
int column = 10;
int[][] iArrays = new int[row][column];
for(int rowCount = 0; rowCount < iArrays.length /*&& rowCount % 2 == 0*/; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length /*&& columnCount % 2 != 0*/; columnCount++) {
if(columnCount % 2 != 0 /*&& rowCount % 2 == 0*/) {
iArrays[rowCount][columnCount] = columnCount + 1;
}
}
}
System.out.println("The array has " + iArrays.length + " rows");
System.out.println("The array has " + iArrays[0].length + " columns");
for(int rowCount = 0; rowCount < iArrays.length; rowCount++) {
for(int columnCount = 0; columnCount < iArrays[0].length; columnCount++) {
System.out.print(iArrays[rowCount][columnCount] + " ");
sum += iArrays[rowCount][columnCount];
}
System.out.println();
}
System.out.println("The sum is: " +sum);
}
}
//OUTPUT//
/*The array has 2 rows
The array has 10 columns
0 2 0 4 0 6 0 8 0 10
0 2 0 4 0 6 0 8 0 10
The sum is: 60*/
Can anyone lend a hand?
Thank you in advance.
Instead of passing over the list twice try this:
for(int v = 0; v < 20; v++) {
iArrays[v % 2][(int)v/2] = v;
}
This will set iArrays to:
[[0,2,4,6,8,10,12,14,16,18],
[1,3,5,7,9,11,13,15,17,19]]
What is happening is the row is being set to the remainder of v % 2 (0 if v is even, 1 if v is odd) and the col is being set to the corresponding index (with the cast to int to drop any fraction). You can even generalize it like this:
public static int[][] group(int groups, int size){
int[][] output = new int[groups][size];
for(int value = 0; value < (groups*size); value++) {
output[value % groups][(int)value/groups] = value;
}
return output;
}
Then a call to group(2, 10) will return:
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]]
If I understand your question, one solution is to iterate the array from 0 to COLUMN and set each successive slot to two plus the previous slots value (starting with 0 for even and 1 for odd). Like,
public static void main(String arg[]) {
final int ROW = 2;
final int COLUMN = 10;
int[][] iArrays = new int[ROW][COLUMN];
for (int i = 0; i < COLUMN; i++) {
iArrays[0][i] = (i > 0) ? iArrays[0][i - 1] + 2 : 0; // 0,2,4,6...
iArrays[1][i] = (i > 0) ? iArrays[1][i - 1] + 2 : 1; // 1,3,5,7...
}
System.out.println(Arrays.deepToString(iArrays));
}
Output is
[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]]
Related
I'm trying to get the sum of each row printed out after that row. It needs to be formatted like this
2 5 6 3| 16
9 4 4 7| 24
1 10 2 3| 16
8 4 5 3| 20
-----------------
20 23 17 16| 76
Doesn't have to be as nice, but close to it. I have to use a toString method, here is what I have so far.
Edit: Got it solved thanks to #KevinAnderson. Needed to append rowSum[r] to Arrays instead of trying to use another for loop to get the values.
public String toString() {
//Stores the colSum into a string col
String col = "";
for (int j = 0; j < cell[0].length; j++) {
col += " " + colSum[j];
}
//Calculates the total of both the rows and columns
for (int i = 0; i < cell.length; i++) {
for (int j = 0; j < cell[0].length; j++) {
grandTotal += cell[i][j];
}
}
//Prints the array
String array = "";
for (int r = 0; r < cell.length; r++) {
for (int c = 0; c < cell[r].length; c++) {
array += " " + cell[r][c];
}
array += "|" + +rowSum[r] + "\n";
}
return array + "-----------------" + "\n" + col + "| " + grandTotal;
}
rowSum and colSum are calculated in a separate method that can be provided if need be, but they do work as intended.
What I believe I need to do is store the value of rowSum in either an int value and print it, or increment through rowSum in some way. I've tried both, and so far it prints out the whole array that it is stored into.
Here a solution by using two for-loops.
One to print the sum of the rows the other to print the sum of the columns
Also to build the whole sum get track of it either in the first or the second for-loop.
package so;
import java.util.*;
public class RemoveString {
public static void main(String[] args) {
int[][] arr = {{2, 5, 6, 3}, {9, 4, 4, 7}, {1, 10, 2, 3}, {8, 4, 5, 3}};
System.out.println(toString(arr));
}
public static String toString(int[][] cell) {
int sum = 0;
int allSum = 0;
int counter = 0;
String resultString = "";
for (int i = 0; i < cell.length; i++) {
for (int j = 0; j < cell[i].length; j++) {
// Count the columns for the condition later on
if (i == 0) {
counter++;
}
sum += cell[i][j];
resultString += cell[i][j] + " ";
}
resultString += "| " + sum + "\n";
sum = 0;
}
resultString += "--------------\n";
for (int i = 0; i < counter; i++) {
for (int j = 0; j < cell.length; j++) {
sum += cell[j][i];
}
allSum += sum;
resultString += sum + " ";
sum = 0;
}
resultString += "|" + allSum;
return resultString;
}
}
Creates the output
2 5 6 3 | 16
9 4 4 7 | 24
1 10 2 3 | 16
8 4 5 3 | 20
--------------
20 23 17 16 |76
You can first prepare two arrays of sums by rows and columns, then it is easier to print this:
2 5 6 3 | 16
9 4 4 7 | 24
1 10 2 3 | 16
8 4 5 3 | 20
----------------
20 23 17 16 | 76
Code:
// assume that we have a rectangular array
int[][] arr = {
{2, 5, 6, 3},
{9, 4, 4, 7},
{1, 10, 2, 3},
{8, 4, 5, 3}};
// array of sums by rows
int[] sum1 = Arrays.stream(arr)
.mapToInt(row -> Arrays.stream(row).sum())
.toArray();
// array of sums by columns
int[] sum2 = Arrays.stream(arr)
.reduce((row1, row2) -> IntStream
.range(0, row1.length)
.map(i -> row1[i] + row2[i])
.toArray())
.orElse(null);
// output
IntStream.range(0, arr.length)
// iterate over the indices of the rows of an array
.peek(i -> Arrays.stream(arr[i])
// elements of the row
.forEach(e -> System.out.printf("%2d ", e)))
// sum of the row
.peek(i -> System.out.printf("| %2d", sum1[i]))
// end of the row, new line
.forEach(i -> System.out.println());
// line of hyphens, assume that all numbers are two-digit
System.out.println("-" .repeat(arr[0].length * 2 + arr[0].length + 4));
// line of sums by columns
IntStream.range(0, sum2.length)
// sum of column
.forEach(i -> System.out.printf("%2d ", sum2[i]));
// last number, sum of sums, total
System.out.printf("| %2d", Arrays.stream(sum2).sum());
"%2d" - format as a two-digit number.
See also: Pascal's triangle 2d array - formatting printed output
I have a 2d array like this:
2 0 0 2 0 4
2 0 0 2 0 4
2 0 0 2 0 4
And I want to shift all the zeros to the left, so for that I made this method:
public static void shiftLeft(int [][] array){
for (int j = 0; j < array.length; j++) {
for (int i = 0; i < array.length - 1; i++) {
if ((array[j][i] != 0) && (array[j][i + 1] == 0)) {
array[j][i + 1] = array[j][i];
array[j][i] = 0;
}
}
}
}
But the output I get is this:
0 0 2 0 2 4
0 0 2 0 2 4
0 0 2 0 2 4
How can I make all zeros to go to the left?
In my opinion the easiest way to do this is using 3 nested loops.
Variable i iterates over the rows.
Variable j1 finds the first nonzero element starting from the left of each row.
Variable j2 finds the first zero element after j1 and swaps them.
The code below assumes that the bidimensional matrix A was declared as A[N][M], where N and M are respectively the number of rows and number of columns.
for(int i =0;i<N;i++){
for(int j1=0;j1<M;j1++){
if (A[i][j1]==0)
continue;
for(int j2=j1;j2<M;j2++){
if( A[i][j2]==0){
//swap
int tmp=A[i][j1];
A[i][j1]=A[i][j2];
A[i][j2]=tmp;
}
}
}
}
In fact Trugis's answer is also correct but it will just swap the zero with the first non zero. So the order of the numbers will change.
This answer will not change the order of the numbers :
int[][] A = { { 2, 3, 4, 2, 4, 4, 5, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 4, 3, 4, 5, 6 },
{ 2, 0, 4, 2, 0, 4, 1, 2, 3, 4 }};
int N = A.length;
int M = A[0].length;
int firstZeros = 0;
for(int i = 0; i < N; i++) { // Loop over the rows
for(int j1 = 0; j1 < M; j1++) {
// If there is a zero we pass by
if (A[i][j1] == 0 && firstZeros == j1) {
firstZeros++;
continue;
}
// Otherwise, we have a value so we want to check if there is a zero afterwards
for(int j2 = j1+1; j2 < M; j2++) {
// If we find a zero we move it to the left
if(A[i][j2] == 0) {
for (int j3 = j2; j3 > firstZeros; j3--) {
// Change zero with previous value
A[i][j3] = A[i][j3-1];
A[i][j3-1] = 0;
}
firstZeros++;
}
}
}
firstZeros = 0;
}
Using java, I am supposed to create a program that stores the square of the numbers 0, 1, 2 & 9 in an ArrayList of 10 elements.
I have created part of the code that displays the numbers and its squares but the program goes straight down with all the numbers and does not look organized. Can someone help me write it out like like this instead:
number: 0 square: 0
number: 1 square: 1
number: 2 square: 4
Code
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int value : temp) {
System.out.println(value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(value);
}
}
You need just one loop like this :
public static void main(String[] args) {
int[] temp = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i] + "\t" + (int)Math.pow(temp[i], 2));
}
}
OutPut
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
If you want to store your results in an ArrayList you can use :
List<int[]> array = new ArrayList<>();//create a List which take an array of int
int arr[] = new int[2];//create a temporary array of 2 elements
for (int i = 0; i < temp.length; i++) {
System.out.println("Number: " + temp[i] + " \tSquare: " + (int) Math.pow(temp[i], 2));
arr[0] = temp[i];//add your number to your array pos 1
arr[1] = (int) Math.pow(temp[i], 2);//add the power to the 2ed position
array.add(arr);//add your array to your list
}
public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
// here you are printing all your numbers in the array, so the output will be:
// 0
// 1
// ...
// 9
for (int value : temp) {
System.out.println(value);
}
// after that, you calculate and store them in the same array; so your array now look like this:
// [0,1,4,9,...,81]
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
// here you are printing again your array
// 0
// 1
// 4
// ...
// 81
for (int value : temp) {
System.out.println(value);
}
}
to get your desired outcome, you have to calculate the number before printing everything... one option will be to create another array
int[] square = new int[9];
calculate in the first for loop and save the result in the square array and print them, something like this:
for (int i = 0; i < temp.length; i++) {
square[i] = (int) Math.pow(temp[i],2);
System.out.println("number " + temp[i] + " square: " + square[i]);
}
Assuming the original question which referred to an ArrayList was correct (the OP's example only had an array), and assuming the results are supposed to be stored in the array (per the question), then the following will work:
public static void main(String[] args)
{
// instantiate ArrayList
List<Double> array = new ArrayList<>();
// load the values
for (int i = 0; i < 10; ++i) {
array.add(i, Math.pow(i, 2));
}
// output
for (int i = 0; i < array.size(); ++i) {
System.out.println(String.format("%2d\t%3.0f", i, array.get(i)));
}
}
Output:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
Try this :
public static void main(String[] args) {
int[] temp = {0, 1,2,3,4,5,6,7,8,9};
for (int value : temp) {
System.out.println("number : "value);
}
for (int i = 0; i < temp.length; i++) {
temp[i] = (int) Math.pow(temp[i], 2);
}
for (int value : temp) {
System.out.println(" square : " + value + "\n");
}
}
I am trying to find to the max sum of an array and print the corresponding sequence that produces that max sum. I have been able to get the correct sum but when I try to print the sequence for some of the test arrays my program leaves off one of the indices. For example, for the array [1, -1, 2, 3, -2] my program finds the max sum of 5 but it only prints 1, -1, 2 instead of 1, -1, 2, 3. I know the problem is inside my for loop and my count variable not incrementing correctly but I do not know how to fix it.
import java.util.*;
public class practice
{
public static void main(String args[])
{
int arr[] = {1, -1, 2, 3, -2};
int arr2[] = {1, 12, -2, -15, 10};
int arr3[] = {0, -1, -3, -5, -6};
int arr4[] = {1, 2, 3, 4, 5};
int arr5[] = {1, 12, -2, 15, 10};
subsequence(arr);
subsequence(arr2);
subsequence(arr3);
subsequence(arr4);
subsequence(arr5);
}
public static void subsequence(int[] arr)
{
int max = 0;
int tempMax = 0;
int count = 0;
// My problem is in here:
for (int i = 0; i < arr.length; i++)
{
tempMax += arr[i];
if (max < tempMax)
{
max = tempMax;
count++;
}
}
System.out.println("count = " + count);
System.out.println("Max sum is " + max);
System.out.print("Sequence is: ");
for (int j = 0; j < count; j++)
System.out.print(arr[j] + " ");
System.out.println("\n");
}
}
here is my output
count = 3
Max sum is 5
Sequence is: 1 -1 2
count = 2
Max sum is 13
Sequence is: 1 12
count = 0
Max sum is 0
Sequence is:
count = 5
Max sum is 15
Sequence is: 1 2 3 4 5
count = 4
Max sum is 36
Sequence is: 1 12 -2 15
here is my edited code:
public class practice
{
public static void main(String args[])
{
int arr[] = {1, -1, 2, 3, -2};
int arr2[] = {1, 12, -2, -15, 10};
int arr3[] = {0, -1, -3, -5, -6};
int arr4[] = {-1, 2, 3, -4, -5};
int arr5[] = {1, 12, -2, 15, 10};
subsequence(arr);
subsequence(arr2);
subsequence(arr3);
subsequence(arr4);
subsequence(arr5);
}
public static void subsequence(int[] arr)
{
int max = 0;
int tempMax = 0;
int count = 0;
int start = 0;
int end = 0;
if (arr[0] < 0)
start++;
for (int i = start; i < arr.length; i++)
{
tempMax += arr[i];
if (max < tempMax)
{
max = tempMax;
count = i;
}
if (Math.abs(arr[i]) < tempMax)
end = i;
}
System.out.println("count = " + count);
System.out.println("Max sum is " + max);
System.out.print("Sequence is: ");
if (arr[end] < 0)
end--;
for (int j = start; j <= end; j++)
System.out.print(arr[j] + " ");
System.out.println("\n");
}
}
and here is my new output:
count = 3
Max sum is 5
Sequence is: 1 -1 2 3
count = 1
Max sum is 13
Sequence is: 1 12
count = 0
Max sum is 0
Sequence is: 0
count = 2
Max sum is 5
Sequence is: 2 3
count = 4
Max sum is 36
Sequence is: 1 12 -2 15 10
Your count variable doesn't make sense, since you only increment it if you find a new candidate for the maximum. When you find a new maximum candidate, set count to the current index :
count = i;
Then when you print the sequence, change the condition to j <= count.
BTW, I'm not sure your implementation is correct. You always return a sub-sequence that starts in the beginning of the array. What if the sub-sequence with the max sum doesn't start at the beginning? (for example, in [-1,2,3,4,5], the max sequence is [2,3,4,5]).
I am encountering a problem generating 6 random numbers between 1 and 6 in Java. All the numbers have to be unique. When I enter kolon value 5, the arrays should be like this:
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
I don't want the program to generate the same two numbers. What is wrong here?
Relevant code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter row quantity: ");
int kolon = input.nextInt();
Integer[][] dizi_asil = new Integer[kolon][6];
for (int i = 0; i < kolon; i++) {
Integer[] dizi = new Integer[6];
for (int j = 0; j < 6; j++) {
dizi[j] = (int) ((Math.random() * 6) + 1);
for (int u = 0; u < 1; u++) {
for (int k = 0; k < j; k++) {
while (dizi[k] == dizi[j]) {
dizi[j] = (int) ((Math.random()* 6) + 1);
u++;
}
}
}
dizi_asil[i][j] = dizi[j];
}
Arrays.sort(dizi_asil[i]);
}
for (int i = 0; i < dizi_asil.length; i++) {
for (int k = 0; k < dizi_asil[i].length; k++) {
System.out.print(dizi_asil[i][k] + "\t");
}
System.out.println();
}
create a list containing 1 to 6. then shuffle it using Collection.shuffle. Then you will get random unique number
This is an easy way:
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
Collections.shuffle(list);
// you can convert it to an array if you need to.
A very simple fix - replace u++; with u--;. ++ will make the loop stop, -- will make it carry on.
Though I'd suggest something more like the below. I hope it's easy enough to understand.
Integer[] dizi = new Integer[6];
for (int j = 0; j < 6; j++)
{
boolean isValid;
do
{
dizi[j] = (int) ((Math.random() * 6) + 1);
isValid = true;
for (int k = 0; isValid && k < j; k++)
if (dizi[k] == dizi[j])
isValid = false;
}
while (!isValid);
dizi_asil[i][j] = dizi[j];
}
I'd also suggest the Random class, which has a nextInt(int) method, which is better than (int) ((Math.random() * 6) + 1).
But shuffling is probably a faster way to do it. Either use the API like one of the other answers or look into the Fisher-Yates / Knuth shuffle for an easy shuffle algorithm.
Try Collections.shuffle(list);
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i<7 ; i++)
list.add(i);
Or you can do :
List<Integer> list = Arrays.asList(1,2,3,4,5,6)
Collections.shuffle(list);
Iterate the list and get unique value each time.
A much shorter way is to use shuffle as many have mentioned already.
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter row quantity: ");
List<Integer> rolls = Arrays.asList(1, 2, 3, 4, 5, 6);
for (int i = 0, rows = input.nextInt(); i < rows; i++) {
Collections.shuffle(rolls);
System.out.println(rolls);
}
}
if you run it you get something like
Please enter row quantity:
5
[5, 6, 3, 2, 4, 1]
[5, 4, 3, 6, 2, 1]
[6, 4, 2, 3, 5, 1]
[3, 1, 6, 2, 5, 4]
[4, 1, 6, 3, 5, 2]
Imports:
import acm.util.RandomGenerator;
private RandomGenerator rgen = RandomGenerator.getInstance();
Actually picking:
randnum = rgen.nextInt(1, 6);
This picks a random number between 0 and 5. You can just do this for 1 through 6:
randnum = rgen.nextInt(2, 7);
Or:
randnum = rgen.nextInt(1, 6);
randnum++;