Java program not outputting negative integers from array? - java

One of my Java assignments is to take numbers from a file and then seperate them to two arrays. One named P (positive numbers) and N (negative numbers.) I have it working for the positive numbers but the negative numbers keep outputting 0s. I have no idea why! Help?
import java.io.*;
import java.util.*;
public class Prog404a {
public static void main(String[] args) {
Scanner inFile = null;
try {
inFile = new Scanner(new File("prg404a1.dat"));
} catch (FileNotFoundException e) {
System.out.println("File not found!!");
System.exit(0);
}
int temp = 0;
int P[] = new int[23];
int N[] = new int[23];
int i = 0;
while (inFile.hasNext()) {
temp = inFile.nextInt();
if (temp < 0) {
N[i] = temp;
}
if (temp > 0) {
P[i] = temp;
}
i++;
}
for (int x = 0; x < i; x++) {
System.out.println(P[x] + "\t" + N[x]);
}
}
}
EDIT: Never mind it's not working for positive numbers either. Only a few.

Maybe you are just not counting right?
You should be using two counters, one for positive, one for negative numbers.
Otherwise, half of the entries will obviously be 0, because they were never set.

Related

Why does this binary search code give wrong output on Eclipse IDE?

Why does this binary search code give wrong output on Eclipse IDE but gets accepted when submitted to Coursera? This is a sample input for which it shows the wrong output.
Sample Input:
5 3 2 4 1 5
3 1 2 7
Output:
-1 -1 -1
Clearly, the element '1' is present is the input array. But the output for that is -1 instead of 3.
import java.io.*;
import java.util.*;
public class BinarySearch {
static int binarySearch(int[] a,int l,int r,int x) {
//write your code here
if(l<=r){
int mid =l + (r - l)/2;
if(x==a[mid])
return mid;
else if(x<a[mid]){
return binarySearch(a,l,mid-1,x);
}
else
return binarySearch(a,mid+1,r,x);
}
return -1;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
int m = scanner.nextInt();
int[] b = new int[m];
for (int i = 0; i < m; i++) {
b[i] = scanner.nextInt();
}
for (int i = 0; i < m; i++) {
//replace with the call to binarySearch when implemented
System.out.print(binarySearch(a,0,n-1,b[i]) + " ");
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
Actually, the problem is with your input data and not the code itself. If you search information about binary search you can find: "binary search is a search algorithm that finds the position of a target value within a sorted array". Your input isn't sorted.
You would have to sort the array before running the search which would be a bad idea - searching with other algorithm would take less time than sorting.
If you try to input sorted data, eg.:
5 1 2 3 4 5
3 1 2 7
The result will be 0 1 -1 - just as expected.

Getting TLE in CodeChef and need for improvement of code

I am trying to solve a practice question of CodeChef . In this problem we are given N numbers Ai...An and we first have to sort(ascending order) the numbers and then add the alternate numbers starting from the last and show the output for each test cases , the test cases has 2 parts :
1>Constraints :
1 ≤ Ai ≤ 109
1 ≤ N ≤ 1000
2>Constraints:
1 ≤ Ai ≤ 109
1 ≤ N ≤ 105
You can see the full problem here.
The first part of my problem was successfully submitted but second part showed NZEC because I was using long to add those numbers(which was beyond that range). So I decided to use Strings to add up my numbers here is the method :
public static String myStringWayToAdd(String first , String second){
String temp = "";
if(first.length() < second.length()){
temp = first;
first = second;
second = temp;
}
temp = "";
int carry = 0;
for(int i=1;i<=first.length();++i){
if(i <= second.length()){
carry += Integer.parseInt(first.charAt(first.length()-i)+"") + Integer.parseInt(second.charAt(second.length()-i)+"");
}
else{
carry += Integer.parseInt(first.charAt(first.length()-i)+"");
}
temp += carry%10;
carry = carry/10;
}
if(carry != 0)
temp += carry;
StringBuilder myResult = new StringBuilder(temp);
return(myResult.reverse().toString());
}
But now it shows TLE(Time Limit Expire) , So then I thought to use BigInteger(which I am not pretty much Aware of but I saw some tutorials) :
BigInteger big = new BigInteger("0");
big = big.add(BigInteger.valueOf(mySort.get(j))); //for addition and mySort is my ArrayList
But this gave me NZEC I don't know whywell now I want to use double variable but there is a problem with that too, because with double large numbers will be in form of exponential value like :
1.243536E15 which will not be accepted by the machine, so is there any good way to solve this problem and not getting any Time Limit Expiry?.
Any help will really be appreciated. Thank you in Advance.
Edit 1 :
I changed baxck the variable to long and run and this time strangely I got TLE here is my code :
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.math.BigInteger;
import java.lang.Number;
class CFEA{
public static void main(String[] s){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
for(int i = 0 ; i<testCases;++i){
long sum = 0;
//BigInteger big = new BigInteger("0");
ArrayList<Integer> mySort = new ArrayList<Integer>();
int n = scan.nextInt();
for(int j = 1 ; j <= n ; ++j){
mySort.add(scan.nextInt());
}
Collections.sort(mySort);
for(int j = mySort.size()-1 ; j >= 0 ; j=j-2){
sum += mySort.get(j);
}
System.out.println(sum);
}
}
}
And here is Link to my submission.Is there Anything I can optimize in my code?
The sum of all number is at most 10^9 * 10^5 = 10^14. It is small enough to fit into long. There is no need to use BigInteger.
java.util.Scanner has performance issues. You can implement a custom scanner(using BufferedReader) to speed up your code.
Here is my implementation of a scanner:
import java.io.*;
import java.util.StringTokenizer;
public class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = reader.readLine();
if (line == null)
throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public void close() {
try {
reader.close();
} catch (IOException e) {
//ignore
}
}
}
I did some changes in my Program and it was All Accepted a much relief after submitting for about 20 times , here is my new code :
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
class CFEA{
public static void main(String[] s){
Scanner scan = new Scanner(System.in);
byte testCases = Byte.parseByte(scan.nextLine()); //used byte for test cases instead of int
for(int i = 0 ; i<testCases;++i){
long sum = 0;
//BigInteger big = new BigInteger("0");
ArrayList<Integer> mySort = new ArrayList<Integer>();
int n = Integer.parseInt(scan.nextLine());
String input = scan.nextLine();
String[] my = input.split(" ");
for(String myString : my){
mySort.add(Integer.parseInt(myString));
}
Collections.sort(mySort);
for(int j = mySort.size()-1 ; j >= 0 ; j=j-2){
sum += mySort.get(j);
}
System.out.println(sum);
}
}
}
I think the main villain was that I was scanning for Integers N number of times as in this :
for(int j = 1 ; j <= n ; ++j){
mySort.add(scan.nextInt());
}
When N was something Like 100000 then this really slows it down.So i used 1 String for complete line and then Split it into Integers using split method as in :
String input = scan.nextLine(); //only 1 Scanner
String[] my = input.split(" ");
for(String myString : my){
mySort.add(Integer.parseInt(myString));
}
Although My code got submitted I still think there is Further scope for optimization , so please do answer if you have something better

java display method

Here im required to Write a method printArray that displays the contents of the array num and Display the contents of the array with each
number separated by a space. and i have to start a new line after every 20 elements.
i wrote this code but whenever i try to execute it, it shows the array without the new line
public class project2 {
public static void main(String[] args) {
int num []= new int [100];
for (int i=0;i<num.length;i++){
num[i]=-1;
num[7]=7;
}
printArray(num);
System.out.println(num);
}
public static void printArray (int array1[]){
int count =20;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (array1[x]==count){
System.out.println(" ");
count=array1[x]+count;
}
}
}
}
import java.util.Arrays;
import java.util.Random;
public class project2 {
public static void main(String[] args) {
int num[] = new int[100];
Random random = new Random();
for (int i = 0; i < num.length; i++) {
num[i] = random.nextInt(100);
}
printArray(num);
System.out.println('\n' + Arrays.toString(num));
}
public static void printArray(int array1[]) {
int count = 20;
for (int i = 0; i < array1.length; i++) {
System.out.printf("%2d ", array1[i]);
if ((i + 1) % count == 0) {
System.out.println("");
}
}
}
}
You should use the modulo (or remainder) operator (%), that suits your usage much better:
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (x>0 && (x%count)==0){
System.out.println(" ");
}
}
This way, you will get a new line every count characters, and the first line will not have it (that is why the x>0 check is there).
Also, in the original post, this line is frankly totally bad:
count=array1[x]+count;
Just what would it do? Why do you add the value stored in the array to the fixed counter? Considering this line, I advise that you should really sit back a bit, and try to think about how things work in the background... There is no magic!
Take a closer look at your if-statement:
if (array1[x]==count)
According to your array values, this will never return true
i have to start a new line after every 20 elements.
Change to following code:
if (x%20 == 0)
{
System.out.println();
}
in place of
if (array1[x]==count)
{
System.out.println(" ");
count=array1[x]+count;
}
Problem is with
if (array1[x]==count)
You are comparing count with value present in array. Instead compare it with desired count ie 20 or Use modulo operator as suggested in other answers / comments .
int count = 1;
for (int x=0;x<array1.length;x++){
System.out.print(array1[x]+" ");
if (count == 20){ // Check if its 20th element
System.out.println(" ");
count=1; // reset count
}
count++;
}

