Fill 2D array square and print in specific patterns - java

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));
}
}

Related

Histogram based on int array and negative values

I've a question to you.
https://stackoverflow.com/questions/14975968/vertical-arrangement-with-asterisk#=
The code which you shared this post is very good. I've an exam tomorrow. May you tell me the solution.
I edited int array in this program.
It's {-1, 2, 5, 3} but program is not printing (-1) value in which int array.
I want to When the loop read this minus value, it cross new line and print "*" and print the minus value to its underline.
Can you tell me how can i do that in Java?
Thank you.
https://i.stack.imgur.com/ESsVE.jpg
public static void main(String[] args) throws IOException {
int[] a = new int[] {-1,3,-4,2,5};
int[] tmp = a.clone();
Arrays.sort(tmp);
int max = tmp[tmp.length-1];
int low = tmp[0];
int last =max;
if(low<0) {
last=max-low;
}
for (int i = 0; i < last+1; i++) {
for (int j = 0; j < a.length; j++) {
if (i == last ) {
System.out.print(a[j]);
} else if(i<max){
if (i < max - a[j])
System.out.print(" ");
else
System.out.print("*");
}
else {
if (i < max - a[j] )
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println();
}
}

java How do I print a reversed AND every other element in an array?

This is my first question, so sorry if I'm not clear
So I'm trying to write a void function printReverse that prints a reversed array and skips every other element in the process. This is what I have:
void printReverse(int[] array) {
for(int i = 0; i < array.length / 2; i+=2){
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
while(i < array.length){
println(array[i]);
i++;
}
}
}
Say that I had an array of {10, 20, 30, 40, 50, 60}, I'm trying to print out on different lines (println) 60 40 20
How would I do that with the code so far?
You can also start from the end of the array, it really easy to do this like that:
for(int i=array.length-1; i>=0; i=i-2)
System.out.println(array[i]);
notice that i=array.length-1 as if array.length is 3 for example, the last index will be 2. Also notice that i>=0 as i is initialize to the end of the array and 0 is the first index of the array.
Here you go:
int[] array = new int[] { 1, 2, 3, 4 };
int count = 0;
for (int i = array.length - 1; i >= 0; i--) {
if (count++ % 2 != 0) {
continue;
}
System.out.println(array[i]);
}
Besides having the system just print it, you could use a for loop to do this.
So,
for (int i = 6, i > array.length, i - 2)
{
System.out.println(array[i]);
}
Which would print out every other element in reverse order, given that there are 6 elements in the array. Of course, you could have a variable set to the length of the array, and plug in the variable instead of six, but this is just an example.
Hope this helps!
Check Image for Output Here you go in simple way,Thank you!!
import java.util.Arrays;
import java.util.Scanner;
class Demo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter total number of elemets: ");
int total = sc.nextInt();
int[]arr1 = new int[total];
int[]arr2 = new int[total];
System.out.print("Enter elemets: ");
for(int i = 0; i<total; i++)
{
arr1[i]= sc.nextInt();
}
System.out.print("Original Array: " +Arrays.toString(arr1));
System.out.println();
for(int a = 0 ; a< total; a++)
{
for(int j =total-a-1; j>=0; j--)
{
arr2[a]= arr1[j];
break;
}
}
System.out.print("Reversed Array: " +Arrays.toString(arr2));
}
}

Extracting a sequence from an array

