A child is located in the middle of a grid which is depicted as a rectangular A
ID: 3906911 • Letter: A
Question
A child is located in the middle of a grid which is depicted as a rectangular A x B 2-dimensional array. The items in the array represent the number of chocolate pieces that exist in each location in the array. If the array does not contain a specific center, the child will begin in a location nearby the center with the highest number of chocolate pieces. In each iteration, the child will consume the chocolate pieces on the square where he is located and then moves up, down, left or right selecting the location which has the highest number of chocolate pieces. In case there are no chocolate pieces in the adjacent cells, the child will sleep. Your task is to write a function which takes an array representing the locations and it should return the total number of chocolate pieces a child would eat. Test your program with the array below: 5 7 4 5 10 The child should consume 8+9.8+6 31 chocolate pieces State any assumptions you haveExplanation / Answer
import java.io.*;
import java.util.*;
public class Demo192 {
public static void main(String[] args){
int[][] d = {
{6,8,9,7,4},
{0,0,8,0,5},
{5,7,4,5,10},
{4,2,0,6,9}
};
Random rand = new Random();
int n = d.length;
int x = n/2;
int y = n/2;
int total = d[x][y];
int newx = x;
int newy = y;
while(true){
int max = 0;
if (y -1 >= 0) {
if (d[x][y-1] > max){
newx = x;
newy = y-1;
max = d[x][y-1];
}
}
if (x -1 >= 0 && y-1 >= 0) {
if (d[x-1][y-1] > max){
newx = x-1;
newy = y-1;
max = d[x-1][y-1];
}
}
if (x-1 >= 0) {
if (d[x-1][y] > max){
newx = x-1;
newy = y;
max = d[x][y-1];
}
}
if (x-1 >= 0 && y + 1 <= n-1) {
if (d[x-1][y+1] > max){
newx = x-1;
newy = y+1;
max = d[x-1][y+1];
}
}
if (y + 1 <= n-1) {
if (d[x][y+1] > max){
newx = x;
newy = y+1;
max = d[x][y+1];
}
}
if (y + 1 <= n-1 && x + 1 <= n-1) {
if (d[x+1][y+1] > max){
newx = x+1;
newy = y+1;
max = d[x+1][y+1];
}
}
if (y + 1 <= n-1) {
if (d[x][y+1] > max){
newx = x;
newy = y+1;
max = d[x][y+1];
}
}
if (y - 1 <= 0 && x + 1 <= n-1) {
if (d[x+1][y-1] > max){
newx = x+1;
newy = y-1;
max = d[x+1][y-1];
}
}
if (max > 0){
total = total + max;
}
else
break;
}
System.out.println("Total Choclates :" + total);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.