Exception in thread "main" java.lang.NullPointerException - java

I started to learn java yesterday and I wrote the followind program which should print pairs of equal numbers, but when I run it I get
Exception in thread "main" java.lang.NullPointerException
at _aaaa.main(_aaaa.java:26)
Here is my program:
import java.util.*;
class pair {
int first, second;
pair() {
first = second = 0;
}
public void make_pair(int a, int b)
{
first = a;
second = b;
}
}
public class aaaa {
public static void main(String[] idontneedthis)
{
Scanner input = new Scanner(System.in);
int N = input.nextInt(), i, lg = 0;
int[] A = new int[5010];
pair[] B = new pair[5010];
for (N <<= 1, i = 1; i <= N; ++i)
{
int var = input.nextInt();
if (A[var] > 0)
{
B[++lg].make_pair(A[var], var);
A[var] = 0;
}
else
{
A[var] = i;
}
}
if (lg == 0) System.out.print("-1");
for (i = 1; i <= lg; ++i)
{
System.out.print(B[i].first + " " + B[i].second + "\n");
}
}
}
Please tell me what is wrong or why do I get this error. I mention that if I cut the line 26 ( B[++lg].make_pair(A[var], var); ) it will write -1.
Thank you!

You need to initialise the pairs in your array:
if (A[var] > 0) {
B[++lg] = new pair(); //here
B[lg].make_pair(A[var], var);
A[var] = 0;
}
This line:
pair[] B = new pair[5010];
creates an array of 5010 pairs but until you initialise them, they are all null.
Also note that since 5010 and N are not related, you could get an ArrayIndexOutOfBoundException depending on N.

This is how I would write it. The less said the better ;)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Pair {
final int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
#Override
public String toString() {
return first + " " + second;
}
}
public class Main {
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
int numOfPairs = input.nextInt();
List<Pair> pairs = new ArrayList<Pair>();
for(int i = 0; i < numOfPairs;i++) {
int first = input.nextInt();
int second = input.nextInt();
pairs.add(new Pair(first, second));
}
for (Pair pair : pairs)
System.out.println(pair);
}
}

pair[] B = new pair[5010];
Only allocates the space for 5010 B elements. You need to instantiate each element in that array.
for(int i = 0; i <B.length;i++)
{
B[i] = new pair();
}
Style things:
Class names start with upper case letters: AAAA not aaaa.
also star imports are bad:
import java.util.*;
replace with:
import java.util.Scanner;

Related

Get value from HashMap by key

