Related
So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}
I want to break a one-dimensional array in rows.
Array dimension 50. I need to output the array to the console with 10 elements per line. (lang Java 1.8) Thanks!
public void print() {
for (int i = 0; i < arr.length; i++) {
if (i<=9) {
System.out.print(arr[i] + " ");
}else {
System.out.print("\r");
}
}
}
Sample output
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
etc....
You can see it from 2 differents point of view
Each 10 numbers, print a new line : when the index ends with a 9 you reach ten elements so you print a new line println()
public void print() {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
if (i % 10 == 9) {
System.out.println();
}
}
}
Print enough number of line and on each one : print 10 elements
public void print() {
for (int i = 0; i < arr.length / 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.print(arr[i * 10 + j] + " ");
}
System.out.println();
}
}
Code for any number of elements per line:
public void print(int elementsPerLine) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i % elementsPerLine == 0 && i > 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
Use the following code,
public static void printResult(int[][] result)
{
for(int i=0; i<5; i++)
{
for(int j=0; j<10; j++)
{
System.out.print(result[i][j] + ", ");
}
System.out.println();
}
}
public static int[][] modifyArray( int[] singleArray )
{
int columns = 10;
int rows = singleArray.length/10;
int[][] result = new int[rows][columns];
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)
{
result[i][j] = singleArray[columns*i + j];
}
}
return result;
}
public static void main(String[] args)
{
int[] singleArray = {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,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
int[][] result = modifyArray( singleArray);
printResult( result );
}
You must use the modulo operator
https://en.wikipedia.org/wiki/Modulo_operation
public void print() {
for (int i = 0; i < arr.length; i++) {
if (i%10 == 0) {
System.out.print("\r");
}else {
System.out.print(arr[i] + " ");
}
}
}
Maybe you could write something like
if (i % 10 == 0)
System.out.print("\r");
}
System.out.print(arr[i] + " ");
Take slices of 10 items into a new array each time and print that array:
int count = 10;
int iterations = (arr.length / count) + ((arr.length % count) > 0 ? 1 : 0);
for (int i = 1; i <= iterations; i++) {
int[] slice = new int[count];
System.arraycopy(arr, (i - 1) * count, slice, 0, i == iterations ? (array.length % count) : count);
System.out.println(Arrays.toString(slice));
}
The above code works for any value of count.
Take a look at a code down below:
public class PrintEach10thElements {
/**
* #param args the command line arguments
*/
static List<Integer> arrays = new ArrayList<>();
public static void main(String[] args) {
//create 50 elements in an array
for (int i = 0; i <= 49; i++) {
arrays.add(i);
}
for (int g = 0; g < arrays.size(); g++) {
if ( arrays.get(g) % 10 != 0) {
System.out.print(arrays.get(g) + " ");
} else {
System.out.println();
System.out.print(arrays.get(g) + " ");
}
}
}
}
If you don't mind using a Guava library, you can also do this
List<Integer> myList = Arrays.asList(myArray);
System.out.println(Lists.partition(myList, 10).stream()
.map(subList -> subList.stream()
.map( Object::toString )
.collect(Collectors.joining(" ")))
.collect(Collectors.joining("\n")));
I am working on a problem where I've to print the largest sum among all the hourglasses in the array. You can find the details about the problem here-
What I tried:
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for (int arr_i = 0; arr_i < 6; arr_i++) {
for (int arr_j = 0; arr_j < 6; arr_j++) {
arr[arr_i][arr_j] = in.nextInt();
}
}
int sum = 0;
int tmp_sum = 0;
for (int arr_i = 0; arr_i < 4; arr_i++) {
for (int arr_j = 0; arr_j < 4; arr_j++) {
if (arr[arr_i][arr_j] > 0) {
sum = sum + (arr[arr_i][arr_j]) + (arr[arr_i][arr_j + 1]) + (arr[arr_i][arr_j + 2]);
sum = sum + (arr[arr_i + 1][arr_j + 1]);
sum = sum + (arr[arr_i + 2][arr_j]) + (arr[arr_i + 2][arr_j + 1]) + (arr[arr_i + 2][arr_j + 2]);
if (tmp_sum < sum) {
tmp_sum = sum;
}
sum = 0;
}
}
}
System.out.println(tmp_sum);
}
}
Input:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 9 2 -4 -4 0
0 0 0 -2 0 0
0 0 -1 -2 -4 0
Output:
12
Expected Output:
13
Screenshot:
I don't know where I'm doing wrong. I cannot understand why the expected output is 13. According to the description given in the problem it should be 10. Is this a wrong question or my understanding about this is wrong?
Remove the if (arr[arr_i][arr_j] > 0) statement. It prevents finding the answer at row 1, column 0, because that cell is 0.
Comments for other improvements to your code:
What if the best hourglass sum is -4? You should initialize tmp_sum to Integer.MIN_VALUE. And name it maxSum, to better describe it's purpose.
You shouldn't define sum outside the loop. Declare it when it is first assigned, then you don't have to reset it to 0 afterwards.
Your iterators should be just i and j. Those are standard names for integer iterators, and keeps code ... cleaner.
If you prefer longer names, use row and col, since that is what they represent.
You don't need parenthesis around the array lookups.
For clarity, I formatted the code below to show the hourglass shape in the array lookups.
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int sum = arr[i ][j] + arr[i ][j + 1] + arr[i ][j + 2]
+ arr[i + 1][j + 1]
+ arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (maxSum < sum) {
maxSum = sum;
}
}
}
System.out.println(maxSum);
This was my solution. I wrapped an if statement around the code that calculates the sum, that makes sure we don't go out of bounds.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
int max = Integer.MIN_VALUE;
int tempMax = 0;
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
if (i + 2 < 6 && j + 2 < 6) {
tempMax += arr[i][j] + arr[i][j + 1] + arr[i][j + 2];
tempMax += arr[i + 1][j + 1];
tempMax += arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (max < tempMax) {
max = tempMax;
}
tempMax = 0;
}
}
}
System.out.println(max);
}
Here's the simple and easy to understand C# equivalent code for your hourglass problem.
class Class1
{
static int[][] CreateHourGlassForIndex(int p, int q, int[][] arr)
{
int[][] hourGlass = new int[3][];
int x = 0, y = 0;
for (int i = p; i <= p + 2; i++)
{
hourGlass[x] = new int[3];
int[] temp = new int[3];
int k = 0;
for (int j = q; j <= q + 2; j++)
{
temp[k] = arr[i][j];
k++;
}
hourGlass[x] = temp;
x++;
}
return hourGlass;
}
static int findSumOfEachHourGlass(int[][] arr)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int j = 0; j < arr.Length; j++)
{
if (!((i == 1 && j == 0) || (i == 1 && j == 2)))
sum += arr[i][j];
}
}
return sum;
}
static void Main(string[] args)
{
int[][] arr = new int[6][];
for (int arr_i = 0; arr_i < 6; arr_i++)
{
string[] arr_temp = Console.ReadLine().Split(' ');
arr[arr_i] = Array.ConvertAll(arr_temp, Int32.Parse);
}
int[] sum = new int[16];
int k = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
int[][] hourGlass = CreateHourGlassForIndex(i, j, arr);
sum[k] = findSumOfEachHourGlass(hourGlass);
k++;
}
}
//max in sum array
Console.WriteLine(sum.Max());
}
}
Happy Coding.
Thanks,
Ankit Bajpai
You can try this code:
I think this will be easy to understand for beginners.
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int arr_i=0; arr_i < 6; arr_i++){
for(int arr_j=0; arr_j < 6; arr_j++){
arr[arr_i][arr_j] = in.nextInt();
}
}
int sum = 0;
int sum2 = 0;
int sum3 = 0;
int x = 0;
int max = Integer.MIN_VALUE;
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 3; k++){
sum += arr[i][j+k]; //top elements of hour glass
sum2 += arr[i+2][j+k]; //bottom elements of hour glass
sum3 = arr[i+1][j+1]; //middle elements of hour glass
x = sum + sum2 + sum3; //add all elements of hour glass
}
if(max < x){
max = x;
}
sum = 0;
sum2 = 0;
sum3 = 0;
x = 0;
}
}
System.out.println(max);
}
}
Here is another easy option, hope it helps:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a[][] = new int[6][6];
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
a[i][j] = in.nextInt();
}
}
int hg = Integer.MIN_VALUE, sum;
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
sum = 0;
sum = sum + a[i][j] + a[i][j+1] + a[i][j+2];
sum = sum + a[i+1][j+1];
sum = sum + a[i+2][j] + a[i+2][j+1] + a[i+2][j+2];
if(sum>hg)
hg = sum;
}
}
System.out.println(hg);
in.close();
}
}
there is another opetion in case of -(minus) and zero output we can use shorted ser Treeset for the same . below is the sameple code
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for(int i=0; i < 6; i++){
for(int j=0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
int sum=0;int output=0;
Set<Integer> set=new TreeSet<Integer>();
for(int k=0;k<4;k++ )
{
for(int y=0;y<4;y++)
{
sum=arr[k][y]+arr[k][y+1]+arr[k][y+2]+arr[k+1][y+1]+arr[k+2][y]+arr[k+2][y+1]+arr[k+2][y+2]; set.add(sum);
}
}
int p=0;
for(int u:set)
{
p++;
if(p==set.size())
output=u;
}
System.out.println(output);
}
}
Solved in PHP, may be helpful.
<?php
$handle = fopen ("php://stdin","r");
$input = [];
while(!feof($handle))
{
$temp = fgets($handle);
$input[] = explode(" ",$temp);
}
$maxSum = PHP_INT_MIN;
for($i=0; $i<4; $i++)
{
for($j=0; $j<4; $j++)
{
$sum = $input[$i][$j] + $input[$i][$j + 1] + $input[$i][$j + 2]
+ $input[$i + 1][$j + 1] +
$input[$i + 2][$j] + $input[$i + 2][$j + 1] + $input[$i + 2][$j + 2];
if($sum > $maxSum)
{
$maxSum = $sum;
}
}
}
echo $maxSum;
?>
Passes all test cases
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int rowSize = 6;
int colSize = 6;
int[][] array = new int[rowSize][colSize];
for(int row = 0; row < rowSize; row++) {
for(int col = 0; col < colSize; col++) {
array[row][col] = read.nextInt();
}
}
read.close();
int max = Integer.MIN_VALUE;
for(int row = 0; row < 4; row++) {
for(int col = 0; col < 4; col++) {
int sum = calculateHourglassSum(array, row, col);
if(sum > max) {
max = sum;
}
}
}
System.out.println(max);
}
private static int calculateHourglassSum(int[][] array, int rowIndex, int colIndex) {
int sum = 0;
for(int row = rowIndex; row < rowIndex + 3; row++) {
for(int col = colIndex; col < colIndex + 3; col++) {
if(row == rowIndex + 1 && col != colIndex + 1) {
continue;
}
sum += array[row][col];
}
}
return sum;
}
}
function galssSum(array) {
let maxGlass = 0;
if (array[0].length == 3) {
maxGlass = 1;
} else if (array[0].length > 3) {
maxGlass = array.length - 2;
}
let maxValue = -100000;
for (let i = 0; i < maxGlass; i++) {
for (let j = 0; j < maxGlass; j++) {
let a = array[i][j] + array[i][j + 1] + array[i][j + 2];
let b = array[i + 1][j + 1];
let c = array[i + 2][j] + array[i + 2][j + 1] + array[i + 2][j + 2];
let sum = a + b + c;
if (maxValue<sum) {
maxValue = sum;
}
}
}
return maxValue;
}
console.log(galssSum([[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 2, 4, 4, 0], [0, 0, 0, 2, 0, 0], [0, 0, 1, 2, 4, 0]]));
int hourglassSum(vector<vector<int>> vec) {
int res = 0;
int size = ((vec[0].size())-2) * ((vec.size())-2);
//cout<<size<<endl;
vector<int> res_vec(size);
int j = 0;
int itr =0 ;
int cnt = 0;
int mid = 0;
int l =0;
while((l+2) < vec.size())
{
while((j+2) < vec.size())
{
for(int i =j ;i<j+3; i+=2)
{
//cout<<i<<" :";
for(int k=l;k<l+3;k++)
{
//cout<<k<<" ";
res_vec[itr] += vec[i][k];
}
//cout<<endl;
}
res_vec[itr] += vec[j+1][l+1];
//cout<<endl;
itr++;
j++;
}
l++;
j=0;
}
int max=res_vec[0];
for(int i =1;i<res_vec.size();i++)
{
if(max < res_vec[i])
{
max = res_vec[i];
}
//cout<<res_vec[i]<< " ";
}
res = max;
//cout<<endl;
return res;
}
// Complete the hourglassSum function below.
static int hourglassSum(int[][] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length - 2; i++) {
for (int j = 0; j < arr.length - 2; j++) {
int hourGlassSum = (arr[i][j] + arr[i][j + 1] + arr[i][j + 2])
+ (arr[i + 1][j + 1])
+ (arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2]);
max = Math.max(hourGlassSum,max);
}
}
return max;
}
public static int hourglassSum(List<List<Integer>> arr) {
// Write your code here
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int sum = arr.get(i).get(j) +arr.get(i).get(j+1) +
arr.get(i).get(j+2)+arr.get(i+1).get(j+1)+
arr.get(i+2).get(j)+arr.get(i+2).get(j+1)+arr.get(i+2).get(j+2);
if (maxSum < sum) {
maxSum = sum;
}
}
}
return maxSum;
}
}
Iterative way,Passing all test cases in hackerank web
public static int hourglassSum(List<List<Integer>> arr) {
// Write your code here
int rowsCount=arr.size();
int colCount=arr.get(0).size();
Integer max=Integer.MIN_VALUE;
Integer subSum=0;
for(int r=0; (r+3)<=rowsCount; r++)
{
for(int c=0; (c+3)<=colCount; c++)
{
subSum= hourglassSubSum(arr,r,c);
System.out.println("r,c,subSum "+r+" "+c+" "+" "+subSum);
if(subSum>max)
{
max=subSum;
}
}
}
return max;
}
public static int hourglassSubSum(List<List<Integer>> hourglassArray,
int rowIndex,int colIndex) {
// Write your code here
Integer subSum=0;
for(int i=rowIndex;i<(rowIndex+3);i++)
{
for(int j=colIndex;j<(colIndex+3);j++)
{
if(i==(rowIndex+1) && (j==colIndex || j==colIndex+2))
{
continue;
}
subSum=subSum+hourglassArray.get(i).get(j);
}
}
return subSum;
}
Solution for actual "2D Array - DS" challenge from HackerRank https://www.hackerrank.com/challenges/2d-array
public static int hourglassSum(List<List<Integer>> arr) {
int maxSum = Integer.MIN_VALUE;
for (int col=0; col <= 3; col++) {
for (int row=0; row <= 3; row++) {
int sum = calcHourglass(arr, col, row);
maxSum = Math.max(sum, maxSum);
}
}
return maxSum;
}
private static int calcHourglass(List<List<Integer>> arr, int col, int row) {
int sum = 0;
for (int i=0; i < 3; i++) {
sum += arr.get(row).get(col+i); // the top of the hourglass
sum += arr.get(row+2).get(col+i); // the bottom of the hourglass
}
sum += arr.get(row+1).get(col+1); // the center
return sum;
}
import java.io.*;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int low = -9,high = 5;
int lh = low * high;
int sum = 0, i, j;
int max = 0;
int a[][] = new int[6][6];
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
a[i][j] = in.nextInt();
}
}
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
sum = (a[i][j] + a[i][j+1] + a[i][j+2]);
sum = sum + a[i+1][j+1];
sum = sum + (a[i+2][j] + a[i+2][j+1] + a[i+2][j+2]);
if (sum > lh) lh = sum;
}
}
System.out.print(lh);
}
}
Here you go..
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a[][] = new int[6][6];
int max = 0;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
a[i][j] = in.nextInt();
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int sum = a[i][j] + a[i][j + 1] + a[i][j + 2] + a[i + 1][j + 1]
+ a[i + 2][j] + a[i + 2][j + 1] + a[i + 2][j + 2];
if (sum > max || (i == 0 && j == 0)) {
max = sum;
}
}
}
System.out.println(max);
}
I'm having some trouble in a couple of areas here. First, when the array is printed to screen, the "P" is placed at [0][0] - which is OK, but it is surrounded by 'null' for any other cell. I'd like it to be filled with dashes " - ". I'm also needing to code in an infinite loop that asks the user to input either 'up', 'down', 'left', 'right' or 'exit'. Does this infinite loop go into the "Driver" class, or the "World" class, and would a switch statement work for this?
Second - the rows and columns are not being summed and displayed. The "World" class is:
import java.util.*;
public class World
{
private static final String P = "P";
private String[][] array;
public World()
{
Scanner input = new Scanner(System.in);
System.out.println("Enter number of row: ");
int crow = input.nextInt();
System.out.println("Enter number of columns: ");
int ccol = input.nextInt();
array = new String[crow][ccol];
array[0][0]=P;
}
public void displayWorld()
{
System.out.println();
for(int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
System.out.print(array[i][j] + " - ");
}
System.out.println();
}
}
public void moveUp()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i - 1][j] = P;
}
return;
}
}
}
}
public void moveDown()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i + 1][j] = P;
}
return;
}
}
}
}
public void moveLeft()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i][j - 1] = P;
}
return;
}
}
}
}
public void moveRight()
{
for(int i= 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if ((array[i][j]) == " - ")
{
if (i < array.length - 1)
{
array[i][j] = " - ";
array[i][j + 1] = P;
}
return;
}
}
}
}
}
The "Driver" class is:
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)
{
World world=new World();
world.moveUp();
world.moveDown();
world.moveLeft();
world.moveRight();
world.displayWorld();
}
}
You need to intialize every element in the array. Add this to the end of the World constructor:
for(int i=0;i<crow;i++){
for(int j=0;j<ccol;j++){
array[crow][ccol]="-";
}
}
You will need to add the infinite loop asking for input in the Driver class. In the infinite loop you need to:
Get input
Use switch statement to detect left, right, etc
Driver.java:
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
World world = new World();
Scanner s = new Scanner(System.in);
while (true) {
String input = s.nextLine();
switch (input) {
case "up":
world.moveUp();
case "down":
world.moveDown();
case "left":
world.moveLeft();
case "right":
world.moveRight();
}
}
s.close();
}
}
Alright, so I tried implementing the bubble sort algorithm into my code, but now my output for the second array (in my code) is giving me a ton of zeros. Can anybody tell me what is wrong with my code and how I can fix it so the zeros are removed and the only thing that remains in the output for my second array are the fixed numerically?
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]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
scan.close();
}
}
}
Copy your array1 to an array2 of the correct length before sorting, something like
for (i = 0; i < 10; i++) {
System.out.println("Input a number for " + (i + 1) + ": ");
int input = scan.nextInt();
if (input == -9000) {
break;
}
array1[i] = input;
}
int[] array2 = Arrays.copyOfRange(array1, 0, i);
System.out.println("Before sorting: " + Arrays.toString(array2));
Arrays.sort(array2); // <-- How I would sort.
System.out.println("After sorting: " + Arrays.toString(array2));
The reason this is necessary is because i might not be 10 in which case your array contains 0(s) to fill the other positions.
Is it possible to move all my numbers from Array 1 to Array 2 using a for-loop?
Yes. You could implement a copyOfRange function with a for loop,
private static int[] copyOfRange(int[] arr, int start, int end) {
int pos = 0;
int[] out = new int[end - start];
for (int i = start; i < end; i++) {
out[pos] = arr[i];
pos++;
}
return out;
}
the built-in version is almost certainly better.
1) You are printing the array multiple times, I think you might be giving 0 as input and thats the reason you are seeing 0's everywhere.
2) You have created array2 which is not necessary.
Move the printing logic out of for loop as in the below snippet. Otherwise your logic looks fine except fot the wrong looping of print statement.
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]);
}
int[] array2 = new int[i];
System.out.println("\n" + "Organized Array: ");
for (int j = 0; j < i; j++) {
int temp;
boolean organized = false;
while (organized == false) {
organized = true;
for (i = 0; i < array1.length - 1; i++) {
if (array1[i] > array1[i + 1]) {
temp = array1[i + 1];
array1[i + 1] = array1[i];
array1[i] = temp;
organized = false;
}
}
}
scan.close();
}
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
}