What's wrong with my code in Java? - java

I have written a code that is supposed to count the following,
here some examples:
x(2) = 1 * (1+2) = 3
x(4) = 1 * (1+2) * (1+2+3) * (1+2+3+4) = 180
x(5) = 1 * (1+2) * (1+2+3) * (1+2+3+4) * (1+2+3+4+5) = 2700
Edit:
Thx a lot so far to everyone!
I didn't expect to get help that fast and precise, really nice :D
Just modified my code now and I no longer get 0 as result (no matter what i typed) which is very good.
But I think there is another mistake left somewhere,
let's say I type into console 2, I will get 2 as result.
If I type 4, I get 24 as result. For 5 I get 120 and 6 I get 720.
From this I could realize one thing.
If i divide let's say 720 by 6, I get 120 which is the previous result (of 5).
And if I take result of 5 which is 120 and divide it by 4, I get 24.
public class CounIt
{
public static int i;
public static int j;
public static int b;
public static int c;
public static int a (int k)
{
j = 0;
for (i = 1; i <= k; ++i)
j = j + 1;
return j;
}
public static int x (int k)
{
b = 1;
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
public static void main (String[] args)
{
int k = Integer.parseInt(args[0]);
System.out.println(x(k));
}
}

Two problems:
b remains 0 in the function x(int), so this function always returns 0. Shouldn't it be initialised to 1?
The function a(int) returns the input parameter. Didn't you mean to return j?
Also, having single character function names makes your program tricky to read.

Because you initialized b to zero every multiplication of b will give you 0
b = 0; // Set b to zero
for (c = 1; c <= k; ++c)
b = b * a(c); // b will stay to 0 because b = 0 * a(c);
Modify your code to
b = 1; // <---- Here the modification
for (c = 1; c <= k; ++c)
b = b * a(c);
To be sure that your code works as expected you should unit test your functions. Take a look at TDD metodology, it will save you a lot of time for bigger projects. And here a link to a nice tutorial to unit tests.

Try this:
public class CountIt
{
public static int i;
public static int j;
public static int b;
public static int c;
public static int a (int k)
{
j = 0;
for (i = 1; i < k; ++i)
j = j + 1;
return j;
}
public static int x (int k)
{
b = 1;
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}
public static void main (String[] args)
{
int k = Integer.parseInt(args[0]);
System.out.println(x(k));
}
}

This function is very suitable for recursion:
public class SumPyramid {
public static void main (String[] args) {
System.out.println(sumPyramid(5));
}
public static int sumPyramid(int height) {
if (height == 1) {
return 1;
}
else
return height + sumPyramid(height - 1);
}
}
}

Both functions a and x have errors. Modify functions as below.
Logically its working
public static int a (int k)
{
j = 0;
for (i = 1; i <= k; ++i) // changed consition to less than or equal to
j = j + 1;
return j; // returns j
}
public static int x (int k)
{
b = 1; // changed initial value to 1
for (c = 1; c <= k; ++c)
b = b * a(c);
return b;
}

Related

Implementing vector multiplication in java