I need to compare the roman letters and get the correct integer out of it.
If I'm correct, there should be a way to compare the hashmap key with the arraylist element and if they match, get the associated value from the key.
The return 2020 is there just for test purposes, since I wrote a JUnit test in a different class. It can be ignored for now.
I hope someone could give me a hint, since I wouldn't like to use the solutions from the web, because I need to get better with algorithms.
package com.company;
import java.util.*;
public class Main {
static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>();
static {
romanNumbers.put("I", 1);
romanNumbers.put("V", 5);
romanNumbers.put("X", 10);
romanNumbers.put("L", 50);
romanNumbers.put("C", 100);
romanNumbers.put("D", 500);
romanNumbers.put("M", 1000);
}
public static void main(String[] args) {
romanToArabic("MMXX");
}
static int romanToArabic(String roman) {
ArrayList romanLetters = new ArrayList();
roman = roman.toUpperCase();
for (int i = 0; i < roman.length(); i++) {
char c = roman.charAt(i);
romanLetters.add(c);
}
// [M, M, X, X]
System.out.println(romanLetters);
// iterates over the romanLetters
for (int i = 0; i < romanLetters.size(); i++) {
System.out.println(romanLetters.get(i));
}
// retrive keys and values
for (Map.Entry romanNumbersKey : romanNumbers.entrySet()) {
String key = (String) romanNumbersKey.getKey();
Object value = romanNumbersKey.getValue();
System.out.println(key + " " + value);
}
return 2020;
}
}
You could just Map.get each array element.
package com.company;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
static HashMap<String, Integer> romanNumbers = new HashMap<String, Integer>();
static {
romanNumbers.put("I", 1);
romanNumbers.put("V", 5);
romanNumbers.put("X", 10);
romanNumbers.put("L", 50);
romanNumbers.put("C", 100);
romanNumbers.put("D", 500);
romanNumbers.put("M", 1000);
}
public static void main(String[] args) {
System.out.println(romanToArabic("MMXX"));
}
static int romanToArabic(String roman) {
ArrayList romanLetters = new ArrayList();
roman = roman.toUpperCase();
for (int i = 0; i < roman.length(); i++) {
char c = roman.charAt(i);
romanLetters.add(c);
}
// [M, M, X, X]
System.out.println(romanLetters);
// iterates over the romanLetters
int sum = 0;
for (int i = 0; i < romanLetters.size(); i++) {
String key = String.valueOf(romanLetters.get(i));
if (romanNumbers.containsKey(key)) {
sum += romanNumbers.get(key);
}
}
return sum;
}
}
As stated in the comments, this just answers your question of how to get values from an hashmap where keys are the array elements. It is not a solution to calculate the numeric value out of a roman number. For that, you will have to look at the next letter, and join if it is larger, before consulting the map for the final value to sum.
I'd like to suggest a completly different approach using an enum.
public enum RomanNumber {
I(1), V(5), X(10), L(50), C(100), D(500), M(1000);
private final int arabic;
RomanNumber(int arabic) {
this.arabic = arabic;
}
public int getArabicNumber() {
return arabic;
}
// This is obviously broken. IV wouldn't work for example.
public static int toArabic(String romanLetters) {
romanLetters = romanLetters.toUpperCase();
int arabicResult = 0;
for (int i = 0; i < romanLetters.length(); i++) {
char romanNumber = romanLetters.charAt(i);
// valueOf(String) returns the enum based on its name. So a String of "I" returns the RomanNumber I enum.
int arabicNumber = valueOf(String.valueOf(romanNumber)).getArabicNumber();
arabicResult = arabicResult + arabicNumber;
}
return arabicResult;
}
}
Can be used like this:
String romanNumber = "MMXX";
System.out.println(RomanNumber.toArabic(romanNumber));
Btw. every enum has an ordinal() method which returns the declaration position inside the enum. (I.ordinal() == 1 or V.ordinal() == 2) I think this could help you with the IV problem aswell. :)

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

How to efficiently implement Eratosphenes method to generate prime numbers?

