I am solving the Acode problem of SPOJ.It is a simple Dp problem here
This is my solution:
//http://www.spoj.com/problems/ACODE/
import java.util.Scanner;
//import java.util.Math;
public class Acode {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String encodedString = sc.next();
while (!encodedString.equals("0")) {
long number = numOfDecodings(encodedString);
System.out.println(number);
encodedString = sc.next();
}
return;
}
public static long numOfDecodings(String encodedString)
{
int lengthOfString = encodedString.length();
long decode[] = new long[lengthOfString];
decode[0] = 1;
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
for (int i=2; i<lengthOfString; i++) {
if (isCurrentTwoDigitsValid(encodedString, i)) {
decode[i] = decode[i-2] + decode[i-1];
} else {
decode[i] = decode[i-1];
}
}
return decode[lengthOfString-1];
}
public static boolean isCurrentTwoDigitsValid(String encodedString, int startIndex)
{
char c1 = encodedString.charAt(startIndex);
char c2 = encodedString.charAt(startIndex-1);
if ( (c2=='1') || (c2=='2' && c1<='6')) {
return true;
} else {
return false;
}
}
}
But I am getting an NZEC error when I try to submit it.I tested it for large values too and it is not breaking.I am not understanding how else to improve it.
When input size is 1 you get an error in
if (isCurrentTwoDigitsValid(encodedString, 1)) {
decode[1] = 2;
} else {
decode[1] = 1;
}
because of accessing out of the decode array bounds.
You treat 0 as a valid number, but it's not. For example, the correct answer for input "10" is 1, not 2.
Related
We define balanced number as number which has the same number of even and odd dividers e.g (2 and 6 are balanced numbers). I tried to do task for polish SPOJ however I always exceed time.
The task is to find the smallest balance number bigger than given on input.
There is example input:
2 (amount of data set)
1
2
and output should be:
2
6
This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
private static final BigDecimal TWO = new BigDecimal("2");
public static void main(String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
int numberOfAttempts = in.nextInt();
for (int i = 0; i < numberOfAttempts; i++) {
BigDecimal fromNumber = in.nextBigDecimal();
findBalancedNumber(fromNumber);
}
}
private static boolean isEven(BigDecimal number){
if(number.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0){
return false;
}
return true;
}
private static void findBalancedNumber(BigDecimal fromNumber) {
BigDecimal potentialBalancedNumber = fromNumber.add(BigDecimal.ONE);
while (true) {
int evenDivider = 0;
int oddDivider = 1; //to not start from 1 as divisor, it's always odd and divide potentialBalancedNumber so can start checking divisors from 2
if (isEven(potentialBalancedNumber)) {
evenDivider = 1;
} else {
oddDivider++;
}
for (BigDecimal divider = TWO; (divider.compareTo(potentialBalancedNumber.divide(TWO)) == -1 || divider.compareTo(potentialBalancedNumber.divide(TWO)) == 0); divider = divider.add(BigDecimal.ONE)) {
boolean isDivisor = potentialBalancedNumber.remainder(divider).compareTo(BigDecimal.ZERO) == 0;
if(isDivisor){
boolean isEven = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) == 0;
boolean isOdd = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0;
if (isDivisor && isEven) {
evenDivider++;
} else if (isDivisor && isOdd) {
oddDivider++;
}
}
}
if (oddDivider == evenDivider) { //found balanced number
System.out.println(potentialBalancedNumber);
break;
}
potentialBalancedNumber = potentialBalancedNumber.add(BigDecimal.ONE);
}
}
}
It seems to work fine but is too slow. Can you please help to find way to optimize it, am I missing something?
As #MarkDickinson suggested, answer is:
private static void findBalancedNumberOptimized(BigDecimal fromNumber) { //2,6,10,14,18,22,26...
if(fromNumber.compareTo(BigDecimal.ONE) == 0){
System.out.println(2);
}
else {
BigDecimal result = fromNumber.divide(new BigDecimal("4")).setScale(0, RoundingMode.HALF_UP).add(BigDecimal.ONE);
result = (TWO.multiply(result).subtract(BigDecimal.ONE)).multiply(TWO); //2(2n-1)
System.out.println(result);
}
}
and it's finally green, thanks Mark!
I am writing a java code to Change a number from decimal base to another base.
But I don't know why the program runs wrong. I think the error comes from function Prin_as. Can anyone tell me why ?
Below is my code,
import java.util.Scanner;
public class bai2chuyendoi {
public static void main(String[] args) {
int a, b;
System.out.println("Number in decimal base:");
a = Enter();
System.out.println("Other base :");
b = Enter();
Change_base (a, b);
}
public static int Enter() {
int n = 0;
boolean check = false;
while (!check) {
Scanner sc = new Scanner(System.in);
try {
n = sc.nextInt();
check = true;
} catch (Exception e) {
System.out.println("Enter again:");
sc.nextLine();
}
}
return n;
}
public static void Change_base(int a, int b) {
int i = 0;
int[] c = new int[8];
while (a != 0) {
c[i] = a % b;
a = a / b;
i++;
}
while (i >= 0) {
--i;
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}
}
}
The error was in Change_base method in second while loop.
You need decrement 'i' and check that i >= 0, but you didn't.
while (--i >= 0) {
if (c[i] < 10) {
System.out.print(c[i]);
} else {
System.out.print((char) (c[i] + 55));
}
}
I'm trying to make a program for a password security, but many times I get Java Array Index Out of Bounds Exception...I tried to fix, but nothing, this is my code:
import java.util.Arrays;
public class BruteForce {
public static void main(String[] args) {
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true) {
if (attempt.equals(password)) {
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while (index >= 0) {
if (cg[index] == cs[cs.length - 1]) {
if (index == 0) {
cg = new char[cg.length + 1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString() {
return String.valueOf(cg);
}
}
When I try to add special char(s):
import java.util.Arrays;
public class BruteForce
{
public static void main(String[] args)
{
String password = "aaaa";
char[] charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true)
{
if (attempt.equals(password))
{
System.out.println("Password Found: " + attempt); // low security
break;
}
attempt = bf.toString();
System.out.println(attempt);
bf.increment();
}
}
private char[] cs;
private char[] cg;
public BruteForce(char[] characterSet, int guessLength)
{
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment()
{
int index = cg.length - 1;
while(index >= 0)
{
if (cg[index] == cs[cs.length-1])
{
if (index == 0)
{
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
}
else
{
cg[index] = cs[0];
index--;
}
}
else
{
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString()
{
return String.valueOf(cg);
}
}
And I get something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -65
The difference between
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
and
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.##"
is that in the first case, the characters are in ascending order (characters in java have a value).
Arrays.binarySearch requires the array to be in ascending order.
If you use
"#.0123456789#ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
instead (or use Arrays.sort in the BruteForce constructor) it should work.
Always remember to post the exact code that you are using!
I can only do the 4 operations,
I'm having a problem on how to input expressions like this, sin(60)*50/4
without GUI and using Scanner only.
Sorry but I'm just a newbie in programming and still learning the basics.
(1st time in programming subject XD)
This is my current code. I'm having a hard time on how to add sin, cos, tan, square, mod and exponent in my calculator.
import java.util.*;
public class Calculator {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int check=0;
while (check==0)
{
String sInput, sReal, sToken, sMToken, sMULTd;
int t, M, Md, term, a, b, sb, sbb;
System.out.print("Enter Expression: ");
sInput=sc.nextLine();
if (sInput.charAt(0)== '-')
{
sReal = sInput.substring(0,1) + minusTracker(sInput.substring(1));
System.out.print(sReal);
}
else
{
sReal = minusTracker(sInput);
System.out.print(sReal);
}
StringTokenizer sADD = new StringTokenizer(sReal, "+");
t = sADD.countTokens();
double iTerm[] = new double [t];
while(sADD.hasMoreTokens())
{
sToken = sADD.nextToken();
for(a=0; a<=(sToken.length()-1); a++)
{
b=a+1;
if( ((sToken.substring(a,b)).equals("*")) || ((sToken.substring(a,b)).equals("/")) )
{
StringTokenizer sMULT = new StringTokenizer(sToken, "*");
M = sMULT.countTokens();
double iMTerm[] = new double [M];
while(sMULT.hasMoreTokens())
{
sMToken = sMULT.nextToken();
for(sb=0; sb<=(sMToken.length()-1); sb++)
{
sbb= sb+1;
if((sMToken.substring(sb,sbb)).equals("/"))
{
StringTokenizer sMULTdiv = new StringTokenizer(sMToken, "/");
Md = sMULTdiv.countTokens();
double iMdTerm[] = new double [Md];
while(sMULTdiv.hasMoreTokens())
{
sMULTd = sMULTdiv.nextToken();
iMdTerm[--Md] = Double.parseDouble(sMULTd);
}
double MdTotal = getMdQuotient(iMdTerm);
sMToken = Double.toString(MdTotal);
}
}
iMTerm[--M] = Double.parseDouble(sMToken);
double mProduct = getMProduct(iMTerm);
sToken = Double.toString(mProduct);
}
}
}
iTerm[--t]= Double.parseDouble(sToken);
double finalAnswer = getSum(iTerm);
if(sADD.hasMoreTokens()==false)
System.out.println(" = " + finalAnswer );
}
}
}
public static String minusTracker(String sInput)
{
if(sInput.isEmpty())
{
return "";
}
else if(sInput.charAt(0)== '*' || sInput.charAt(0)=='/' || sInput.charAt(0)=='+' )
{
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else if( sInput.charAt(0)== '-')
{
if(sInput.charAt(1)== '-')
{
sInput = sInput.replaceFirst("--", "+");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
else
{
sInput = sInput.replaceFirst("-", "+-");
return sInput.substring(0,2) + minusTracker(sInput.substring(2));
}
}
else
{
return sInput.substring(0,1) + minusTracker(sInput.substring(1));
}
}
public static double getMdQuotient(double iMdTerm[])
{
double quotient= iMdTerm[(iMdTerm.length)-1];
for(int y=(iMdTerm.length)-2; y>=0; y--)
{
quotient = quotient / iMdTerm[y];
}
return quotient;
}
public static double getMProduct(double iMTerm[])
{
double product= 1;
for(int z=(iMTerm.length)-1; z>=0; z--)
{
product = product * iMTerm[z];
}
return product;
}
public static double getSum(double iTerm[])
{
double sum= 0;
for(int z=(iTerm.length)-1; z>=0; z--)
{
sum = sum + iTerm[z];
}
return sum;
}
}
I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.