java fill 2D array with specific method - java

I have an 2D array(matrix) and a Integer n.n is full square
for example if n equals 16 fill matrix like this.
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
what can I do?

public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the dimension of the matrix : ");
int dimension = Integer.parseInt(br.readLine());
System.out.print("Enter the number of elements : ");
int n = Integer.parseInt(br.readLine()); // total number of elements to be filled
n = n/dimension; // Get the number of rows and columns
if(n % dimension != 0){
// Not a Square matrix
}
int circularArray[][] = new int[n][n];
int k = 1, c1 = 0, c2 = n - 1, r1 = 0, r2 = n - 1;
while (k <= n * n) {
for (int i = c1; i <= c2; i++) {
circularArray[r1][i] = k++;
}
for (int j = r1 + 1; j <= r2; j++) {
circularArray[j][c2] = k++;
}
for (int i = c2 - 1; i >= c1; i--) {
circularArray[r2][i] = k++;
}
for (int j = r2 - 1; j >= r1 + 1; j--) {
circularArray[j][c1] = k++;
}
c1++;
c2--;
r1++;
r2--;
}
/* Printing the Circular matrix */
System.out.println("The Circular Matrix is:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(circularArray[i][j] + "\t");
}
System.out.println();
}
}

Here is a tiny example how this could look like.
What is actually happening is written as comments.
public class TestArray {
// A simple enum for each direction
public enum Mode {
right, down, left, up;
}
public static void main(String[] args) {
final int size = 4; // We set a fixed size for the square
int[][] arr = new int[size][size]; // create the array from the size
// Running vallues
// i and j to refer to the array.
// val holds the current value to be inserted
// circle holds how often we are going up. Each time we go up it´s increased by one
// In the end this should reduce the amount of steps we do to not override
// already assigned values.
int i = 0,j = 0, val = 1, circle = 0;
Mode runningMode = Mode.right; // We start by going to the right.
while(size*size >= val) { // loop until we reached the last value
arr[j][i] = val++; // Assign the value and increase the value by one afterwards.
// We go right.
if(runningMode == Mode.right) {
// we reached the last assignable item.
// subtract one to not get an index out of bound,
// subract the variable trips that is used to get the last item for the inner circle
if(i==arr.length-1-circle) {
// We are going down now and increase j
runningMode = Mode.down;
++j;
} else {
// go on going right.
++i;
}
} else if(runningMode == Mode.down){
// we reached the last assignable item.
// subtract one to not get an index out of bound,
// subract the variable trips that is used to get the last item for the inner circle
if(j==arr.length-1-circle) {
// We are going left now and decrease i
runningMode = Mode.left;
--i;
} else {
// go on going down.
++j;
}
} else if(runningMode == Mode.left){
// we reached the last assignable item.
// add the variable trips that is used to get the last item for the inner circle
if(i==0+circle) {
// We are going up now and decrease j
// Simultaniosly we are about to end our next circle, so we increase circle
runningMode = Mode.up;
++circle;
--j;
} else {
// go on going left.
--i;
}
} else if(runningMode == Mode.up){
// we reached the last assignable item.
// add the variable trips that is used to get the last item for the inner circle
if(j==0+circle) {
// We are going right now and increase i
runningMode = Mode.right;
++i;
} else {
// go on going up.
--j;
}
}
}
// Print the result
for(int[] a : arr) {
for(int b : a) {
System.out.print(b + "\t" );
}
System.out.println();
}
}
}

Related

How many steps does it take to visit every cell of a 2d array?