I use the following components in my code:
A byte array, each bit representing whether the correspondent number is prime(0) or not(1)
A recursion of Filtering.filter()
I want to ascertain whether these parts make it more efficient or actually slow it down. Any other advices also appreciated.
Code:
import java.lang.Math;
import java.util.*;
class Container{
public final byte[] binary_array;
private final int bit_length;
public Container(int nominal_bit_length){
int byte_length = (int)Math.ceil(nominal_bit_length / 8.0);
this.binary_array = new byte[byte_length];
this.bit_length = 8 * byte_length;
}
private String toBinaryString(int index){//convert into a binary string the byte value on which the bit number refered by the index exists
int byte_index = index / 8;
//System.out.println(index);
String str = Integer.toBinaryString(this.binary_array[byte_index]);
String formatted = ("00000000" + str).substring(str.length());
return formatted;
}
public char get(int index){
String str = this.toBinaryString(index);
return str.charAt(index % 8);//
}
public char set(int index, char value){
StringBuilder str = new StringBuilder(this.toBinaryString(index));
char temp = str.charAt(index % 8);//
str.setCharAt(index % 8, value);//
int byte_index = index / 8;
this.binary_array[byte_index] = (byte)Integer.parseUnsignedInt(str.toString(), 2);
return temp;
}
public int length(){
return this.bit_length;
}
public static Container preset(){
Container c = new Container(8);
c.set(1-1, '1');
c.set(4-1, '1');
c.set(6-1, '1');
c.set(8-1, '1');
return c;
}
}
class Screener{
private static void filterMultiplesOf(int num, Container container){
if (num == 1){
return;
}
int i = 2;
while ((i * num - 1) < container.length()){
container.set(i * num - 1, '1');
i++;
}
}
public static void filter(Container c){
int num = c.length();
if (num <= 8){
c = Container.preset();
} else{
Container base = new Container((int)Math.floor(Math.sqrt(num)));
filter(base);
for (int i = 0; i < base.length(); i++){
if (base.get(i) == '0'){
filterMultiplesOf(i+1, c);
}
}
}
}
}
public class Prime2{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
Container c = new Container(num);
Screener.filter(c);
for (int i = 1; i < c.length(); i++){
if (c.get(i) == '0'){
System.out.print((i + 1) + " ");
}
}
}
}
Edit at 12-03-2014:
What about this segment code?
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class PrimeGenerator {
public static Set<Integer> prime(int num){
if (num <= 2){
Set<Integer> foo = new HashSet<>();
foo.add(2);
return foo;
}
IntStream stream = IntStream.rangeClosed(1, num);
Set<Integer> base = prime((int)Math.ceil(Math.sqrt(num)));
IntStream multiples = base.stream().flatMapToInt((factor) -> (IntStream.rangeClosed(2, (int)Math.floorDiv(num, factor)).map(n -> n * factor)));
Set<Integer> primeset = stream.collect(HashSet::new, HashSet::add, HashSet::addAll);
Set<Integer> nonprimeset = multiples.collect(HashSet::new, HashSet::add, HashSet::addAll);
primeset.removeAll(nonprimeset);
primeset.remove(1);
return primeset;
}
public static void main(String[] args) {
// TODO code application logic here
prime(100000).stream().map(num -> num + " ").forEach(System.out::print);
}
}
as well as this:
import java.lang.Math;
import java.util.*;
/**
* Variation of BitSet which does NOT interpret the highest bit synonymous with
* its length.
*
* #author casper.bang#gmail.com
*/
class FixedBitSet extends BitSet{
int fixedLength;
public FixedBitSet(int fixedLength){
super(fixedLength);
this.fixedLength = fixedLength;
}
#Override
public int length() {
return fixedLength;
}
}
class Screener{
private static FixedBitSet preset;
static{
preset = new FixedBitSet(4);
preset.set(1-1, true);
preset.set(4-1, true);
}
private static void filterMultiplesOf(int num, FixedBitSet bitset){
//System.out.println("--------");
if (num == 1){
return;
}
int i = 2;
while ((i * num - 1) < bitset.length()){
bitset.set(i * num - 1, true);
i++;
}
}
public static void filter(FixedBitSet bitset){
//System.out.println("--------");
int num = bitset.length();
if (num <= 4){
//System.out.println("--------");
bitset = preset;
} else{
FixedBitSet base = new FixedBitSet((int)Math.floor(Math.sqrt(num)));
filter(base);
for (int i = 0; i < base.length(); i++){
if(!base.get(i)){
filterMultiplesOf(i + 1, bitset);
}
}
}
}
}
public class Prime3{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
FixedBitSet bs = new FixedBitSet(num);
// System.out.println(bs.length());
Screener.filter(bs);
for (int i = 1; i < bs.length(); i++){
if(!bs.get(i)){
System.out.print((i + 1) + " ");
}
}
}
}
Your "efficient" usage of a byte array is immaterial to the bad performance of your code, which uses string building to implement getting and setting.
Instead write code which uses low-level bit-manipulation operators (such as ~, &, and |) to implement get and set.
If you're not up to that, then consider using BitSet, a JDK-provided class which serves the same purpose.
If you want to learn how it's done, then simply open BitSet's source code.

Given a target sum, find if there is a pair of element in the given array which sums up to it

