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);
}
Related
I am creating the grid so first, I have to input the size of the grid like 4 and then input the grid
0 0 0 1
1 2 3 0
2 2 0 2
3 3 1 0
however, I want to read the grid from the file.
For example, java test 4 < file.txt
Any suggestion on how to do it?
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[][] grid = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = scn.nextInt();
}
}
int[][] dp = new int[n][n];
for (int j = 0; j < n; j++) {
dp[n - 1][j] = grid[n - 1][j];
}
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j < n; j++) {
if (j - 1 >= 0 && j + 1 < n) {
dp[i][j] = Math.max(dp[i + 1][j + 1], dp[i + 1][j - 1]) + grid[i][j];
} else if (j - 1 >= 0 && j + 1 >= n) {
dp[i][j] = dp[i + 1][j - 1] + grid[i][j];
} else {
dp[i][j] = dp[i + 1][j + 1] + grid[i][j];
}
}
}
int ans = 0;
for (int j = 0; j < n; j++) {
ans = Math.max(ans, dp[0][j]);
}
System.out.println(ans);
}
}
In order to read from a file, you need to have the entire path (where it is located) so that you can read it. Assuming its from the directory as the jar, use can use the below code snippet:
public static void main(String[] args) {
try {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
String fileName = scn.nextLine();
File file= new File(fileName);
Scanner fileReader = new Scanner(file);
while(fileReader.hasNextLine()){
int[][] grid = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = scn.nextInt();
}
}
}
//Remaining operation as in your code
} catch (Exception e) {
System.out.printlin("Exception occurred while processing: " + e);
}
}
}
Note: Something similar can be used, I'm currently not having an editor with me, hence apologies for any mistakes
Try this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws FileNotFoundException {
int n = Integer.parseInt(args[0]);
int[][] grid = new int[n][n];
File myObj = new File(args[2]);
Scanner myReader = new Scanner(myObj);
for (int i = 0; i < n; i++) {
String[] strs = myReader.nextLine().split(" ");
for (int j = 0; j < n; j++) {
grid[i][j] = Integer.parseInt(strs[j]);
}
}
int[][] dp = new int[n][n];
for (int j = 0; j < n; j++) {
dp[n - 1][j] = grid[n - 1][j];
}
for (int i = n - 2; i >= 0; i--) {
for (int j = 0; j < n; j++) {
if (j - 1 >= 0 && j + 1 < n) {
dp[i][j] = Math.max(dp[i + 1][j + 1], dp[i + 1][j - 1]) + grid[i][j];
} else if (j - 1 >= 0 && j + 1 >= n) {
dp[i][j] = dp[i + 1][j - 1] + grid[i][j];
} else {
dp[i][j] = dp[i + 1][j + 1] + grid[i][j];
}
}
}
int ans = 0;
for (int j = 0; j < n; j++) {
ans = Math.max(ans, dp[0][j]);
}
System.out.println(ans);
}
}
Firstly, i should mention that i only recently started programming (about a year ago). My main-language is Java.
to elaborate on what I've done:
to learn about Neural Networks i watched 3Blue1Brown´s series on the topic
after (mostly) understanding it i started to make the actual Implementation
I implemented a File-Reader to turn the raw numbers of the Database (i used MNIST just like 3b1b) into three arrays : 1 for the labels, 1 for the Images and one for the grayscale-values (i mapped the RGB values between 0 and 1) in one input-array
I then designed a test() and train() method, this is what i did:
public class Network {
int L;
int[] Lsize;
double[][][] weights;
double[][] biases;
public Network(int... Lsize) {
L = Lsize.length;
this.Lsize = Lsize;
weights = new double[L - 1][][];
for (int i = 0; i < L - 1; i++) {
weights[i] = new double[Lsize[i + 1]][Lsize[i]];
for (int j = 0; j < Lsize[i + 1]; j++) {
for (int k = 0; k < Lsize[i]; k++) {
weights[i][j][k] = (Math.random() * 2) - 1;
}
}
}
biases = new double[L - 1][];
for (int i = 0; i < L - 1; i++) {
biases[i] = new double[Lsize[i + 1]];
for (int j = 0; j < Lsize[i + 1]; j++) {
biases[i][j] = (Math.random() * 2) - 1;
}
}
}
public static void main(String[] args) {
Network n = new Network(28 * 28, 16, 16, 10);
Database mnist_train = new Database(60000, 28, 28, "mnist_train");
Database mnist_test = new Database(10000, 28, 28, "mnist_test");
System.out.println("accuracy= " + n.accuracy(mnist_test));
for(int i = 0; i < 50; i ++) {
n.train(mnist_train, 10, 0.1);
System.out.println("accuracy= " + n.accuracy(mnist_test));
}
}
public void train(Database data,int batchsize,double factor) {
Batch[] batches = data.dividetoBatches(batchsize);
for (int b = 0; b < data.n / batchsize; b++) {
System.out.println("Step " + b + " started!");
Batch batch = batches[b];
double[][][] averagegweights = new double[L - 1][][];
double[][] averagegbiases = new double[L - 1][];
for (int i = 0; i < L - 1; i++) {
averagegweights[i] = new double[Lsize[i + 1]][Lsize[i]];
averagegbiases[i] = new double[Lsize[i + 1]];
}
double averagecost = 0;
for (int e = 0; e < batchsize; e++) {
double[] target = batch.target[e];
double[] values = batch.values[e];
double[][] z = new double[L - 1][];
double[][] a = new double[L][];
a[0] = values;
for (int i = 0; i < L - 1; i++) {
a[i + 1] = new double[Lsize[i + 1]];
z[i] = new double[Lsize[i + 1]];
for (int j = 0; j < Lsize[i + 1]; j++) {
double sum = biases[i][j];
for (int k = 0; k < Lsize[i]; k++) {
sum += weights[i][j][k] * a[i + 1][j];
}
z[i][j] = sum;
a[i + 1][j] = sigmoid(sum);
}
}
double[][][] gweights = new double[L - 1][][];
double[][] gbiases = new double[L - 1][];
double[][] dCa = new double[L][];
double cost = 0;
dCa[L - 1] = new double[Lsize[L - 1]];
for (int i = 0; i < Lsize[L - 1]; i++) {
dCa[L-1][i] = 2 * (target[i] - a[L - 1][i]);
cost += (target[i] - a[L - 1][i]) * (target[i] - a[L - 1][i]);
}
// Backpropagation:
for (int i = L - 2; i >= 0; i--) {
dCa[i] = new double[Lsize[i]];
gweights[i] = new double[Lsize[i+1]][Lsize[i]];
gbiases[i] = new double[Lsize[i]];
for (int j = 0; j < Lsize[i + 1]; j++) {
gbiases[i][j] = dsigmoid(z[i][j]) * dCa[i+1][j];
for (int k = 0; k < Lsize[i]; k++) {
gweights[i][j][k] = a[i][k] * dsigmoid(z[i][j]) * dCa[i+1][j];
}
}
for (int k = 0; k < Lsize[i]; k++) {
dCa[i][k] = 0;
for (int j = 0; j < Lsize[i + 1]; j++) {
dCa[i][k] += weights[i][j][k] * dsigmoid(z[i][j]) * dCa[i + 1][j];
}
}
}
for (int i = 0; i < L - 1; i++) {
for (int j = 0; j < Lsize[i + 1]; j++) {
averagegbiases[i][j] += gbiases[i][j];
for (int k = 0; k < Lsize[i]; k++) {
averagegweights[i][j][k] += gweights[i][j][k];
}
}
}
averagecost += cost;
}
for (int i = 0; i < L - 1; i++) {
for (int j = 0; j < Lsize[i + 1]; j++) {
averagegbiases[i][j] = averagegbiases[i][j]/batchsize * -1;
for (int k = 0; k < Lsize[i]; k++) {
averagegweights[i][j][k] = averagegweights[i][j][k]/batchsize * -1;
}
}
}
for (int i = 0; i < L - 1; i++) {
for (int j = 0; j < Lsize[i + 1]; j++) {
biases[i][j] += averagegbiases[i][j] * factor;
for (int k = 0; k < Lsize[i]; k++) {
weights[i][j][k] += averagegweights[i][j][k] * factor;
}
}
}
averagecost = averagecost/batchsize;
System.out.println("averagecost = " + averagecost);
// System.out.println(Arrays.deepToString(batch.target));
System.out.println("Das sollte eine" + data.labels[0] + " sein!");
data.shuffle();
double[] output = test(data.values[0]);
for (int i = 0; i < output.length; i++) {
float val = (float) output[i];
System.out.print(i + ": ");
System.out.printf("%.2f", val);
System.out.println();
}
System.out.println("Step " + b + " finished!");
}
}
public double accuracy(Database data) {
int rightanswers = 0;
int answers = 0;
for(int i = 0; i < data.n; i++) {
if(maxIndex(test(data.values[i])) == data.labels[i]) {
rightanswers++;
}
answers++;
}
return (double)rightanswers/(double)answers;
}
public int maxIndex(double[] output) {
int index = 0;
for(int i = 0; i < output.length; i++) {
if(output[i] > output[index])
index = i;
}
return index;
}
public double[] test(double[] input) {
double[][] values = new double[L][];
values[0] = input;
for (int i = 0; i < L - 1; i++) {
values[i + 1] = new double[Lsize[i + 1]];
for (int j = 0; j < Lsize[i + 1]; j++) {
double sum = biases[i][j];
for (int k = 0; k < Lsize[i]; k++) {
sum += weights[i][j][k] * values[i][k];
}
values[i + 1][j] = sigmoid(sum);
}
}
double[] output = values[L - 1];
return output;
}
public double sigmoid(double x) {
return 1 / (1 + Math.pow(Math.E, x));
}
// derivative of the sigmoid-function
public double dsigmoid(double x) {
return sigmoid(x) * (1 - sigmoid(x));
}
}
my problem now is when i run the training the Cost-function decreases, but only because all of the output-values are nearing 0 and not because the network has actually found the right number to the picture.
after about one run through the Database the average Cost stagnates around 0.9
am i missing something fundamental or am i just not noticing an simple error
Thank you in advance
I`m sorry for my bad English, I´m actually German
The first thing you can do is to increase the complexity of the network. I just tried your architecture with my implementation and the network you currently have definitely isn't big enough to fit handwritten digits. I would recommend 784,128,128,10 as that had around 90% accuracy for 3 runs over the training set. If that doesn't yield better results, make sure your implementation of a neural network is functional on something less complex like the XOR problem. If XOR is learnable by your implementation, it could be the way you are altering the dataset. Debugging a neural network is tough, but you have to make sure the foundation of it is built correctly before looking at higher-level problems like learning rate and optimizers. You're using vanilla gradient descent so you should definitely implement momentum as it is easier to implement than what you've already done and is a significant improvement to your current method.
**This is my code that look a way to find a sum in an array **
public class Piecedemonei {
public static void recherche(int[] tab) {
int num;
int quo;
for (int i = 0; i <= tab.length - 1; i++) {
int somme = 18;
System.out.println("Solution " + i);
for (int j = i; j < tab.length; j++){
if (tab[j] <= somme) {
num = somme / tab[j];
System.out.print(num+"*" + " " + tab[j]);
System.out.println(" ");
somme -= num * tab[j];
j=0;
}
}
}
}
public static void main(String[] args) {
int aba[] = { 7, 6, 4, 5 };
recherche(aba);
System.out.println();
}
}
Output
Solution 0
2 7 + 1 4
Solution 1
Solution 2
Solution 3
**I am looking a way to improve my code so that the output looks like this : **
Solution 0
2*7 + 1*4
Solution 1
3*6
Solution 2
4*4 + 1*4
Solution 3
**Why cant I reset my loop so that it does the same thing again and again ? **
Change
int somme = 18;
for (int i = 0; i <= tab.length - 1; i++) {
System.out.println("Solution " + i);
for (int j = 0; j < tab.length; j++){
...
to
for (int i = 0; i <= tab.length - 1; i++) {
int somme = 18;
System.out.println("Solution " + i);
for (int j = i; j < tab.length; j++) {
...
Notice the int j = i in the inner loop.
I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";
so im done with the whole thing and i compile it when i ran it it had a error for said: arrayindexexception and i try looking for my mistake and i could not find it so i need someone to see if they can help me
public class Merging
{
public static int[] merge(int[] arrA, int[] arrB)
{
int[] sum = new int[arrA.length + arrB.length];
int i = 0, j = 0, k = 0;
while ( i < arrA.length && j < arrB.length)
{
if(arrA[i] < arrB[j])
{
sum[k] = arrA[i];
i++;
k++;
}else
sum[k] = arrB[i];
j++;
k++;
}
return sum;
}
public static void main(String[] args)
{
int a = (int)(Math.random() * (50-20+1)+20);
int b = (int)(Math.random() * (50-20+1)+20);
int[] a1 = new int[a];
int[] a2 = new int[b];
int i = 0;
while(i < a1.length && 1 < a2.length)
{
a1[i] = (int) (Math.random() * (150-20+1)+20);
a2[i] = (int) (Math.random() * (150-20+1)+20);
i++;
}
for(int j = 0; j < a1.length; j++)
{
System.out.print(a1[j]);
}
System.out.println();
for(int k = 0; k < a2.length; k++)
{
System.out.print(a1[k]);
}
System.out.println();
System.out.print(merge(a1,a2));
}
}
Two errors.
1.) Change from 1 < a2.length to i < a2.length
while (i < a1.length && i < a2.length) {
a1[i] = (int) (Math.random() * (150 - 20 + 1) + 20);
a2[i] = (int) (Math.random() * (150 - 20 + 1) + 20);
i++;
}
2.) Change from System.out.print(a1[k]); to System.out.print(a2[k]);
for (int k = 0 ; k < a2.length ; k++) {
System.out.print(a2[k]);
}
In your while loop
while(i < a1.length && 1 < a2.length)
the "1" should be an "i"
One of your problems is here
for(int k = 0; k < a2.length; k++)
{
System.out.print(a1[k]);
}
You're iterating through a1, but your index goes to the length of a2.