Currently I'm trying to implement a way to be able to use vector- and matrix-multiplication in java, right now I have the code:
package ai2;
public class MyMatrix {
int[][] alpha;
int a;
int b;
int rowsB;
int colsB;
public MyMatrix(int a, int b) {
this.a = a;
this.b = b;
alpha = new int[a][b];
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
alpha[k][l] = 0;
}
}
}
public void insertValue(int o, int q, int z) {
this.alpha[o][q] = z;
}
public void print() {
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
System.out.print(this.alpha[k][l] + " ");
}
System.out.println();
}
}
public void multiplyMatrix(MyMatrix B) {
MyMatrix created = new MyMatrix(this.a, B.b);
for (int m = 0; m < a; m++) {
for (int k = 0; k < b; k++) {
for (int l = 0; k < this.a; l++) {
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
}
}
}
}
public static void main(String[] args) {
MyMatrix a = new MyMatrix(2, 2);
a.insertValue(0, 0, 1);
a.insertValue(1, 1, 1);
a.print();
MyMatrix b = new MyMatrix(2, 2);
b.insertValue(0, 0, 1);
b.insertValue(1, 0, 1);
// System.out.println(a);
}
}
The problem is my multiplyMatrix method, it takes a MyMatrix object but I cant reach the values using for example:
MyMatrixA[k][l]
I need some sort of idea to reach those values or perhaps a smarter implementation, I cannot use packages outside of java, thankful for any help!
Square brackets in Java are only for accessing array elements.
Your syntax there will not compile, and you cannot access your matrix elements that way.
Why don't you just implement a getAlpha getter in your MyMatrix class that returns the value for alpha (or better, a copy thereof, to ensure immutability)?
You could then reference it with theMatrixInstance.getAlpha()[k][l].
You could also simplify a bit and implement a get method taking two indices.
That would allow you to check whether the given indices are within the bounds of your two-dimensional array and throw a custom exception (or return some default value) rather than the ArrayIndexOutOfBoundsException you'd otherwise get.
Replace this line
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
with
created.alpha[i][j] += this.alpha[i][k] * B.alpha[k][j];
Or better yet, replace
MyMatrix created = new MyMatrix(this.a, B.b);
with
MyMatrix A = this;
MyMatrix C = new MyMatrix(this.a, B.b);
then you can do
C.alpha[i][j] += A.alpha[i][k] * B.alpha[k][j];
Which reads a little more clearly.
Finally, no need to initialize alpha with 0's in your constructor, this happens automatically.

Trouble with Prime connection