I am writing code that reads an integer array in from a file, checks for an increasing sequence of numbers, and prints the length of the array as well as the sequence of numbers itself. The code I have written appears to correctly print the array, showing that is has found the array in the file, and count off the longest sequence of numbers, but it doesn't quite get the exact sequence right. Below is the code in its entirety and the output.
public static void main(String[] args) throws IOException {
File file = new File("input.txt");
Scanner s = null;
final int MAX_SIZE = 100;
int count = 0;
int[] tempArray = new int[MAX_SIZE];
try {
s = new Scanner(file);
int arrayAddress = 0;
System.out.println("File found!");
while (s.hasNextInt()) {
count++;
tempArray[arrayAddress] = s.nextInt();
arrayAddress++;
}
s.close();
}
catch (FileNotFoundException noFile) {
System.out.println("File not found.");
}
int[] inputArray = new int[count];
for (int i = 0; i < count; i++)
{
inputArray[i] = tempArray[i];
}
int sequence = 0;
int maxSequence = 0;
int sequenceEnd = 0;
for (int j = 0; j < count; j++) {
for (int k = j; k < count - 1; k++) {
if (inputArray[k + 1] == inputArray[k] + 1 ) {
sequence++;
sequenceEnd = k;
}
if (sequence > maxSequence) {
maxSequence = sequence;
sequence = 0;
}
}
}
int temp = 0;
System.out.println("The array is: " + Arrays.toString(inputArray));
System.out.println("The longest sequence of increasing numbers is " + maxSequence);
System.out.println("The sequence is as follows: ");
for (int i = sequenceEnd - maxSequence; i < sequenceEnd; i++) {
temp = inputArray[i];
System.out.println(temp);
}
}
The output for the code above on my sequence was as follows:
File found!
The array is: [7, 2, 13, 4, 5, 18, 11, 1, 20, 17, 15, 10, 19, 8, 16, 12, 6, 14, 9, 3]
The longest sequence of increasing numbers is 2
The sequence is as follows:
2
13
I really hope this isn't a minor oversight, but I can't seem to figure out where I have made an error. Thanks in advance if you have time to look over this and assist me.
There are two problems in your code:
(1) Finding the maximum length of the sequence
Your reset of the sequenc length
if (sequence > maxSequence) {
maxSequence = sequence;
sequence = 0;
}
should not be located within the inner loop. That is the one, where you are still counting the elements. You want to move it to the outer loop, i.e. from
for (int j = 0; j < count; j++) {
for (int k = j; k < count - 1; k++) {
//current location
}
}
for (int j = 0; j < count; j++) {
for (int k = j; k < count - 1; k++) {
}
//assumingly desired location
}
(2) Print sequence
The offset of your print-loop is off by one element and should be
for (int i = sequenceEnd - maxSequence1; i < sequenceEnd; i++) {
temp = inputArray[i-1];
System.out.println(temp);
}
Once maxSequence contains the correct amount of elements (i.e. not 2 as it is currently the case), it will print the entire sequence.

How I can print largest sum in this Program?

package Message;
public class Example_R {
public static void main (String args[])
int n=1;
int input[]={1, 2, 1, 3, 4};
for (int j=0; j<=4; j++) {
int Add = 0;
for (int i=0; i<=4; i++) {
if (input[j] !=input[i]) {
Add+=input[i];
}
}
System.out.println(Add);
}
}
}
Output of This program is: 9 9 9 8 7 sum of all the other elements in the array that are not equal to the element.
Now I want to extend the program so I can print the Largest sum of any of it's element, (In this case 9 is the largest sum.) Do you have any suggestions? For this assignment I am restricted from using additional array, hashmap etc. not allowed. Arrays.sort(..)
Hint: use a variable that is holding "the largest sum reached so far". You will update it very time you compute a new sum.
You will need to find "how and when do I initialize this variable ?" and "how do I update it ?"
You probably want to create a separate method that you pass your "input[]" array to (left as an exercise). However when considering problems like this, first just consider how you would do it in english (or whatever your native language is). Write down that strategy (an "algorithm") and then implement that in Java.
public class Example_R {
public static void main(String args[]) {
int input[] = { 1, 2, 1, 3, 4 };
int largestSum = 0;
int currentSum;
for (int j = 0; j < input.length; j++) {
currentSum = 0;
for (int i = 0; i < input.length; i++) {
if (input[j] != input[i]) {
currentSum += input[i];
}
}
System.out.println("Sum of all values not equal to " + input[j]
+ " is: " + currentSum);
if (j == 0) {
largestSum = currentSum;
} else {
if (largestSum < currentSum) {
largestSum = currentSum;
}
}
}
System.out.println("The largest overall sum was " + largestSum);
}
}
You'll need a temporary variable to save the current highest number.
int temp = intArray[0]
for(int i : intArray)
{
if(i > temp)
temp = i;
}
Try this:
int n = 1,sum=0;
int[] input = { 1, 2, 1, 3, 4 };
for (int j = 0; j <= 4; j++){
int Add = 0;
for (int i = 0; i <= 4; i++){
if (input[j] != input[i])
Add += input[i];
}
if (sum < Add)
sum = Add;
}
After completing the second loop every time,the "sum" was updated if it is less than the current "add" value.
You can use variables of type Comparable and use the compareTo() method.
one.compareTo(two) will return > 0 if one > two
one.compareTo(two) will return < 0 if one < two
one.compareTo(two) will return 0 if one and two are equal
Go through the array, compare the current index with the previous index, and update a variable that holds the currentLargest value.

Adding the columns of a jagged 2D array

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]);
}
}
}
}

Categories

Resources