HackerEarth exercise running out of time - java

I solved the following problem from HackerEarth. All test cases are correct except the last one bacause it runs out of time. I tried optimizing my solution but I cannot optimize it better.
Here is my solution:
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
Set<Integer> perfectNumbers = new HashSet<>();
for (int i = 0; i <= 20; i++) {
perfectNumbers.add(i * i * i);
}
for (int i = 1; i <= 44; i++) {
perfectNumbers.add(i * i);
}
int t = sc.nextInt();
for (int k = 0; k < t; k++) {
int db = 0;
int n = sc.nextInt();
int[] a = new int[1001];
int[] b = new int[1001];
int[] numbers = new int[n];
for (int j = 0; j < n; j++) {
int x = sc.nextInt();
numbers[j] = x;
for (Integer perfect : perfectNumbers) {
if (x == perfect - x) {
b[x]++;
} else if (perfect - x >= 0 && perfect - x <= 1000)
a[perfect - x]++;
}
}
for (int j = 0; j < n; j++) {
db += a[numbers[j]];
}
for (int j = 0; j <= 1000; j++) {
if (b[j] > 1) {
db += b[j] * (b[j] - 1);
}
}
System.out.println(db / 2);
}
}
}

Probably you should consider reading the input with some faster method because Scanner is really slow. You could for example wrap Scanner into a BufferedReader.
I modified the code. Now it passes all test cases:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
class TestClass {
public static void main(String args[]) throws Exception {
FastReader sc = new FastReader();
Set<Integer> perfectNumbers = new HashSet<>();
for (int i = 0; i <= 20; i++) {
perfectNumbers.add(i * i * i);
}
for (int i = 1; i <= 44; i++) {
perfectNumbers.add(i * i);
}
int t = sc.nextInt();
for (int k = 0; k < t; k++) {
int db = 0;
int n = sc.nextInt();
int[] a = new int[1001];
int[] b = new int[1001];
int[] numbers = new int[n];
for (int j = 0; j < n; j++) {
int x = sc.nextInt();
numbers[j] = x;
for (Integer perfect : perfectNumbers) {
if (x == perfect - x) {
b[x]++;
} else if (perfect - x >= 0 && perfect - x <= 1000)
a[perfect - x]++;
}
}
for (int j = 0; j < n; j++) {
db += a[numbers[j]];
}
for (int j = 0; j <= 1000; j++) {
if (b[j] > 1) {
db += b[j] * (b[j] - 1);
}
}
System.out.println(db / 2);
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
Integer nr=null;
try {
nr = Integer.parseInt(next());
} catch (Exception e) {
//something went wrong
}
return nr;
}
}
}

Related

Why am I getting 100% accuracy in my Java MLP program?

I am writing a code in java that uses an MLP algorithm on a digit recognition dataset. I have 2 excel files. One for training and one for testing and they both contain 65 columns and 2810 rows. Below is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;
public class Main {
static int hiddenNeurons = 64; // Number of hidden neurons
static int[][] WH = new int[hiddenNeurons][64]; // Weight between the input and the hidden neurons
static int[][] WO = new int[10][hiddenNeurons]; // Weight between the hidden neurons and the output
static double[] outputHidden = new double[hiddenNeurons];
static double[] outputNeuron = new double[10];
static int[] dataSample = new int[64];
static int[] mapTarget = new int[10];
static int[] errorOutput = new int[10];
static int[] errorHidden = new int[hiddenNeurons];
static void initializeWeights(){
Random randomNumber = new Random();
for (int i = 0; i < WH.length; i++) {
for (int j = 0; j < WH[i].length; j++) {
WH[i][j] = randomNumber.nextInt(10);
}
}
for (int i = 0; i < WO.length; i++) {
for (int j = 0; j < WO[i].length; j++) {
WO[i][j] = randomNumber.nextInt(10);
}
}
}
public static void feedForward(){
double sigmoid = 0;
double sumWH = 0;
for (int i = 0; i < hiddenNeurons; i++) {
for (int j = 0; j < dataSample.length; j++) {
sumWH += dataSample[j] * WH[i][j];
}
sigmoid = 1 / (1 + Math.exp(-sumWH));
outputHidden[i] = sigmoid;
}
for (int i = 0; i < outputNeuron.length; i++) {
double sumWO = 0;
for (int j = 0; j < dataSample.length; j++) {
sumWO += outputHidden[j] * WO[i][j];
}
outputNeuron[i] = sumWO >= 0 ? 1 : 0;
}
}
static boolean testError() {
for (int i = 0; i < outputNeuron.length; i++) {
if (mapTarget[i] != outputNeuron[i]) {
return false;
}
}
return true;
}
static void training(){
double learningRate = 0.1;
for (int i = 0; i < outputNeuron.length; i++) {
errorOutput[i] = (int) (mapTarget[i] - outputNeuron[i]);
}
for (int j = 0; j < hiddenNeurons; j++) {
double errorTemp = 0;
for (int i = 0; i < outputNeuron.length; i++) {
errorTemp += errorOutput[i] * WO[i][j]; //try [j][i]
}
errorHidden[j] = (int) (outputHidden[j] * (1-outputHidden[j]) * errorTemp);
}
for (int i = 0; i < outputNeuron.length; i++) {
for (int j = 0; j < hiddenNeurons; j++) {
WO[i][j] = (int) (WO[i][j] + learningRate * outputHidden[j] * errorOutput[i]);
}
}
for (int i = 0; i < hiddenNeurons; i++) {
for (int j = 0; j < dataSample.length; j++) {
WH[i][j] = (int) (WH[i][j] + learningRate * dataSample[j] * errorHidden[i]);
}
}
}
static void testing(){
double success = 0;
try(BufferedReader br = new BufferedReader(new FileReader("test.csv"))) {
String line;
int numOfRows = 0;
boolean errorTested = false;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (int i = 0; i < 64; i++) {
dataSample[i] = Integer.parseInt(values[i]);
}
int targetOutput = Integer.parseInt(values[values.length - 1]);
for (int i = 0; i < 10; i++) {
mapTarget[i] = 0;
}
numOfRows++;
mapTarget[targetOutput] = 1;
feedForward();
errorTested = testError();
if(!errorTested){
success++;
}
}
double accuracy = success / numOfRows;
System.out.println("testing dataset accuracy: " + accuracy * 100);
}
catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
double success = 0;
initializeWeights();
try (BufferedReader br = new BufferedReader(new FileReader("train.csv"))) {
String line;
int numOfRows = 0;
double accuracy = 0;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (int i = 0; i < 64; i++) {
dataSample[i] = Integer.parseInt(values[i]);
}
int targetOutput = Integer.parseInt(values[values.length - 1]);
for (int i = 0; i < 10; i++) {
mapTarget[i] = 0;
}
mapTarget[targetOutput] = 1;
feedForward();
if (testError()) {
training();
} else {
success++;
}
numOfRows++;
accuracy = success / numOfRows;
}
System.out.println("training dataset: " + accuracy*100);
testing();
}
catch (Exception e){
e.printStackTrace();
}
}
}
This code, when run, gives me this output:
training dataset: 100.0
testing dataset accuracy: 100.0
What is the issue that seems to show me 100% accuracy even though that isn't possible.