I have the following problem I can't figure out on my own.
There is a 2D array with 8x8 dimensions. A dog is randomly put within this dimension. The dog is not allowed to walk out of the dimension, if it does those steps are not counted. Every step the dog takes to another square is counted. Each simulation should calculate the number of overall steps it took for the dog to visit all squares of the 8x8 dimension at least once.
How do I know if all 64 squares got stepped at least once to stop the simulation and print the steps?
int [] [] onSquare = new int [8][8];
int counter = 0;
int x = rnd.nextInt(8); // random position for the dog 0-7
int y = rnd.nextInt(8);
for (int i = 0; i < onSquare.length; i++) {
for (int j = 0; j < onSquare.length; j++) {
onSquare [i] [j] = -1; // dog is on no square in beginning
}
while (onSquare[i][j] == -1) {
int dog = rnd.nextInt(4)+1; // random movement from dog
if (dog == 1) {
x++; // x,y show position of the dog
counter++; // number of steps
if (onSquare[i][j] == onSquare[x][y]) { <---- This gives me errors when checking if x,y lies within i,j
onSquare[i][j] = 1; // stepped on square
}
}
if (dog == 2) {
x--;
counter++;
onSquare[i][j] = 1;
}
if (dog == 3) {
y++;
counter++;
onSquare[i][j] = 1;
}
if (dog == 4) {
y--;
counter++;
onSquare[i][j] = 1;
}
if (x < 0 || y < 0 || x > onSquare.length || y > onSquare.length) {
counter++;
onSquare[i][j] = 0;
}
}
}
use a steps counter to keep track of movement, for each movement, increment its value.
instead of using boolean array, use int array for tracking cells traversed.
int [] [] onSquare = new int [8] [8];
initialize all the cell to have -1 , indicating no dog movement to the cell yet.
for(int i = 0 ; i < 8; i++ )
for(int j = 0; j < 8 ; j++ )
onSquare[i][j]=-1;
when dog enters it, assign its value to 1 , indicating presence of dog
when dog exits, assign its value to 0, indicating absence of dog
once all cell have non-negative value, stop the simulation and display the value of steps counter!!
Edit: since you are struggling to solve , here is the complete code:
/**
* This simulation assumes dog movement is discrete relative to grid cells
* i.e. its either in one of these cells at a time, overlapping two cells in not allowed!!
* **/
public class DogMovementSimulation
{
int onBoard[][] = null;
int dogPosX = 0;
int dogPosY = 0;
int dogPrevPosX = 0;
int dogPrevPosY = 0;
int directionOfMovement = 0;
int stepsCount = 0;
DogMovementSimulation()
{
onBoard = new int[8][8];
//initialize each position in onBoard to -1 ,implying dog has not been placed yet, not even once!!
for( int i = 0 ; i < 8 ; i++ )
{
for( int j = 0 ; j < 8 ; j++ )
{
onBoard[i][j] = -1;//implying dog has not been placed yet, not even once!!
}
}
//place dog in random cell
dogPosX = (int)Math.round(Math.random()*7);//generating random number between 0 and 7, since index is from 0 to 7 as there are 8 cell!!
dogPosY = (int)Math.round(Math.random()*7);
//assigning 1 to onBoard at index dogPosX,dogPosY to indicate dog has been placed there
onBoard[dogPosX][dogPosY] = 1;
}
/*this function returns false if any cell has -1,else true
* cause when all cells have been traversed , each cell have non negative value,either 0 or 1
* */
public boolean areAllCellsTraversed()
{
boolean result = true;
for( int i = 0 ; i < 8 ; i++ )
{
for( int j = 0 ; j < 8 ; j++ )
{
if( onBoard[i][j] == -1 )//implying this cell not traversed yet,i.e dog not placed in this cell yet!!
{
result = false;
}
}
}
return result;
}
public void simulate()
{
//loop while all cells have been not traversed
while( !areAllCellsTraversed() )
{
directionOfMovement = (int)Math.round(Math.random()*3);//generating random number between 0 and 3
switch( directionOfMovement )
{
case 0://move left-to-right
dogPosX += 1;
if( dogPosX >= 7 ) dogPosX = 0; //since largest array index is 1 less than its size, we compare with 7 instead of 8
break;
case 1://move right-to-left
dogPosX -= 1;
if( dogPosX <= 0 ) dogPosX = 7;
break;
case 2://move top-to-bottom
dogPosY += 1;
if( dogPosY >= 7 ) dogPosY = 0;
break;
case 3://move bottom-to-top
dogPosY -= 1;
if( dogPosY <= 0 ) dogPosY = 7;
break;
}
//assign 0 to previous position, meaning dog is no longer there
onBoard[dogPrevPosX][dogPrevPosY] = 0;
//assign 1 to new position , meaning dog is here
onBoard[dogPosX][dogPosY] = 1;
stepsCount++;
dogPrevPosX = dogPosX;
dogPrevPosY = dogPosY;
}
//once all cells have been traversed , print result!!
printSteps();
}
/*prints the total number of step taken to traverse all cells*/
public void printSteps()
{
System.out.println("Total steps taken by dog to traverse all cell = "+stepsCount);
}
public static void main(String[] args)
{
DogMovementSimulation dms = new DogMovementSimulation();
dms.simulate();
}
}
Going to write this as a series of suggestions, otherwise I'd feel like I'm basically writing an assignment for you.
It sounds like you should get rid of dimension, since it isn't doing anything useful.
You should store the value 8 in a variable.
int size = 8;
It sounds like you're trying to both check when all squares have been visited, but also check how many steps were taken, including revisiting old squares. For this you will require two counters, not one.
int steps = 0;
int visited = 0;
You need bounds checking to make sure x and y don't go out of bounds.
if (dog == 1 && x < size - 1) {
x += 1;
steps += 1;
You need to check whether the dog has visited this location before. If he hasn't been here before, then increment the counter.
if (!onSquare[x][y]) {
onSquare[x][y] = true;
visited += 1;
}
You need to stop when you've visited every location.
while (visited < size * size) {

How do i correct my DP solution for the Cherry Pickup problem

My approach seems to be correct , the issue is whether multiple trips are allowed.
My solution seems to exceed the correct answer.
The Question:
In a N x N grid representing a field of cherries, each cell is one of three possible integers.
0 means the cell is empty, so you can pass through;
1 means the cell contains a cherry, that you can pick up and pass through;
-1 means the cell contains a thorn that blocks your way.
Your task is to collect maximum number of cherries possible by following the rules below:
Starting at the position (0, 0) and reaching (N-1, N-1) by moving right or down through valid path cells (cells with value 0 or 1);
After reaching (N-1, N-1), returning to (0, 0) by moving left or up through valid path cells;
When passing through a path cell containing a cherry, you pick it up and the cell becomes an empty cell (0);
If there is no valid path between (0, 0) and (N-1, N-1), then no cherries can be collected.
My Solution:
class Solution {
public int cherryPickup(int[][] grid) {
int N = grid.length;
int[][] dp;
char[][] track;
boolean f = true;
int sum = 0;
int count = 0;
while(f)
{
dp = new int[N][N];
track = new char[N][N];
dp[0][0] = grid[0][0];
track[0][0] = 'a';
char c;
c='u';
for(int i=1;i<N;i++)
{
if(c=='r'||grid[i][0]==-1)
{
c='r';
dp[i][0]=-1;
}
else
dp[i][0] = dp[i-1][0] + grid[i][0];
track[i][0] = c;
}
c='s';
for(int j=1;j<N;j++)
{
if(c=='r'||grid[0][j]==-1)
{
c='r';
dp[0][j]=-1;
}
else
dp[0][j] = dp[0][j-1] + grid[0][j];
track[0][j] = c;
}
for(int i=1;i<N;i++)
for(int j=1;j<N;j++)
{
if(grid[i][j]==-1||(track[i-1][j]=='r' && track[i][j-1]=='r'))
{
track[i][j] = 'r';
dp[i][j] = -1;
}
else
{
if(dp[i-1][j]>=dp[i][j-1])
{
track[i][j] = 'u';
dp[i][j] = dp[i-1][j] + grid[i][j];
}
else
{
track[i][j] = 's';
dp[i][j] = dp[i][j-1] + grid[i][j];
}
}
}
if(dp[N-1][N-1]<=0)
break;
sum += dp[N-1][N-1];
int r = N-1 , cr = N-1;
while(r>0||cr>0)
{
grid[r][cr]=0;
if(track[r][cr]=='s')
cr--;
else
r--;
}
grid[0][0] = 0;
}
return sum;
}
}
Can someone help??

Coding Bubble Sort using Java

I don't know if I did this coding correctly, but can someone confirm if my doBubbleSort method and its implementation in the main method are programmed correctly? My coding requires me to create an array of size 20 and populate it with random integers between 1 and 1000 without hard coding them. The result should display the original, unsorted list of integers; and then display each pass of the bubble sorting algorithm on a separate line. I have to repeat the program until the user chooses to quit. **I have made edits to make sure that whatever variables I use, it is declared according to ArrayLists.
An example of how I want my output to come out as is shown below (although it only shows 5 integers when I'm trying to do 20):
Unsorted list: 68 3 298 290 1
Pass 1: 3 68 290 1 298
Pass 2: 3 68 1 290 298
Pass 3: 3 1 68 290 298
Pass 4: 1 3 68 290 298
// Used to capture keyboard input
import java.util.*;
// Our class called BubbleSort
public class BubbleSort {
// Create doBubbleSort method
public static void doBubbleSort(ArrayList<Integer> arr) {
boolean needNextPass = true;
while (needNextPass) {
// Array may be sorted and next pass not needed
needNextPass = false;
// Swap list
for (int i = 0; i < arr.size()-1; i++) {
if (arr.get(i) > arr.get(i+1)) {
int temp = arr.get(i);
arr.set(i, arr.get(i+1));
arr.set(i+1, temp);
printOut(i+1, arr); // using printOut method
needNextPass = true; // Next pass still needed
}
}
}
}
private static void printOut(int pass, ArrayList<Integer> list) {
System.out.print("PASS " + pass + ": ");
for (int i = 0; i < list.size()-1; i++) {
System.out.print(list.get(i) + ", ");
}
// Shows very last integer with a period
System.out.print(list.get(list.size()-1) + ".");
System.out.println();
}
// Main method
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>(); // Declare and instantiate a new ArrayList object
Scanner userChoice = new Scanner(System.in); // User input for quitting program
String choice = ""; // Will hold user choice to quit program
boolean inputFlag = false; // True if input is valid, false otherwise
// Repeat program until user chooses to quit
while (inputFlag = true) {
System.out.print("\nWould you like to continue the program? (Y/N): ");
choice = userChoice.nextLine();
if (choice.equalsIgnoreCase("Y")) {
try {
/* Create an array of size 20 and populate it with random integers between 1 and 1000.
Do not ask user for the numbers and do not hard code them */
for (int i = 0; i < 20; i++) {
int integer = (int)(1000.0 * Math.random());
array.add(integer);
}
System.out.print("\nUNSORTED LIST: ");
//Display the 20 size of the unsorted ArrayList
for (int i = 0; i < array.size() - 1; i++) {
System.out.print(array.get(i) + ", ");
}
// Shows very last integer with a period
System.out.print(array.get(array.size() - 1) + ".");
System.out.println();
doBubbleSort(array);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nThere is an out of bounds error in the ArrayList.");
}
}
else if (choice.equalsIgnoreCase("N")) {
break;
}
// Error message when inputting anything other than Y/N
else {
System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
System.out.println("Please try again.");
}
}
}
}
Going with your implementation, since you seem to be newly learning this, there are a few things you should change. First of all, since you're using an int array for the doBubbleSort method, use an int array in the main method as well.
The implementation of bubblesort needs to be changed too. You should first look into its logic carefully. Going through the whole array every time is not necessary.
// Create doBubbleSort method
public static void doBubbleSort(int[] arr) {
boolean needNextPass = true;
// Array may be sorted and next pass not needed
// Swap list
for (int i = 0; i < arr.length - 1; i++) {
if (needNextPass) {
needNextPass = false;
for (int j = arr.length - 1; j > i; j--) {
int temp;
if (arr[j] < arr[j - 1]) {
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
needNextPass = true; // Next pass still needed
}
}
printOut(i + 1, arr); // using printOut method
}
}
}
And then, printing the array.
private static void printOut(int pass, int[] list) {
System.out.print("PASS " + pass + ": ");
for (int i = 0; i < list.length - 1; i++) {
System.out.print(list[i] + ", ");
}
// Shows very last integer with a period
System.out.print(list[list.length - 1] + ".");
System.out.println();
}
Now the main method. I've changed the input handling part for re-running the program, and used an int array as you had originally posted.
// Main method
public static void main(String[] args) {
int[] array = new int[20]; // Declare and instantiate a new ArrayList object
Scanner userChoice = new Scanner(System.in); // User input for quitting program
boolean inputFlag = true; // True if input is valid, false otherwise
String choice;
// Repeat program until user chooses to quit
while (inputFlag == true) {
try {
/* Create an array of size 20 and populate it with random integers between 1 and 1000.
Do not ask user for the numbers and do not hard code them */
for (int i = 0; i < 20; i++) {
int integer = (int) (1000.0 * Math.random());
array[i] = integer;
}
System.out.print("\nUNSORTED LIST: ");
//Display the 20 size of the unsorted ArrayList
for (int i = 0; i < array.length - 1; i++) {
System.out.print(array[i] + ", ");
}
// Shows very last integer with a period
System.out.print(array[array.length - 1] + ".");
System.out.println();
doBubbleSort(array);
} catch (IndexOutOfBoundsException e) {
System.out.println("\nThere is an out of bounds error in the ArrayList.");
}
System.out.print("\nWould you like to continue the program? (Y/N): ");
choice = userChoice.nextLine();
while (!(choice.equalsIgnoreCase("Y")) && !(choice.equalsIgnoreCase("N"))) {
// Error message when inputting anything other than Y/N
System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
System.out.println("Please try again.");
choice = userChoice.nextLine();
}
if (choice.equalsIgnoreCase("N")) {
inputFlag = false;
}
}
}
}
You wrote too much boiler plate code for bubble sort. For bubble sort, use recursive method. I wrote for you simple bubble method, do what you want with output
private int[] bubbleSort(int[] arr){
int c;
boolean isArranged = false;
for (int i = 0; i < arr.length; i++) {
if (i < (arr.length - 1) && arr[i] > arr[i+1]){
c = arr[i];
arr[i] = arr[i+1];
arr[i+1] = c;
isArranged = true;
}
}
if (isArranged){
return bubbleSort(arr);
}else{
return arr;
}
}
Call this like:
Scanner in = new Scanner(System.in);
int length = in.nextInt();
int[] arr = new int[length];
for (int i = 0; i < length; i++) {
arr[i] = in.nextInt();
}
Main main = new Main();
int[] newArr = main.bubbleSort(arr);
for (int i = 0; i < newArr.length; i++) {
System.out.print(newArr[i] + " ");
}
You can write ArrayList instead int array.

Java not inclusive of 100 in 100 Lockers

MY desired output is locker 1,4,9,16,36,49,81 AND 100.
I'm iterating through trying to find which lockers after a student is sent, and opens every locker. (All are closed by default) and opens every locker. then student number 2 goes to every other locker, and if it is open, close it, and if it is closed, open it. Student three does the same but with every third locker. All the way up to student 100. I know the output should be all the square numbers but I can't get the 100 to show up. What am I missing? I put a <= on both of my iterations and it doesn't work. It throws an IndexOutOfRangeException. What should I do?
import java.util.Arrays;
public class runLocker {
final static int numberOfLockers = 100;
final static int numberOfStudents = 100;
public static void main(String[] args) {
// TODO Auto-generated method stub
int LockersToCloseBy = 1;
boolean[] totalLockersArray = new boolean[numberOfLockers];
for(int i = 0; i < totalLockersArray.length - 1; i++){
totalLockersArray[i] = false;
}
for(int n= 0; n < totalLockersArray.length ; ++n){
for(int j = 0; j < totalLockersArray.length; j+=LockersToCloseBy){
if(totalLockersArray[j] == true)
{
totalLockersArray[j] = false;
}
else
{
totalLockersArray[j] = true;
}
}
LockersToCloseBy++;
}
for(int i = 0; i < numberOfLockers; i++){
if(totalLockersArray[i] == true){
System.out.println("Locker " + i + " is open");
}
}
//Currently outputs 1, 4, 9, 16, 36, 49, and 81...
//Need it to output 1,4,9,16,36,49,81,100
}
}
Your array is defined for indices [0,...,99] (100 elements total, exclusive of 100).
In the following code:
for(int i = 0; i < numberOfLockers; i++){
if(totalLockersArray[i] == true){
System.out.println("Locker " + i + " is open");
}
}
100 is not even a candidate.
An easy fix could be to set the lockers array at 101 (numberOfLockers=101), so all the loops will be inclusive of 100.

Display Matrix to get a unique Pattern

I want to construct a square matrix (2D) of size n (which will be input by the user)
Now I want to construct a diagonal pattern.
For example (3X3 Matrix):
2 3
1
4 5
The value variable will be initialized to 1 and stored at the center of the square matrix. Then value will be incremented and stored at upper left corner as shown above, and so on.
It is a simple program to be displayed on console.
User input can taken from command line.
I am trying to generalize a condition in a for loop that will work for square matrix of size 5,7,9... (odd numbers).
For a matrix of size 5 it will be
6 7
2 3
1
4 5
8 9
(the empty spaces can be zero)
My code:
import java.util.*;
public class MatrixAdv
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Please enter size of element...");
int n=sc.nextInt(); //stores size of Matrix
int value=0; //To be incremented everytime to get the Pattern
int [][] matrix = new int[n][n];
int k=0;
for(int i=0;i<some Condition;i++)
{
for(int j=1;j<some Condition;j++)
{
k=n-2-j;
matrix[k][k]=++value;
}
}
}
//Display the value in matrix form
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
Print(matrix[i][j]+"\t");
}
Print("\n");
}
}
its very easy to print 99% matrix patterns if you know the magic of matrix...and you can do it without using any memory.
here is the code......
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
if(n == 1)
cout<<1;
else
{
int sv=2*n-4,a,b;
a=sv;b=sv+1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i == j && i+j == n+1)
{
cout<<" 1 ";
sv=4;
}
else
{
if(i == j)
cout<<" "<<a<<" ";
else if((i+j) == n+1)
cout<<" "<<b<<" ";
else
cout<<" ";
}
}
if(i < n/2+1)
{
sv=sv-4;
a=sv;b=sv+1;
}
else if(i > n/2+1)
{
sv=sv+4;
b=sv;a=sv+1;
}
else
{
sv=4;
b=sv;a=sv+1;
}
cout<<"\n";
}
}
}
There are basically 2 options for solving this:
Go through the whole matrix, row by row and column by column, and check whether a certain value has to be set at the current position
Go through all the positions where a certain value has to be set.
Both of them have nothing to do with the condition of a for-loop. However, here an example for the second approach:
public class MatrixAdv
{
public static void main(String args[])
{
//Scanner sc = new Scanner(System.in);
//System.out.println("Please enter size of element...");
//int n = sc.nextInt(); // stores size of Matrix
int n = 9;
int value = 0;// To be incremented everytime to get the Pattern
int[][] matrix = new int[n][n];
matrix[n/2][n/2] = 1;
int maxValue = ((n / 2) * 4) + 1;
int r = n / 2 - 1;
int c = n / 2 - 1;
int d = 2;
for (value=2; value<=maxValue; value++)
{
matrix[r][c] = value;
int step = ((value-2)%4);
switch (step)
{
case 0: c+=d; break;
case 1: r+=d; c-=d; break;
case 2: c+=d; break;
case 3: d+=2; r-=d-1; c-=d-1; break;
}
}
// Display the value in matrix form
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i][j] == 0)
{
System.out.printf("%3s", "_");
}
else
{
System.out.printf("%3d", matrix[i][j]);
}
}
System.out.print("\n");
}
}
}

Categories

Resources