import java.util.HashMap;
public class target
{
public static void hash(int []a,int sum)
{
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int i;
for (i = 0; i < a.length; ++i)
map.put(a[i], sum-a[i]);
for (i = 0; i < a.length; ++i)
if(map.containsValue(a[i]) && map.get(a[i])!=null)
{
System.out.println("("+a[i]+","+map.get(a[i])+")");
map.remove(a[i]);
}
}
public static void main(String[] args)
{
int []a={1, 2, 13, 34, 9, 3, 23, 45, 8, 7, 8, 3, 2};
hash(a,11);
}
}
I want to know if there is a better and more efficient solution that the above one. Complexity of this is n. Can I do better?
Your implementation misses duplicated pairs.
You could
sort the array
iterate from the start and for each element
calculate the required complement (sum - element)
do a reverse binary search (from the end of the sorted array) looking for that precise value
if found, remove both
It boils down to the observation that, with elements sorted:
n1 < n2 < n3 < n4 < n5 < n6
the most likely pairs are coming symmetrically from both ends to the middle. Now, the worst case is still bad, but at least you don't have the hashtable overhead
As I commented, your sollution is not O(N), because the containsValue make a search of all values stored at the HashMap. To solve it, I made a different approach using your solution:
public static void newVersion(int[] a, int sum){
HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
for (int i= 0; i< a.length; i++) {
map.put(sum - a[i], true);
}
for (int i = 0; i < a.length; i++) {
if (map.containsKey(a[i]) && map.get(a[i])) {
System.out.println("("+(sum-a[i])+","+a[i]+")");
map.put(a[i], false);
map.put(sum-a[i], false);
}
}
}
At the first step, it stores the "complement value" of each integer and at the second step it checks if the complement exists. If it exists, mark both pair as used.
This complexity is:
* O(N) for the first looping
* O(N) * (O(1) + O(1)) for the second loop and the containsValue and get.
* Finally: O(N) + O(N) .:. O(N) solution,
I have the following solution for this problem. The time complexity should be O(N) because the HashMap operations put, get and keySet are O(1).
import java.util.HashMap;
import java.util.Map;
/**
* Find a pair of numbers in an array given a target sum
*
*
*/
public class FindNums {
public static void findSumsForTarget(int[] input, int target)
{
// just print it instead of returning
Map<Integer, String> myMap = populateMap(input);
// iterate over key set
for (Integer currKey : myMap.keySet()) {
// find the diff
Integer diff = target - currKey;
// check if diff exists in the map
String diffMapValue = myMap.get(diff);
if(diffMapValue!=null)
{
// sum exists
String output = "Sum of parts for target " + target + " are " + currKey + " and " + diff;
System.out.println(output);
return; // exit; we're done - unless we wanted all the possible pairs and permutations
}
// else
// keep looking
}
System.out.println("No matches found!");
}
private static Map<Integer, String> populateMap(int[] input)
{
Map<Integer,String> myMap = new HashMap<Integer,String>();
for (int i = 0; i < input.length; i++) {
String currInputVal = myMap.get(input[i]);
if(currInputVal!=null) // value already exists
{
// append current index location to value
currInputVal = currInputVal + ", " + i;
// do a put with the updated value
myMap.put(input[i], currInputVal);
}
else
{
myMap.put(input[i], Integer.toString(i)); // first argument is autoboxed to Integer class
}
}
return myMap;
}
// test it out!
public static void main(String[] args)
{
int[] input1 = {2,3,8,12,1,4,7,3,8,22};
int[] input2 = {1,2,3,4,5,6,7,8,9,10};
int[] input3 = {2,-3,8,12,1,4,7,3,8,22};
int target1 = 19;
int target2 = 16;
// test
FindNums.findSumsForTarget(input1, target1);
FindNums.findSumsForTarget(input1, -1);
FindNums.findSumsForTarget(input2, target2);
FindNums.findSumsForTarget(input3, target1);
}
}
import java.util.*;
import java.io.*;
class hashsum
{
public static void main(String arg[])throws IOException
{
HashMap h1=new HashMap();
h1.put("1st",new Integer(10));
h1.put("2nd",new Integer(24));
h1.put("3rd",new Integer(12));
h1.put("4th",new Integer(9));
h1.put("5th",new Integer(43));
h1.put("6th",new Integer(13));
h1.put("7th",new Integer(5));
h1.put("8th",new Integer(32));
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no.");
int no=Integer.parseInt(br.readLine());
Iterator i=h1.entrySet().iterator();
boolean flag=false;
while(i.hasNext())
{
Map.Entry e1=(Map.Entry)i.next();
Integer n1=(Integer)e1.getValue();
Iterator j=h1.entrySet().iterator();
while(j.hasNext())
{
Map.Entry e2=(Map.Entry)j.next();
Integer n2=(Integer)e2.getValue();
if(no==(n1+n2))
{
System.out.println("Pair of elements:"+n1 +" "+n2);
flag=true;
}
}
}
if(flag==false)
System.out.println("No pairs");
}
}
public static void hash1(int[] a, int num) {
Arrays.sort(a);
// printArray(a);
int top = 0;
int bott = a.length - 1;
while (top < bott) {
while (a[bott] > num)
bott--;
int sum = a[top] + a[bott];
if (sum == num) {
System.out.println("Pair " + a[top] + " " + a[bott]);
top++;
bott--;
}
if (sum < num)
top++;
if (sum > num)
bott--;
}
}
Solution: O(n) time and O(log(n)) space.
public static boolean array_find(Integer[] a, int X)
{
boolean[] b = new boolean[X];
int i;
for (i=0;i<a.length;i++){
int temp = X-a[i];
if(temp >= 0 && temp < X) //make sure you are in the bound or b
b[temp]=true;
}
for (i=0;i<a.length;i++)
if(a[i]<X && b[a[i]]) return true;
return false;
}
Recursively to find the subset whose sum is the targeted sum from given array.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static Set<List<Integer>> set = new HashSet<>();
public static void main(String[] args) {
int[] biggerArray = {1, 2, 1, 1};
int targetedSum = 3;
findSubset(biggerArray, targetedSum);
}
public static void findSubset(int[] biggerArray, int targetedSum) {
for (int i = 0; i < biggerArray.length; i++) {
List<Integer> subset = new ArrayList<>();
if (biggerArray[i] > targetedSum)
continue;
else
subset.add(biggerArray[i]);
if (i + 1 < biggerArray.length)
find(subset, i, biggerArray, targetedSum, i);
}
System.out.println(set);
}
public static List<Integer> find(List<Integer> subset, int startIndex, final int[] biggerArray, final int targetedSum, final int skipIndex) {
if (skipIndex == startIndex) {
find(subset, startIndex + 1, biggerArray, targetedSum, skipIndex);
return null;
}
int subsetSum = findSumOfList(subset);
int remainedSum = targetedSum - subsetSum;
int i = startIndex;
if (remainedSum == 0) {
set.add(subset);
return null;
}
if ((startIndex < biggerArray.length) && (biggerArray[startIndex] == remainedSum)) {
List<Integer> temp = new ArrayList<Integer>(subset);
temp.add(biggerArray[i]);
set.add(temp);
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] < remainedSum)) {
while (i + 1 <= biggerArray.length) {
List<Integer> temp = new ArrayList<Integer>(subset);
if (i != skipIndex) {
temp.add(biggerArray[i]);
find(temp, ++i, biggerArray, targetedSum, skipIndex);
}
else {
i = i + 1;
}
}
}
else if ((startIndex < biggerArray.length) && (biggerArray[startIndex] > remainedSum)) {
find(subset, ++i, biggerArray, targetedSum, skipIndex);
}
return null;
}
public static int findSumOfList(List<Integer> list) {
int i = 0;
for (int j : list) {
i = i + j;
}
return i;
}
}
We need not have two for loops. The match can be detected in the same loop while populating the map it self.
public static void matchingTargetSumPair(int[] input, int target){
Map<Integer, Integer> targetMap = new HashMap<Integer, Integer>();
for(int i=0; i<input.length; i++){
targetMap.put(input[i],target - input[i]);
if(targetMap.containsKey(target - input[i])){
System.out.println("Mathcing Pair: "+(target - input[i])+" , "+input[i]);
}
}
}
public static void main(String[] args) {
int[] targetInput = {1,2,4,5,8,12};
int target = 9;
matchingTargetSumPair(targetInput, target);
}
We can easily find if any pair exists while populating the array itself. Use a hashmap and for every input element, check if sum-input difference element exists in the hashmap or not.
import java.util.*;
class findElementPairSum{
public static void main(String[] args){
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sum key: ");
int sum=sc.nextInt();
for(int i=0; i<10; i++){
int x = sc.nextInt();
if(!hm.containsKey(sum-x)){
hm.put(x, 1);
} else {
System.out.println("Array contains two elements with sum equals to: "+sum);
break;
}
}
}
}

Uva's 3n+1 problem

I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}

Categories

Resources