equation = 0, idk why this happens but it is not in integer data type

Here is a code operating a simple clock (second chance) Page Replacement, my problem is that my math equation (double pager = fault/ref_len*100;) always outputs to 0 when i call it in my output line.
i wish to make my variable output the correct product but it always == to 0 when i output it on my terminal.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ClockReplacement {
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int frames, pointer = 0, hit = 0, fault = 0,ref_len;
int buffer[][];
int reference[];
int mem_layout[][];
int used_layout[][];
System.out.println("Please enter the number of Frames: ");
frames = Integer.parseInt(br.readLine());
System.out.println("Please enter the length of the Reference string: ");
ref_len = Integer.parseInt(br.readLine());
reference = new int[ref_len];
mem_layout = new int[ref_len][frames];
used_layout = new int[ref_len][frames];
buffer = new int[frames][2];
for(int j = 0; j < frames; j++)
{
buffer[j][0] = -1;
buffer[j][1] = 0;
}
System.out.println("Please enter the reference string: ");
for(int i = 0; i < ref_len; i++)
{
reference[i] = Integer.parseInt(br.readLine());
}
System.out.println();
for(int i = 0; i < ref_len; i++)
{
int search = -1;
for(int j = 0; j < frames; j++)
{
if(buffer[j][0] == reference[i])
{
search = j;
hit++;
buffer[j][1] = 1;
break;
}
}
if(search == -1)
{
while(buffer[pointer][1] == 1)
{
buffer[pointer][1] = 0;
pointer++;
if(pointer == frames)
pointer = 0;
}
buffer[pointer][0] = reference[i];
buffer[pointer][1] = 1;
fault++;
pointer++;
if(pointer == frames)
pointer = 0;
}
for(int j = 0; j < frames; j++)
{
mem_layout[i][j] = buffer[j][0];
used_layout[i][j] = buffer[j][1];
}
}
for(int i = 0; i < frames; i++)
{
for(int j = 0; j < ref_len; j++)
System.out.printf("%3d %d ",mem_layout[j][i],used_layout[j][i]);
System.out.println();
}
System.out.println("#Page Faults: " + fault);
double pager = fault/ref_len*100;
System.out.println("%page replacement: " + pager);
}
}

Finding minimum weight and number of edges traversed in a graph