interviewstreet.com - String similarity

I'm trying to solve the string similarity question on interviewstreet.com. My code is working for 7/10 cases (and it is exceeding the time limit for the other 3).
Here's my code -
public class Solution {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String v1 = user_input.next();
int number_cases = Integer.parseInt(v1);
String[] cases = new String[number_cases];
for(int i=0;i<number_cases;i++)
cases[i] = user_input.next();
for(int k=0;k<number_cases;k++){
int similarity = solve(cases[k]);
System.out.println(similarity);
}
}
static int solve(String sample){
int len=sample.length();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(sample.charAt(j-i)==sample.charAt(j))
sim++;
else
break;
}
}
return sim;
}
}
Here's the question -
For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.
Calculate the sum of similarities of a string S with each of it's suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.
Output:
Output T lines containing the answer for the corresponding test case.
Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.
Sample Input:
2
ababaa
aa
Sample Output:
11
3
Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.
For the second case, the answer is 2 + 1 = 3.
How can I improve the running speed of the code. It becomes harder since the website does not provide a list of test cases it uses.
I used char[] instead of strings. It reduced the running time from 5.3 seconds to 4.7 seconds and for the test cases and it worked. Here's the code -
static int solve(String sample){
int len=sample.length();
char[] letters = sample.toCharArray();
int sim=0;
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
if(letters[j-i]==letters[j])
sim++;
else
break;
}
}
return sim;
}
used a different algorithm. run a loop for n times where n is equals to length the main string. for each loop generate all the suffix of the string starting for ith string and match it with the second string. when you find unmatched character break the loop add j's value to counter integer c.
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Solution {
public static void main(String args[]) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(in.readLine());
for (int i = 0; i < T; i++) {
String line = in.readLine();
System.out.println(count(line));
}
}
private static int count(String input) {
int c = 0, j;
char[] array = input.toCharArray();
int n = array.length;
for (int i = 0; i < n; i++) {
for (j = 0; j < n - i && i + j < n; j++)
if (array[i + j] != array[j])
break;
c+=j;
}
return c;
}
}
I spent some time to resolve this question, and here is an example of my code (it works for me, and pass thru all the test-cases):
static long stringSimilarity(String a) {
int len=a.length();
char[] letters = a.toCharArray();
char localChar = letters[0];
long sim=0;
int sameCharsRow = 0;
boolean isFirstTime = true;
for(int i=0;i<len;i++){
if (localChar == letters[i]) {
for(int j = i + sameCharsRow;j<len;j++){
if (isFirstTime && letters[j] == localChar) {
sameCharsRow++;
} else {
isFirstTime = false;
}
if(letters[j-i]==letters[j])
sim++;
else
break;
}
if (sameCharsRow > 0) {
sameCharsRow--;
sim += sameCharsRow;
}
isFirstTime = true;
}
}
return sim;
}
The point is that we need to speed up strings with the same content, and then we will have better performance with test cases 10 and 11.
Initialize sim with the length of the sample string and start the outer loop with 1 because we now in advance that the comparison of the sample string with itself will add its own length value to the result.
import java.util.Scanner;
public class StringSimilarity
{
public static void main(String args[])
{
Scanner user_input = new Scanner(System.in);
int count = Integer.parseInt(user_input.next());
char[] nextLine = user_input.next().toCharArray();
try
{
while(nextLine!= null )
{
int length = nextLine.length;
int suffixCount =length;
for(int i=1;i<length;i++)
{
int j =0;
int k=i;
for(;k<length && nextLine[k++] == nextLine[j++]; suffixCount++);
}
System.out.println(suffixCount);
if(--count < 0)
{
System.exit(0);
}
nextLine = user_input.next().toCharArray();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Which is the most efficient way of taking input in Java?

I am solving this question.
This is my code:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] t = new int[n];
int count = 0;
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
if (t[i] % k == 0) {
count++;
}
}
System.out.println(count);
}
}
But when I submit it, it get's timed out. Please help me optimize this to as much as is possible.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
They say :
You are expected to be able to process
at least 2.5MB of input data per
second at runtime.
Modified CODE
Thank you all...I modified my code and it worked...here it is....
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int k = Integer.parseInt(input[1]);
int count = 0;
for (int i = 0; i < n; i++) {
if (Integer.parseInt(br.readLine()) % k == 0) {
count++;
}
}
System.out.println(count);
}
regards
shahensha
This could be slightly faster, based on limc's solution, BufferedReader should be faster still though.
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
while (true) {
try {
if (sc.nextInt() % k == 0) {
count++;
}
} catch (NoSuchElementException e) {
break;
}
}
System.out.println(count);
}
}
How about this?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
if (sc.nextInt() % k == 0) {
count++;
}
}
System.out.println(count);
You may consider reading big chunks of input and then get the numbers from there.
Other change is, you may use Integer.parseInt() instead of Scanner.nextInt() although I don't know the details of each one, somethings tells me Scanner version performs a bit more computation to know if the input is correct. Another alternative is to convert the number yourself ( although Integer.parseInt should be fast enough )
Create a sample input, and measure your code, change a bit here and there and see what the difference is.
Measure, measure!
BufferedReader is supposed to be faster than Scanner. You will need to parse everything yourself though and depending on your implementation it could be worse.

Categories

Resources