I start learning programming about 4 days ago by myself and iam a lil bit stuck with 2d arrays. I try to challenging myself with tasks, like get from 2d array column with most zeros or atleast just count zeros, so far i get this far
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
for(j=0;j<a[0].length;j++) {
for(i=0;i<a.length;i++) {
if(a[i][j] >-1 || a[i][j]<1) {
s++;
System.out.println(s +"\t");
s = 0;
}
}
}
}
}
Can somebody explain me why result is always 1 and why it counts columns and rows in one row?
Suppose the condition enters into if(a[i][j] >-1 || a[i][j]<1) then you increase s by 1 then print it which gives 1 then you reassign it to s=0 so it gives same 1 each time.So remove the s=0 and place the printing line after end of loop
public class b {
public static void main(String[] args) {
int a[][] = new int [5][5];
int i,j;
int s = 0;
for(i= 0;i<a.length; i++)
for(j = 0; j<a[i].length; j++){
a[i][j] = (int)(Math.random()*10);
}
for(i=0;i<a.length;i++){
for(j=0;j<a[i].length;j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
for(j=0;j<a[0].length;j++){
for(i=0;i<a.length;i++)
if(a[i][j] >-1 && a[i][j]<1){
s++;
}
System.out.println("Zero in column no. "+j+" is "+s +"\t");
s=0;
}
}
}
Demo
Result will be 1 because you're re-assigning 0 to s everytime. But the issue is not only that.
Firstly your condition is using wrong indices. Instead of a[i][j] you should use a[j][i] as you're traversing column-wise. Secondly:
if(a[j][i] >-1 || a[j][i]<1){
can be simply written as:
if(a[j][i] == 0) {
So the structure is the outer for loop will iterate over each column number. And for each column number, inner for loop will find count of 0. You've to maintain a max variable outside both the loops, to track the current max. Also, you've to use another variable inside the outer for loop to store the count for current column.
Everytime the inner for loop ends, check if current column count is greater than max. If yes, reset max.
int max = 0;
for(j=0;j<a[0].length;j++){
int currentColumnCount = 0;
for(i=0;i<a.length;i++) {
if(a[j][i] == 0) {
currentColumnCount++;
}
}
if (currentColumnCount > max) {
max = currentColumnCount;
}
}
Related
Im trying to take count of the unique prime numbers,im able to print the unique prime number but unable to take count , also im not suppose to use an extra array ?
my logic after finding the prime number went wrong ! can anyone help me with this ?
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Please enter your array limit");
int limit=sc.nextInt();
int array[]=new int[limit];
System.out.println("please enter your array elements ");
for(int i=0;i<limit;i++) {
array[i]=sc.nextInt();
}
int flag=0;
for(int i=0;i<limit;i++) {
int counter=0;
for (int j=1;j<=array[i];j++) {
if(array[i]%j==0) {
counter++;
}
}
if(counter==2) {
System.out.println(array[i]);
for(int k=i;k<limit;k++) {
if(array[i]!=array[k]) {
flag++;
}
}
}
}
System.out.println("Count of unique prime number: "+flag);
sc.close();
}
}
output:
Please enter your array limit
6
please enter your array elements
1 2 3 4 5 6
2
3
5
Count of unique prime number: 8
//expected output 3
Update: if you need only unique values, you might want to insert them into a Set and in the end return the size of the Set, like this:
int flag = 0;
Set<Integer> primeNumbers = new HashSet<>();
for (int i = 0; i < limit; i++) {
int counter = 0;
for (int j = 1; j <= array[i]; j++) {
if (array[i] % j == 0) {
counter++;
}
}
if (counter == 2) {
primeNumbers.add(array[i]);
System.out.println(array[i]);
}
}
In the end just return primeNumbers.size(). This works because a Set data-structure does not allow duplicate values.
There is no need to do a second loop after encountering a prime number (i.e counter == 2). Just change the code after that if condition with:
if (counter == 2) {
System.out.println(array[i]);
flag++;
}
In the end just print/return the flag. Happy coding! =)
I'm pretty new to Java, just started learning it. I've got an array of numbers, with array length origArraySize:
29.50 10.80 16.40 87.80 12.20 63.70 13.90 25.00 77.40 97.40
I'm trying to arrange them in this format:
29.50
10.80 16.40
87.80 12.20 63.70
13.90 25.00 77.40 97.40
While I've seen similar half Pyramid questions, i just can't seem to figure out how to implement an array to print the numbers. Here's what I got so far, just a method of class rn:
public String toString() {
String t = "";
for (int i = 0; i < this.origArraySize; i++) {
t += String.format("%8.2f", array[i]);
for (int j = 0; j < i; j++) {
System.out.println(t + "\n");
}
}
}
I know it includes nested for loops but I just can't seem to get it. The method toString() has to return String value, and I'm not sure how to implement that at the end either, but for now I tried with t.
You do not want an inner loop, you just need a couple of counters
double arr[] = {29.50,10.80,16.40,87.80,12.20,63.70,13.90,25.00,77.40,97.40};
int loop = 0;
int printAtNum = 0;
for (double d : arr) {
System.out.printf("%8.2f", d); // always print
if (loop == printAtNum) {
System.out.println(); // only print if loop is equal
// to incremented counter
loop = 0; // reset
printAtNum++; // increment
} else {
loop++;
}
}
output
29.50
10.80 16.40
87.80 12.20 63.70
13.90 25.00 77.40 97.40
You can use two nested for loops. The internal action is to print and increment a single value:
public static void main(String[] args) {
double[] arr = {29.50,10.80,16.40,87.80,12.20,63.70,13.90,25.00,77.40,97.40};
printHalfPyramid(arr);
}
public static void printHalfPyramid(double[] arr) {
int i = 0; // counter, index of an element in an array
for (int row = 1; row < Integer.MAX_VALUE; row++) {
for (int el = 0; el < row; el++) {
// print a number and increment a counter
System.out.print(arr[i++] + " ");
// if the last element
if (i == arr.length) return;
}
// line break, next row
System.out.println();
}
}
Output:
29.5
10.8 16.4
87.8 12.2 63.7
13.9 25.0 77.4 97.4
I'm having trouble in getting the rest of the numbers after I sum up the first 3 elements. This is the question that it asks me: "Write a method that takes an array. return true if the sum of the first three elements in the array is less than the sum of the rest of the elements of the array."
Therefore 5 5 5 5 2 2 should be false. Since the first 3 numbers sum are greater than the sum of 5 2 2. My program returns true for this question and I would appreciate any help.
public static boolean sumThree(int [] myArray)
{
int sum = 0;
for(int i = 0; i < myArray.length; i++)
{
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if(sum > sumof3E)
{
return true;
}
else if(sumof3E < sum)
{
return false;
}
else
{
return false;
}
}
You shouldn't include the first three elements of the array. Those have to be exclusive of the summation.
Change the for loop control variable to this:
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
Also, you should remove the else if block from your code, because it's redundant (the first if statement checks for that condition):
else if(sumof3E < sum)
{
return false;
}
Alternatively, with the help of java 8 features, you can shorten your code into one line:
public static boolean sumThree(int [] myArray){
return Arrays.stream(myArray).limit(3).sum() < Arrays.stream(myArray).skip(3).sum();
}
note - with the alternative solution you won't get IndexOutOfBoundsException even if the array being passed in is empty.
There are two issues in your code:
1) You don't verify that the Array even has 3 elements before you index into it, which will potentially cause errors.
2) You're summing the entire array and comparing it to the sum of the first three elements... in your loop try initializing i = 3 in the loop initialization (assuming the array has at least 4 elements)
Pseudo code:
public static boolean sumThree(int [] myArray)
{
if (myArray.length < 4) { return false; }
var first = myArray[0] + myArray[1] + myArray[2];
var rest = 0;
for(int i = 3; i<myArray.length; i++) {
rest += myArray[i];
}
return first < rest;
}
the sum loop need to be altered to start from index 2 and else if is not required.
public static boolean sumThree(int[] myArray) {
int sum = 0;
for (int i = 3; i < myArray.length; i++) {
sum += myArray[i];
}
int sumof3E = myArray[0] + myArray[1] + myArray[2];
if (sum > sumof3E) {
return true;
}
else {
return false;
}
}
for clarity make a two loop then use the conditional operator or known as ternary operator for using thee if..else easily
int sum1=0;
int sum2=0;
for(int i=0;i<=2;++i)
{
sum1+=myArray[i];
}
for(int i=3;i<myArray.length;++i)
{
sum2+=myArray[i];
}
boolean myBool = (sum1>sum2)?false:true;
return myBool;
There is no need to keep going through the whole array at a time when first sum becomes less than sum of rest:
int sumf3 =0;
int sumRest=0;
for (int i = 0; i < myArray.length; i++)
{
if (i < 3){
sumf3 += myArray[i];
} else {
sumRest += myArray[i];
}
if(sumf3 < sumRest ){
return true;
}
}
return false;
P.S. and no need to check size of array before loop as well.
I'm relatively new to java. I'm trying to find if numbers from 0 - 4 are stored
somewhere in an array of size 5. The array is populated by the user entering integers between 0-4. I have successfully managed to get it to confirm that the first number entered by the user is in the array however, the numbers after that not appearing.
So for example: If the user enters the numbers 2,2,2,1,3 I will get only 2 appears in the array as a result.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
break;
}
else
{
System.out.println(currentNum + " doesn't appear in the array");
break;
}
}
}
}
To resolve your problem you should simply remove the have used in the else part of the array.
Consider a case like this
ex. 2 1 4 3
when checking for i=1 it will first compare the value with 2 so it will come out of the loop.
public static void checkEachNumber(int[] array)
{
int currentNum = 0;
for(int i = 0; i < array.length; i++)
{
int flag=0;
for(int j = 0; j < array.length; j++)
{
currentNum = i;
if(currentNum == array[j])
{
System.out.println(currentNum + " appears in the array");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("currentNum+"Doesn't appear in array");
}
}
}
When you execute a break statement, the loop stops running completely. In general, the way to scan for a match is going to look like this:
found_match = no
for (... in ...) {
if (match) {
found_match = yes
break
}
}
if (found_match) {
do_found_match_stuff();
}
So my code is having a problem. Here's what I want to do: have one array have the original set of numbers (up to 10 numbers) and then copy and paste those numbers onto the second array. And then afterwards, the second area lists those numbers from the first array numerically (going from the lowest number to the highest).
The problem is... my second output is giving me a good output with the lowest numbers going to the highest numbers, however, at the same time, I'm getting a long list of repeated numbers and a ton of zeros if I stop my code with the -9000 input. Can anyone tell me what the problem is and how to fix it? I don't want to sort this second array with the Array.sort() option, by the way. No importing anything but the scanner:
public static void main(String[] args) {
System.out.println("Input up to '10' numbers for current array: ");
int[] array1 = new int[10];
int i;
Scanner scan = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
} else {
array1[i] = input;
}
}
System.out.println("\n" + "Original Array: ");
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + ": " + array1[j]);
}
System.out.println("\n" + "Organized Array: ");
int[] array2 = new int[i];
for (i = 0; i < array1[i]; i++) {
System.out.println(+array1[i]);
for (int j = 0; j < i; j++) {
int temp;
boolean numerical = false;
while (numerical == false) {
numerical = true;
for (i = 0; i < array1.length - 1; i++) {
if (array2[i] > array2[i + 1]) {
temp = array2[i + 1];
array2[i + 1] = array2[i];
array2[i] = temp;
numerical = false;
}
}
}
}
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
}
}
You have several issues that you need to fix to make your program run:
You have forgotten to copy array1 into array2:
The output that you think is coming from sorting array2 is actually from the process of sorting.
int[] array2 = new int[i];
for (int j = 0; j < i; j++) {
array2[j] = array1[j];
}
You placed the output of sorted array inside the loop that does sorting:
Check the level of curly braces, and move the output loop to after the sorting loop
for (i = 0; i < array2.length; i++) {
System.out.println(array2[i]);
}
Your sorting algorithm has an extra loop:
Having the outermost loop makes no sense: your bubblesort algorithm works perfectly without it, so you should remove the loop, and move its body up by one level of nesting:
for (i = 0; i < array1[i]; i++) { // Remove the loop
... // <<== Keep the body
}
Your innermost loop reuses i incorrectly:
Replace loop variable i with another variable, e.g. m
for (int m = 0 ; m < array2.length - 1; m++) {
if (array2[m] > array2[m + 1]) {
temp = array2[m + 1];
array2[m + 1] = array2[m];
array2[m] = temp;
numerical = false;
}
}
Demo.
in your for loop you set i limit to array1[i] value not to array lenght, surely it is wrong.
you are reusing the same index i, inside the other loops of the outer big 'for' loop, so the i value will be messed up by inner loops
you never copied the array1 values to array2