I have to find the minimum distance between two vertices and no. of edges traversed in finding that minimum distance in a adirected weighted graph. I did write a code on using Dijkstras algo. But my test cases are failing. What am i missing here.?
Ideal input: given any two vertices A,B
Output: min distance between two nodes, no. of edges traversed
If the node is unreachable then output should be -1, -1.
//This is a java program to find the shortest path between source vertex and destination vertex
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Dijkstras_Shortest_Path
{
private int distances[];
private int Numnodes[];
private int numnodes;
private Set<Integer> settled;
private Set<Integer> unsettled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public Dijkstras_Shortest_Path(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
Numnodes=new int[number_of_nodes+1];
settled = new HashSet<Integer>();
unsettled = new HashSet<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];
for (int i = 1; i <= number_of_nodes; i++)
{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min;
int node = 0;
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
int newNodes=1;
for (int destinationNode = 1; destinationNode <= number_of_nodes;
destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] !=
Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode]
[destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
newNodes=Numnodes[evaluationNode]+1;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
Numnodes[destinationNode]=newNodes;
}
unsettled.add(destinationNode);
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int number_of_edges;
int source = 0, destination = 0;
Scanner scan = new Scanner(System.in);
try
{
number_of_vertices = scan.nextInt();
number_of_edges=scan.nextInt();
if (number_of_vertices<1||number_of_vertices>10000)
{
System.out.println("Number of vertices out of boundary");
}
if (number_of_edges<1||number_of_edges>10000)
{
System.out.println("Number of edges out of boundary");
}
adjacency_matrix = new int[number_of_vertices + 1]
[number_of_vertices + 1];
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = 0;
}
}
for(int i=1;i<=number_of_edges;i++)
{
int node1=scan.nextInt();
int node2=scan.nextInt();
adjacency_matrix[node1][node2]=scan.nextInt();
}
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
source = scan.nextInt();
destination = scan.nextInt();
Dijkstras_Shortest_Path dijkstrasAlgorithm = new
Dijkstras_Shortest_Path(
number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++)
{
if (i == destination)
System.out.println(dijkstrasAlgorithm.distances[i] +" "+
dijkstrasAlgorithm.Numnodes[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

SPOJ's prime generator giving runtime error while it is working fine on Idone.com

I am getting runtime error on submitting this code, while it is running fine on idone.com and on my local machine. I think I am omitting boundary condition somewhere but can't find where.
Here is my code.
package com.prime.src;
import java.util.Scanner;
class PrimeSieve {
static boolean[] isPrime = new boolean[100000];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int j = 2; j < isPrime.length; j++) {
isPrime[j] = true;
}
if(scanner.hasNextInt()){
int N = Integer.parseInt(scanner.nextLine());
int lowerBound = 0;
int upperBound = 0;
for (int i = 0; i < N; i++) {
lowerBound = scanner.nextInt();
upperBound = scanner.nextInt();
printPrime(lowerBound, upperBound);
}
}
else{
System.out.println();
}
}
public static void printPrime(long lowerBound, long upperBound){
for (int i = 2; i * i <= upperBound; i++) {
if (isPrime[i]) {
for (int j = i; i * j <= upperBound; j++) {
isPrime[i * j] = false;
}
}
}
boolean[] range = new boolean[(int) (upperBound + 1)];
for (int i = (int) upperBound; i >= lowerBound; i--) {
range[i] = true;
}
for (int j = 2; j * j < upperBound; j++) {
if (isPrime[j]) {
long num1 = lowerBound / j;
long num2 = num1 * j;
long limit = num2;
for (long i = lowerBound; limit <= upperBound; i++) {
if (limit != j) {
range[(int) limit] = false;
}
limit = limit + j;
}
}
}
for (long i = lowerBound; i <= upperBound; i++) {
if (i == 1)
continue;
if (range[(int) i]) {
System.out.println(i);
}
}
}
}
AS SPOJ is not quite verbose when it comes to exceptionhandling you could wrap the code in the main method like this to get more information:
public static void main(String[] args) throws IOException
{
try {
//the original code in your main-Method goes here
} catch(Exception e){
e.printStackTrace();
return;
}
}
I suspect it's a wrapped timeout, as Scanner is not very fast.

What is the wrong with my code for the StairCase challenge on HackerRank?

Here is my main method in Java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//n is the number of height
int n = in.nextInt();
int j = 0;
int k = 0;
for (int i = 0; i < n; i++)
{
//print out spaces
while(j < n - i)
{
System.out.print(" ");
j++;
}
while(k < (n - j + 1))
{
System.out.print("#");
k++;
}
System.out.println();
j = 0;
k = 0;
}
}
You are printing space for the last line also.
You can replace space with some other visible character and check output.
Here is accepted solution.
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 n = in.nextInt();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(j>=n-i+1)
System.out.print("#");
else System.out.print(" ");
}
System.out.println();
}
}
}
You can try with this code. It's gathering the whole string and printing it at the end.
static void Main(string[] args)
{
int _n;
_n = Convert.ToInt32(Console.ReadLine());
StairCase(_n);
}
static void StairCase(int n)
{
string s = "";
if (n > 0 && n < 101)
{
for (int i = 0; i < n; i++)
{
s = StairCase(s, i + 1);
if (i + 1 < n)
{
s += string.Format("\n");
}
}
}
Console.WriteLine(s);
Console.ReadLine();
}
private static string StairCase(string s, int n)
{
int c = n;
while (c > 0)
{
s += string.Format("#");
c = c - 1;
}
return s;
}

Categories

Resources