public int Neighbours(int xCoordinate, int yCoordinate)
{
xCoordinate -= 1;
yCoordinate -= 1;
int NeighbourCounter = 0;
int incrementer = 0;
int m1 = -1; //istart
int n1 = -1; //jstart
int m2 = 1; //iend
int n2 = 1; //jend
if (xCoordinate == 0)
{
m1 = 1;
}
if (yCoordinate == 0)
{
n1 = -1;
}
if (xCoordinate + 1 == yLen)
{
m2 = 0;
}
if (yCoordinate + 1 == xLen)
{
n2 = 0;
}
for (int xNeighbour = m1; xNeighbour <= m2; xNeighbour++)
{
if (xNeighbour == 0)
{
incrementer = 2;
}
else
{
incrementer = 1;
}
for (int yNeighbour = n1; yNeighbour<n2; yNeighbour += incrementer)
{
if (CurrentGen[yCoordinate + yNeighbour][xCoordinate + xNeighbour] == 1)
{
NeighbourCounter++;
}
}
}
return NeighbourCounter;
}
Is it possible to make this code more efficient? This code is for my Game of Life project, and I seem to be getting an error when I try to run this code for the next generation of the game of life. For my NextGeneration I seem to be getting an ArrayOutOfBoundsException: -2. This error occurs in the line 45.
Look at ArrayIndexOutOfBoundsException.
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
if(CurrentGen[yCoordinate + yNeighbour][xCoordinate + xNeighbour] == 1)
You are accessing CurrentGen.
yCoordinate + yNeighbour or xCoordinate + xNeighbour equals -2. Arrays start from index 0.
Related
My goal is to write a method showing how the fibonacci sequence moves. I have to use an array and equation to show how the numbers move on the array (thus iterating the value using fibonacci method: previous number + current number = next number).
This is the logic that I want to use with array[] as representation:
n = fibonacci number
i = 1;
previousNumber = 0
nextNumber = 1
sum = previousNumber + nextNumber;
while (i <= n) {
sum = previousNumber + nextNumber;
previousNumber = nextNumber;
nextNumber = sum;
return nextNumber;
I went this far and I am stuck:
long fibonacci(int fibonacci) {
int[] fib = new int[20];
if (fibonacci < 0) {
throw new IllegalArgumentException("n value cannot be negative number");
}
if (fibonacci == 0 || fibonacci == 1) {
return 1;
}
fib[0] = 1;
fib[1] = 1;
int i ;
for (i = 2; i < fibonacci; i++) {
fib[i] = fib[0] + fib[1];
fib[0] = fib[1];
fib[1] = fib[i];
}
return fib[i];
}
The returned value seems ok. In the fibonacci test, fib from 5 is 5 and 4 is 3. What worries me is how this string looks on the debugger. The way I move them makes them look like this : {3,5,2,3,5} and it should be {1,1,2,3,5}.
You don't need an array.
long fibonacci(int fibonacci) {
if (fibonacci < 0) {
throw new IllegalArgumentException("n value cannot be negative number");
}
if (fibonacci == 0 || fibonacci == 1) {
return 1;
}
first = 1;
second = 1;
sum i;
for (i = 2; i <= fibonacci; i++) {
sum = first + second;
first = second;
second = sum;
}
return sum;
}
This implementation is simpler and more readable.
Your loop is wrong. It should be:
for (i = 2; i <= fibonacci; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib[i-1];
You should never change fib[0] and fib[1], and fib[i] should be the sum of the previous two elements.
If the goal was to calculate fib(i) without an array, you would need two variables to keep track of the last two values:
long fibonacci(int fibonacci) {
if (fibonacci < 0) {
throw new IllegalArgumentException("n value cannot be negative number");
}
if (fibonacci == 0 || fibonacci == 1) {
return 1;
}
int beforeLast = 1;
int last = 1;
int i;
int fib = 1;
for (i = 2; i <= fibonacci; i++) {
fib = last + beforeLast;
beforeLast = last;
last = fib;
}
return fib;
}
Here is how your method should look like:
static long fibonacci(int fibonacci) {
int[] fib = new int[20];
if (fibonacci < 0) {
throw new IllegalArgumentException("n value cannot be negative number");
}
if (fibonacci == 0 || fibonacci == 1) {
return 1;
}
fib[0] = 1;
fib[1] = 1;
int i;
for (i = 2; i < fibonacci; i++) {
fib[i] = fib[i - 1] + fib[i - 2]; // change here
}
return fib[i-1]; // change here
}
This is my code and the answer always seems to 100001 (its not even
performing the loop).
I know there are much easier ways to solve this problem but what exactly is wrong with this particular code? and how do I fix it?
public class LargestPalindromes
{
public static void main(String[] args)
{
int largest = 100001;
for(int i = 100; i < 1000; i++)
{
for(int j = 100; j < 1000; j++)
{
int mult = i * j;
if(largest < mult && isPalindrome(mult))
largest = mult;
}
}
System.out.printf("\n\nThe largest palindrome is: %d\n\n", largest);
}
public static boolean isPalindrome(int mult)
{
int n1=0, n2=0, n3=0, n4=0, n5=0, n6=0;
int largest = 0, count = 0, p =100000;
int x = mult;
while(count < 6)
{
if(count == 1)
n1 = x / p;
else if(count == 2)
n2 = x / p;
else if(count == 3)
n3 = x / p;
else if(count == 4)
n4 = x / p;
else if(count == 5)
n5 = x / p;
else if(count == 6)
n6 = x / p;
x %= p;
p /= 10;
count++;
}
int reverse = Integer.valueOf(String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5) + String.valueOf(n6));
return reverse == mult;
}
}
There were too many errors in your original public static boolean isPalindrome(int mult) method. So I replaced it with the standard version:
public static boolean isPalindrome(int mult)
{
int temp=mult;
int r,sum=0;
while(mult>0){
r=mult%10; //getting remainder
sum=(sum*10)+r;
mult=mult/10;
}
if(temp==sum)
return true;
else{
return false;
}
}
I need the loop to iterate through A1,A2..A8..B8...H8 but it stops at C3 for some reason. For the life of me I cannot figure out why this loop within a loop is not running.
P.S letters is just an arraylist of the alphabet {A,B,C...Z} and getValue() just returns a value depending on how much a letter is worth.
int bestMove = 0;
for(int i = 0; i < 8; i++){
for(int x = 0; x < 8; x++){
System.out.println(letters.get(i) + "" + (x+1));
int distanceRow = currentRow - i;
int distanceCol = currentCol - x;
distanceRow = Math.abs(distanceRow);
distanceCol = Math.abs(distanceCol);
if(currentRow == i && currentCol == x){
System.out.println("if");
} else if (distanceRow - distanceCol == 0) {
bestMove = getValue(getPiece(i, x));
System.out.print("else if");
System.out.println(letters.get(i) + "" + (x+1));
} else {
System.out.print(letters.get(i) + "" + (x+1));
System.out.println("else");
}
}
Edit: I tested it as was suggested and it seems theres an error with this method although I dont know what since it just returns a value
public int getValue(String piece) {
if (piece.equals(w1)) {
return 1;
} else if (piece.equals(w2)) {
return 3;
} else if (piece.equals(w3)) {
return 3;
} else if (piece.equals(w4)) {
return 5;
} else if (piece.equals(w5)) {
return 9;
}
return 0;
}
This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
For one of my classes, we had to find a way to make a certain amount of change given an arbitrary amount of coins, with the least amount of coins. Here is my code below:
public class Changemaker {
public static void main ( String[] args ) {
int amount = Integer.parseInt(args[args.length-1]);
int coins = args.length - 1;
if (amount < 0){
throw new IllegalArgumentException("IMPROPER AMOUNT");
} else {
for (int i = 1; i <= coins; i++) {
int coin = Integer.parseInt(args[i]);
if (coin <= 0){
throw new IllegalArgumentException("IMPROPER DENOMINATION");
} else {
for (int j = 1; j <= coins; j++) {
int validCoin = Integer.parseInt(args[j]);
if (validCoin == coin && j != i ) {
throw new IllegalArgumentException("DUPLICATE DENOMINATION");
}
}
}
try {
String firstCoin = args[1];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("INSUFFICIENT DATA");
throw new ArrayIndexOutOfBoundsException(" ");
}
}
}
Tuple [][] table = new Tuple [coins][amount + 1];
for(int x = 0; x < coins; x++) {
for (int i = 0; i <= amount; i++) {
Tuple tuple = new Tuple (coins);
table[x][i] = tuple;
}
}
for (int i = 1; i <= amount; i++) {
Tuple tuple = table[0][i];
int coin = Integer.parseInt(args[1]);
int total = i;
int remainder = total % coin;
int coinAmt= (int)Math.floor(total / coin);
if (remainder == 0) {
tuple.setElement(0, coinAmt);
}
}
for(int x = 1; x < coins; x++) {
int coin = Integer.parseInt(args[x + 1]);
for (int i = 1; i <= amount; i++) {
Tuple tuple = table[x][i];
int total = i;
int remainder = total % coin;
int coinAmt= (int)Math.floor(total / coin);
if (remainder == 0) {
tuple.setElement(x, coinAmt);
int optimalRow = optimalCheck(table, tuple, x, i);
Tuple optimalTuple = table[optimalRow][i];
tuple.copy(optimalTuple);
} else if (remainder != 0 && amount < coin) {
tuple.copy(table[x - 1][i]);
} else if (remainder != 0 && amount > coin) {
tuple.setElement(x, coinAmt);
Tuple remainderTuple = table[x][remainder];
tuple.add(remainderTuple);
int optimalRow = optimalCheck(table, tuple, x, i);
Tuple optimalTuple = table[optimalRow][i];
tuple.copy(optimalTuple);
}
}
}
Tuple finalAnswer = table[coins - 1][amount];
String result = "";
result = result + finalAnswer.total() + " COIN(S) IN TOTAL: ";
for (int i = 0; i < coins; i++) {
result = result + finalAnswer.getElement(i) + " x " + args[i + 1] + " cent , ";
}
if (finalAnswer.total() == 0) {
System.out.println("AMOUNT CANNOT BE MADE");
} else {
System.out.println(result);
}
}
public static int optimalCheck(Tuple[][] table, Tuple tuple, int row, int column) {
int total = tuple.total();
int optimalRow = 0;
for (int i = 0; i <= row; i++ ){
int checkedTotal = table[i][column].total();
if (checkedTotal < total && checkedTotal > 0) {
optimalRow = optimalRow + i;
break;
} else if (checkedTotal == total && i == row) {
optimalRow = optimalRow + row;
break;
}
}
return optimalRow;
} }
For the most part, my code is correct. The only thing wrong with it is that it counts the amount of change to make as a denomination, and it cuts out my first denomination amount.
So, for example, if I put 1 5 10 25 133 in the command line (1,5,10, and 25 cent coins to make 133 cents), it returns:
1 COIN(S) IN TOTAL: 0 x 5 cent , 0 x 10 cent , 0 x 25 cent , 1 x 133 cent ,
I looked at the code, and I don't see where I went wrong. Can anyone tell me where I made the error? Thanks a ton.
In your for loop, you want
for (int i = 1; i < coins; i++) {
not
for (int i = 1; i <= coins; i++) {
<= will include coins, which is length - 1 - the last argument.
i have made a program to print 1-100 prime numbers.
please help me to throw exception for composite number in range of 1-100 numbers.
i am a beginner so any help will be appreciated.
public static void main(String[] args) {
System.out.println("Prime numbers from 1 - 100 are :");
int i = 0;
int x = 0;
for (i = 1; i <= 100; i++) {
int ctr = 0;
for (x = i; x >= 1; x--) {
if (i % x == 0) {
ctr = ctr + 1;
}
}
if (ctr == 2) {
System.out.println(i);
}
}
}
I'd rather implement isPrime method and call it
public static boolean isPrime(int value) {
if (value <= 1)
return false;
// There's only one even prime: that is two
if ((value % 2) == 0)
return (value == 2);
int from = (int) (Math.sqrt(value) + 1);
// You have to check possible divisors from 3 to sqrt(value)
for (int i = 3; i <= from; i += 2)
if ((value % i) == 0)
return false;
return true;
}
public static void main(String[] args) {
...
for (int i = 1; i <= 100; ++i) {
if (isPrime(i))
System.out.println(i);
else {
// i is not prime. You can do nothing, throw an exception etc
// throw new MyException("Not a prime");
}
}
}
You should add an else clause to if (ctr == 2) { and throw an exception in it. Have a look at the documentation on how to throw an exception.
put one more condition like.
else if(ctr!=2){
throw new CompositeException("composite exception occurs");}
public void primeNumber(int n1, int n2){
String primeNo= "";
System.out.print("Prime number between " + n1 +" and "+ n2 + "is/are - ");
for(int i = n1;i <=n2; i++)
{
int count = 0;
for(int j=1; j<=i; j++)
{
if(i%j==0)
{
count = count + 1;
}
}
if(count == 2) {
primeNo = primeNo + i + ", ";
}
}
System.out.print(primeNo);
}