The problem below was given in one of my exams and was asked to solve the following problem using Java only.
The problem is, I got stuck in the part where the program is supposed to return the given non-negative integer as an array of digits. Can anyone provide a solution to this?
Thanks in advance.
Two positive numbers A and B are said to be connected (denoted by "A ↔ B") if one of these conditions holds:
(1) A and B have the same length and differ in exactly one digit; for example, 123 ↔ 173.
(2) Adding one digit to the left of A (or B) makes B (or A); for example, 23 ↔ 223 and 123 ↔ 23.
We call a prime P a 2's relative if there exists a chain of connected primes between 2 and P and no prime in the chain exceeds P.
For example, 127 is a 2's relative. One of the possible chains is shown below:
2 ↔ 3 ↔ 13 ↔ 113 ↔ 103 ↔ 107 ↔ 127
However, 11 and 103 are not 2's relatives.
Let F(N) be the sum of the primes ≤ N which are not 2's relatives.
We can verify that F(103) = 431 and F(104) = 78728.
Find F(107).
Edited: my part
I am sorry I don't carbon copy remember my solution as I don't have my results given to me. But just for the sake of this question, I think the part where it was supposed to return non-negative number, I had something like this -
private static int[] toDigits(int n) {
if (n < 0)
throw new IllegalArgumentException();
int[] temp = new int[10];
int len = 0;
do {
temp[len] = n % 9;
n /= 9;
len++;
} while (n > 0);
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
public final class infinitybyone implements TestSolution {
public static void main(String[] args) {
System.out.println(new infinitybyone().run());
}
private static final int LIMIT = Library.pow(10, 7);
public String run() {
boolean[] isPrime = Library.listPrimality(LIMIT);
int[] pathMax = new int[isPrime.length];
Arrays.fill(pathMax, Integer.MAX_VALUE);
Queue<IntPair> queue = new PriorityQueue<>();
queue.add(new IntPair(2, 2));
while (!queue.isEmpty()) {
IntPair item = queue.remove();
int n = item.b;
int pmax = item.a;
if (pmax >= pathMax[n]) {
continue;
}
pathMax[n] = pmax;
int[] digits = toDigits(n);
int[] tempDigits = digits.clone();
for (int i = 0; i < tempDigits.length; i++) {
for (int j = 0; j < 10; j++) {
tempDigits[i] = j;
int m = toNumber(tempDigits);
int nextPmax = Math.max(m, pmax);
if (m < isPrime.length && isPrime[m] && nextPmax < pathMax[m])
queue.add(new IntPair(nextPmax, m));
}
tempDigits[i] = digits[i];
}
}
long sum = 0;
for (int i = 0; i < isPrime.length; i++) {
if (isPrime[i] && pathMax[i] > i)
sum += i;
}
return Long.toString(sum);
}
private static int[] toDigits(int n) {
if (n < 0)
throw new IllegalArgumentException();
//************This is PROBABLY where you made the error************
int[] temp = new int[11];
int len = 0;
do {
temp[len] = n % 10;
n /= 10;
len++;
} while (n > 0);
int[] result = new int[len + 1];
for (int i = 0; i < result.length; i++)
result[i] = temp[len - i];
return result;
}
private static int toNumber(int[] digits) {
int result = 0;
for (int x : digits)
result = result * 10 + x;
return result;
}
private static class IntPair implements Comparable<IntPair> {
public final int a;
public final int b;
public IntPair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(IntPair other) {
return Integer.compare(a, other.a);
}
}
}
I can't really tell where you messed up but at least from the code you shared, tell me why would you use 10 instead of 11? It should extract base-10 in little endian.

A simple Java method not working

Hello everyone I am a newbie with the java programming language and have been learning the use of methods, below is a simple method i wrote for adding two numbers but when I run the code, it doe not display any output, please what I am doing wrongly? the code should sum numbers from 2 to 4 in this case
//testing Java methods
public class Methods {
public static void main(String [] args) {
int addition = add (2,4);
System.out.println(addition);
}
//the method for addition
public static int add(int a, int b){
int sum = 0;
for (int i = a; a <= b ; i++)
sum += i;
return sum;
}
}
for (int i = a; a <= b ; i++)
It should be
for (int i = a; i <= b ; i++)
It was actually running into infinite loop.
try this program (change from a <= b to i <= b)
public static void main(String[] args) {
int addition = add(2, 4);
System.out.println(addition);
}
// the method for addition
public static int add(int a, int b) {
int sum = 0;
for (int i = a ; i <= b ; i++) {
sum += i;
}
return sum;
}
output
9
your for loop should be
for (int i = a; i <= b ; i++)
//testing Java methods
public class Methods {
public static void main(String[] args) {
int addition = add(2,4);
System.out.println(addition);
}
//the method for addition
public int add(int a, int b){ // Place this method in the class.
int sum = 0;
for (int i = a; i <= b ; i++){ // "a <= b" Has to be: i <= b
sum += i;
}
return sum;
}
}
I think this is want you want.
The result will be:
2+3+4 = 9

Algorithm to calculate Fibonacci sequence implemented in Java gives weird result

When I run Countdown.class I get the following output:
263845041
-1236909152
-973064111
2084994033
1111929922
-1098043341
13886581
-1084156760
-1070270179
2140540357
Blast Off!
The numbers before "Blast Off!" ought to be the first 10 Fibonacci numbers. My source code is as follows.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return 1;
return fib(n-1) + fib(n-2);
}
public static long fastfib(int n) {
int a = 0;
int b = 1;
int c = 0;
for (int i = 0; i <= n; n++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
and the class that implements the fastfib method is:
public class Countdown {
public static void countdown(int n) {
if (n == 0) System.out.println("Blast Off!");
else {
System.out.println(Fibonacci.fastfib(n));
countdown(n - 1);
}
}
public static void main(String[] args) {
countdown(10);
}
}
Though your fastfib() method returns long, the calculations are done on ints.
You are encountering integer overflow.
Make sure to declare a,b,c as longs and NOT as ints. If you want even larger numbers (that are out of range for longs as well) - you might want to have a look on BigInteger (and use it).
EDIT: As mentioned by #ExtremeCoders in comment, there is another issue in the code in your for loop:
for (int i = 0; i <= n; n++) should be for (int i = 0; i <= n; i++), you want to increase i - not n.
In addition to the other answers,
for (int i = 0; i <= n; n++) {
should be
for (int i = 0; i <= n; i++) {
// ^ that's an i
Change the datatypes of a,b and c to long, and it will start working fine. Your numbers are crossing the limits for int.
You should user BigInteger insted of long
import java.math.BigInteger;
public class Fibonacci {
public static BigInteger fib(BigInteger n) {
int result = n.compareTo(BigInteger.valueOf(1)); // returns -1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.
if (result != 1) return BigInteger.valueOf(1);
return fib(
n.subtract(
BigInteger.valueOf(1).add
(n.subtract
(
BigInteger.valueOf(-2)
)
)
)
);
}
public static BigInteger fastfib(int n) {
BigInteger a = BigInteger.valueOf(0);
BigInteger b = BigInteger.valueOf(1);
BigInteger c = BigInteger.valueOf(0);
for (int i = 1; i < n; i++) {
c = a.add(b);
a = b;
b = c;
}
return c;
}
}

getting error StringIndexOutOfBoundsException: String index out of range [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am trying to build a matrix with row and column having values such as "aaa" for aligning purposes. but when I run it I get an error. below is my code
public class compute_matrix {
static String seq1="aaa";
static String seq2="aaa";
static int[][] matrix;
static int max_row;
static int max_col;
private static int match_reward=1;
private static int mismatch_penalty= -1;
private static int gap_cost= -1;
private static boolean case_sensitive;
private static boolean isCaseSensitive() {
return case_sensitive;
}
private static int max(int ins, int sub, int del, int i) {
if (ins > sub) {
if (ins > del) {
return ins > i? ins : i;
} else {
return del > i ?del : i;
}
} else if (sub > del) {
return sub> i ? sub : i;
} else {
return del > i ? del : i;
}
}
protected char sequence[];
public static void main(String args[]){
int r, c, rows, cols, ins, sub, del, max_score;
rows = seq1.length()+1;
cols = seq2.length()+1;
matrix = new int [rows][cols];
// initiate first row
for (c = 0; c < cols; c++)
matrix[0][c] = 0;
// keep track of the maximum score
max_row = max_col = max_score = 0;
// calculates the similarity matrix (row-wise)
for (r = 1; r < rows; r++)
{
// initiate first column
matrix[r][0] = 0;
for (c = 1; c < cols; c++)
{
sub = matrix[r-1][c-1] + scoreSubstitution(seq1.charAt(r),seq2.charAt(c));
ins = matrix[r][c-1] + scoreInsertion(seq2.charAt(c));
del = matrix[r-1][c] + scoreDeletion(seq1.charAt(r));
// choose the greatest
matrix[r][c] = max (ins, sub, del, 0);
if (matrix[r][c] > max_score)
{
// keep track of the maximum score
max_score = matrix[r][c];
max_row = r; max_col = c;
}
}
}
}
private static int scoreSubstitution(char a, char b) {
if (isCaseSensitive())
if (a == b)
return match_reward;
else
return mismatch_penalty;
else
if (Character.toLowerCase(a) == Character.toLowerCase(b))
return match_reward;
else
return mismatch_penalty;
}
private static int scoreInsertion(char a) {
return gap_cost;
}
private static int scoreDeletion(char a) {
return gap_cost;
}
public char charAt (int pos)
{
// convert from one-based to zero-based index
return sequence[pos-1];
}
}
and my error is displaying this
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:695)
at compute_matrix.main(compute_matrix.java:67)
Java Result: 1
rows = seq1.length()+1;
cols = seq2.length()+1;
matrix = new int [rows][cols];
and then later:
for (c = 1; c < cols; c++)
{
//when c == cols-1, it is also `seq2.length()`
//the access to seq2.charAt(c) will cause this exception then.
sub = matrix[r-1][c-1] + scoreSubstitution(seq1.charAt(r),seq2.charAt(c));
ins = matrix[r][c-1] + scoreInsertion(seq2.charAt(c));
del = matrix[r-1][c] + scoreDeletion(seq1.charAt(r));
In the above loop, when c == cols-1, it is also seq2.length(), the access to seq2.charAt(c) will cause this exception then.
You initialize the number of rows and cols to length() + 1, while you later iterate from 0 to length (inclusive), while the string contain only length() chars - from 0 to n exclusive.
If you are a C programmer in your past - I assume you are expecting a \0 terminator at the end of the string. In java you don't have those - since String is an object - you can hold a field to indicate its exact length. Meaning the last char in the string, is actually the last character there.
in line 60 of your code
sub = matrix[r-1][c-1] + scoreSubstitution(seq1.charAt(r),seq2.charAt(c));
max value for r is 4 so when you look up for seq.charAt(3) there is nothingso it shows index out of bound
I refactored your code into more canonical java.
The things I've changed:
The class is now called SimilarityMatrix, a more appropriate, self documenting name
variable declarations now happen where they get used as opposed to at the top of main
The work is now done in an instance of the class rather than the main method
I used the built in Math.max(int, int) instead of rolling my own
I removed a lot of unnecessary nested if statements. Java's short circuit evaluation helps here
Since both r and c as well as r+1 and c+1 are used frequently in your calculation loop, I track both
I removed many of the dependencies on static state (made many things instance variables)
Static state that remains is all final now (I made them constants)
Used more java-y variable names (java people really like their camel case)
public class SimilarityMatrix
{
public static final int matchReward = 1;
public static final int mismatchPenalty = -1;
public static final int gapCost = -1;
private int[][] matrix;
private int maxRow = 0;
private int maxCol = 0;
private boolean caseSensitive = false;
SimilarityMatrix(String s1, String s2, boolean dontIgnoreCase)
{
this(s1, s2);
caseSensitive = dontIgnoreCase;
}
SimilarityMatrix(String s1, String s2)
{
int rows = s1.length() + 1;
int cols = s2.length() + 1;
matrix = new int[rows][cols];
int max_score = 0;
for (int x = 0; x < cols; x++)
{
matrix[0][x] = 0;
matrix[x][0] = 0;
}
for (int r = 0, rp1 = 1; rp1 < rows; ++r, ++rp1)
{
for (int c = 0, cp1 = 1; cp1 < rows; ++c, ++cp1)
{
int sub = matrix[r][c] + scoreSubstitution(s1.charAt(r), s2.charAt(c));
int ins = matrix[rp1][c] + scoreInsertion(s2.charAt(c));
int del = matrix[r][cp1] + scoreDeletion(s1.charAt(r));
// choose the greatest
matrix[rp1][cp1] = Math.max(Math.max(ins, sub), Math.max(del, 0));
if (matrix[rp1][cp1] > max_score)
{
// keep track of the maximum score
max_score = matrix[rp1][cp1];
maxRow = rp1;
maxCol = cp1;
}
}
}
}
public static void main(String args[])
{
SimilarityMatrix me = new SimilarityMatrix("aaa", "aaa");
System.out.println(me.getMaxRow() + " " + me.getMaxCol());
}
private int scoreSubstitution(char a, char b)
{
if ((a == b && caseSensitive) || Character.toLowerCase(a) != Character.toLowerCase(b))
return matchReward;
else
return mismatchPenalty;
}
public int getMaxRow()
{
return maxRow;
}
public int getMaxCol()
{
return maxCol;
}
private int scoreInsertion(char a)
{
return gapCost;
}
private int scoreDeletion(char a)
{
return gapCost;
}
}

Categories