Here is what i have done but i have some questions:
class masivins {
public static void main (String args[]) {
int mas[][] = {{0, 2, 7, 0, 8, 5, 3},
{0, 4, 0, 6, 0, 0, 0},
{0, 0, 0, 0, 3, 0, 0},
{7, 0, 0, 9, 1, 0, 7},
{5, 0, 4, 0, 0, 2, 0}};
int nulmas[] = new int [7];
int nul=0;
for(int j=0; j<7; j++) {
nul=0;
for(int i=0; i<5; i++) {
if(mas[i][j]==0) {
nul++;
}
}
nulmas[j]=nul;
}
for(int i=0; i<5; i++) {
for(int j=0; j<7; j++) {
System.out.println(mas[i][j]);
}
System.out.println();
}
System.out.println();
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println();
}
}
so my questions are:
Why after running project there are only 5 "Zeros in each array column....." shown?
What and where i need to change in this code to get out the number of column in which zeros are least?
Question 1 - look at your code:
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
In particular, look at the loop. How many lines do you expect it to print out?
Question 2: You could keep a "least number of 0s in an array column so far" and "column in which the least number of 0s appeared" - then update those variables at the end of the inner loop where you set nulmas[j].
1) because you loop from 0 to 4:
for(int i=0; i<5; i++) {
If you looped until 7, all values would be printed out:
for(int i=0; i<7; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
2) you could keep an index and a minimum counter. The min counter stores the minimum number of zeros, the index the column where this is found:
int nulmas[] = new int [7];
int nul=0;
int minNuls=5;
int minIndex=0;
for(int j=0; j<7; j++) {
nul=0;
for(int i=0; i<5; i++) {
if(mas[i][j]==0) {
nul++;
}
}
nulmas[j]=nul;
if (nul < minNul) {
minNul = nul;
minIndex = j;
}
}
You seem to be very close to answering the question. It looks to me like you've set up the nul_mas array to contain the number of zeros in each column, so the question becomes "which index of nul_mas has the smallest value?". You can do this with two variables - one for the smallest value seen so far, one for the index where it was seen - and a loop through that array to look at each element in turn. (Then, when you've got it working, consider what happens if there is a tie.)
Try:
int leastZeroIndex = 0;
for(int i=0;i<5;i++) {
if (nul_mas[i] < nul_mas[leastZeroIndex])
leastZeroIndex = i;
}
System.out.print(leastZeroIndex);
Though there is no check if there are multiple rows with the lowest amount of zeros.
It looks to me as if you need to create some new arrays, so create an array for each column, and then put the numbers for the column in there. After that, just iterate over that array of arrays which represent the columns and count the numbers (you could use a method for doing this, i.e., int count(int num, int[] arr). I think this'll give the least amount of code.
int[][] mas = ...; // (you have this already), it's [NO_OF_ARRS][NO_OF_COLS] with the data
int[][] colsarrs = new int[NO_OF_COLS][NO_OF_ARRS];
for (int i = 0; i < NO_OF_ARRS; i++) {
for (int j = 0; j < NO_OF_COLS; i++) {
colsarrs[j][i] = mas[i][j];
}
}
int[] resultarr = new int[NO_OF_COLS];
for (int i = 0; i < NO_OF_COLS; i++) {
resultarr[i] = count(0, colsarrs[i]);
}
int count(int num, int[] arr) {
int count;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) ++count;
}
return count;
}
Store the amount of zeros in an additional array (resultarr) gathered from this function for each column. After this, go over the array and find the lowest number, and grab the index of it. That's your column with the lowest amount of zeroes.
int lowestcurr = 0;
for (int i = 0; i < NO_OF_COLS; i++) {
if (resultarr[i] < resultarr[lowestcurr]) {
lowestcurr = i;
}
}
for(int i=0; i<5; i++) {
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println(); place there it
change it on :
int minElement = 0;
for(int i=0; i<7; i++) {
if (nulmas[i] < nulmas[minElement]) minElement = i;
System.out.println("Zeros in each array column: " + nulmas[i]);
}
System.out.println(nulmas[minElement]);
better use "\n" to skip one line in console
Related
New to java and am trying to create a program/method that will take an int array, and return another int array but it replaces the values of the indexes with the value of the elements. (Example {2,1,3} will return {0,0,1,2,2,2}
public static void main(String[] args) {
int[] pracArray = {2, 1, 3};
int sum = 0;
for (int i = 0; i < pracArray.length; i++)
{
sum = sum + pracArray[i];
}
System.out.println("Amount of array indexes: " + sum);
int[] newArray = new int[sum];
System.out.println(Arrays.toString(pracArray));
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[j] = i;
}
}
System.out.println(Arrays.toString(newArray));
}
}
Currently I am getting [2,2,2,0,0,0]. I have tried changing the how many times each for loop iterates with no avail. I have also tried to make the elements of newArray equal to a counter ( int count = 0; and having count++ in the for loop) since the values of the new array will always be 0 - however many runs.
Given the length of your array is 3, your outer 'i' loop is iterating through the values 0,1,2. That means your inner 'j' loop never writes to index 3,4,5 (hence why they are 0 in the output), and why the first 3 indexes are set to '2' (2 is the last indexed processed in the 'i' loop). Try this instead...
int h = 0;
for (int i = 0; i < pracArray.length; i++)
{
for (int j = 0; j < pracArray[i]; j++)
{
newArray[h] = i;
h++;
}
}
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;
"Your program should proceed as follows:
Display a welcome message.
Prompt the user for an integer which is 3. If the number entered is < 3. keep prompting the user until they enter a number 3 (use a do/while). This number will determine the size of the square array.
Fill the array as per pattern 1 and display it using printf to format the array.
Fill the same array as per pattern 2 and display it using printf t0 format the array.
Display a closing message."
Pattern:
I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?
Also any tips on to how to go about the second patterns.
Here is my code.
import java.util.Scanner;
public class a3q33
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n;
do
{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int [][] arr = new int [n][n];
int i, j, k=1;
for(i=0;i<n;i++)
{
if(i % 2 != 0)
{
for(j=n;j>0;j--)
{
k = k+n;
arr[i][j]=k;
k--;
}
}
else
{
for(j=0;j<n;j++)
{
arr[i][j]=k;
k++;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf(arr[i][j]+" ");
}
System.out.printf("");
System.out.println();
}
}
}
Any help would be greatly appreciated!
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?
Also, the for loop in your code:
for(j=n;j>0;j--)
This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.
Instead, try using:
for(j=n-1;j>-1;j--)
It would be a good first steps to look into.
import java.util.Scanner;
public class a3q33{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int n;
do{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int count = 1;
int [][] arr = new int [n][n];
for(int i = 0;i<n; i++){
if(i%2==0){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
else{
for(int j = n-1;j>=0; j--){
arr [i][j] = count;
count++;
}
}
}
System.out.println("\nPattern 1 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
// reset count back to 1 and fill the array in the same way only without the if/else
// for n = 5 for example this will produce [1, 2, 3, 4, 5 ]
// [6, 7, 8, 9, 10]
// [11,12, 13, 14, 15]
// [16,17, 18, 19, 20]
// [21,22, 23, 24, 25]
count = 1;
for(int i = 0;i<n; i++){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
// rotate arrays using arraycopy; for array at index 1 rotate by one, at index 2 by 2 and so on see
//http://stackoverflow.com/questions/31174840/how-to-rotate-an-array
//
for (int i = 1; i<n; i++){
int [] temp = new int [n];
for (int j = 0; j < n; j++) {
temp[(j + i) % n] = arr[i][j];
}
System.arraycopy(temp, 0, arr[i], 0, n);
arr[i]=temp;
}
System.out.println("\nPattern 2 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
}
}
You can achieve this by checking the modulo:
for (int i = 0; i < n; i++) {
int start = i * n;
for (int j = 0; j < n; j++) {
arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
}
}
I have an array:
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
I'm trying to split it into a two-dimensional array with x amount of chunks, where all of the chunks have an equal length (in my case, 2), then assign each value of the original array to a corresponding index within the array. It would then increment the index of the chunk number and reset the index iterating through the individual arrays hit the length of one.
Problem is, the code I wrote to perform all that isn't outputting anything:
public class Debug
{
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
private static void chunkArray(int chunkSize)
{
int chunkNumIndex = 0;
int chunkIndex = 0;
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++)
{
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
while(chunkNumIndex < numOfChunks)
{
if (chunkIndex == chunkSize)
{
chunkNumIndex++;
chunkIndex = 0;
}
}
}
for(int i = 0; i < chunkNumIndex; i++)
{
for(int j = 0; j < chunkIndex; j++)
{
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
System.out.println();
}
}
public static void main(String args[])
{
chunkArray(2);
}
}
Could anyone be of assistance in debugging my program?
The problem is that you have an unnecessary while(chunkNumIndex < numOfChunks) which makes no sense. The if statement is sufficient to iterate your variables correctly:
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
if (chunkIndex == chunkSize) {
chunkNumIndex++;
chunkIndex = 0;
}
}
Also, remember that the values of chunkNumIndex and chunkIndex are dynamic, so for the last for loops, use twoDimensionalArray.length and twoDimensionalArray[0].length instead:
for(int i = 0; i < twoDimensionalArray.length; i++) {
for(int j = 0; j < twoDimensionalArray[0].length; j++) {
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
}
You're making this unnecessarily hard, there is no need to keep counters for chunkIndex and chunkNumIndex, we can just div and mod i.
int numOfChunks = (array.length / chunkSize) + (array.length % chunkSize == 0 ? 0 : 1);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[i / chunkSize][i % chunkSize] = array[i];
}
Something like this should already do the job.
I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
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();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}
I want to print the contents of the second half of an array, or copy it to another new array.
I have this method:
public static void evaluateF3(int[] anArray) {
int[] array2 = new int[anArray.length/2];
for( int i = 0; i<array2.length; i++) {
for(int j= (anArray)/2; j<anArray.length;j++) {
array2[i]= anArray[j];
System.out.print(" "+ array2[i]);
}
}
}
However it prints the same number of times as the inside for loop, when I only want to print once. I've tried taking the statement outside of the for loop, but then it just says it cannot find 'i'. How do I solve this problem?
Why don't you put it outside the inner loop, but still inside the outer loop, then it should print out properly.
Btw: you got a compile error in your second loop. Either you meant to say j= anArray.length; or j = anArray.length/2. In either case you forgot the .length
I figured out your problem you dont need the second loop
public static void evaluateF3(int[] anArray) {
int[] array2 = new int[anArray.length / 2];
for (int i = 0; i < array2.length; i++) {
array2[i] = anArray[i + (array2.length)];
System.out.print(" " + array2[i]);
}
}
Let me know!
Maybe you're looking to do something like this?
public static void evaluateF3(int[] anArray) {
int[] array2 = new int[anArray.length/2];
for(int i = 0, j= array2.length; j<anArray.length;i++, j++) {
array2[i]= anArray[j];
System.out.print(" "+ array2[i]);
}
}
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8 };
evaluateF3(a); // 5 6 7 8
int[] a = { 0, 1, 1, 0, 0, 0, 2, 2 };
evaluateF3(a); // 0 0 2 2
You cannot divide an array int[] over 2: (anArray)/2
I believe an example of the code you're looking for is as follows:
public static void evaluateF3(int[] array1) {
int[] array2 = new int[array1.length / 2];
System.arraycopy(array1, array1.length / 2, array2, 0, array2.length);
for (int i = 0; i < array2.length; i++)
{
System.out.println(array2[i]);
}
}
I think(1) you want to copy the upper half of elements into a new array. Then you just need one for loop (if you want to do it with loops):
public static void evaluateF3(int[] anArray) {
// assuming that anArray.size() is even!!
int[] array2 = new int[anArray.length/2];
for(int i = 0; i < array2.length; i++) {
array2[i]= anArray[i + anArray.length/2];
System.out.print(" "+ array2[i]);
}
}
(1) Just read your comment to another answer, I think I got it right
for( int i = 0; i<array2.length; i++)
{
for(int j= (anArray.length)/2; j<anArray.length;j++)
{
array2[i]= anArray[j];
}
System.out.print(" "+ array2[i]);
}
That would print the value of each index in the array2. Do you want it to print once after both of the loops?