Program not returning - java

i want to find a "peak value" in an array (a value where a1 ai+1>...>an, ai being the peak value here). I am using divide and conquer for a more optimum solution here. For" 6 1 3 50 70 100 48", it will print "70 100 48 4" which is good ( 70 < 100 and 100 > 48) but it does not return Integer.toString(a[m]), it returns "Array has no peak". I tried removing string and working with int but i get the exact same issue.
public class Main {
public int n, a[];
void read() {
File file = new File("src/com/fmi/Vector.txt");
Scanner sc;
try {
sc = new Scanner(file);
int i = 0;
if (sc.hasNextInt()) {
n = sc.nextInt();
}
a = new int[n];
while (sc.hasNextInt()) {
int aux = sc.nextInt();
a[i] = aux;
i++;
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
}
String search(int p, int u) {
int m;
System.out.println(p + " " + u);
if (p == u) {
return "0";
} else {
m = (p + u) / 2;
System.out.println(a[m - 1] + " " + a[m] + " " + a[m + 1] + " " + m);
if (a[m - 1] < a[m] && a[m] > a[m + 1]) {
return Integer.toString(a[m]);
} else if (a[m - 1] < a[m] && a[m] < a[m + 1]) {
search(m, u);
} else if (a[m - 1] > a[m] && a[m] > a[m + 1]) {
search(p, m);
}
}
return "Array has no peak!";
}
void display() {
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println(" ");
for (int i = 0; i < n; i++) {
System.out.print(i + " ");
}
}
public static void main(String[] args) {
Main obj = new Main();
obj.read();
System.out.println(obj.search(0, obj.n));
obj.display();
}
}

You're calling search but you're not doing anything with the result.
You should do something like
return search(m,u);

Related

Why is null appearing in my output? - Java

I am writing this program and all of a sudden null appears in the output:
1-10 |null**********
11-20 |null**********
21-30 |null
31-40 |null
41-50 |null
it should be like this:
1-10 |**********
11-20 |**********
21-30 |
31-40 |
41-50 |
This is my code:
import java.util.Arrays;
public class Ex4Method {
public void Average(int[] a) {
int total = 0;
for (int i = 0; i < a.length; i++) {
total = total + a[i];
}
int average = total / a.length;
System.out.println(" ");
System.out.println("Average: " + average);
}
public void MaxAndRange(int[] b) {
int min = b[0];
int max = b[0];
for (int i = 0; i <= 19; i++) {
//System.out.println(i);
if (b[i] < min) {
min = b[i];
}
if (b[i] > max) {
max = b[i];
}
}
int range = max - min;
System.out.println("Maximum Number: " + max);
System.out.println("Range: " + range);
}
public void Median(int[] c) {
Arrays.sort(c);
double median = 0;
System.out.println("Median: " + median);
}
public void findMedian(int a[]) {
// First we sort the array
Arrays.sort(a);
double median;
if (a.length % 2 == 0) {
median = ((double) a[a.length / 2] + (double) a[a.length / 2 - 1]) / 2;
} else {
median = (double) a[a.length / 2];
}
System.out.println("Median: " + median);
}
public void Mode(int[] d) {
int maxValue = 0, maxCount = 0;
for (int i = 0; i < d.length; i++) {
int count = 0;
for (int j = 0; j < d.length; j++) {
if (d[j] == d[i]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
maxValue = d[i];
}
}
System.out.println("Mode: " + maxValue);
}
public void Histogram(int[] f) {
String[] asterisk = new String[6];
System.out.println("Histogram: ");
System.out.println(" ");
for (int i = 0; i <= f.length - 1; i++) {
if (f[i] >= 1 && f[i] <= 10) {
asterisk[1] += "*";
}
if (f[i] >= 11 && f[i] <= 20) {
asterisk[2] += "*";
}
if (f[i] >= 21 && f[i] <= 30) {
asterisk[3] += "*";
}
if (f[i] >= 31 && f[i] <= 40) {
asterisk[4] += "*";
}
if (f[i] >= 41 && f[i] <= 50) {
asterisk[5] += "*";
}
}
System.out.println(" 1-10 |" + asterisk[1]);
System.out.println("11-20 |" + asterisk[2]);
System.out.println("21-30 |" + asterisk[3]);
System.out.println("31-40 |" + asterisk[4]);
System.out.println("41-50 |" + asterisk[5]);
}
}
MAIN CLASS-
import TurtleGraphics.KeyboardReader;
public class ArrayEx4 {
public static void main(String[] args) {
KeyboardReader reader = new KeyboardReader();
Ex4Method object = new Ex4Method();
int[] nums = new int[20];
int i = 0;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
while (nums[i] >= 1 && nums[i] <= 50 && i < 19) {
i++;
System.out.print("Enter a number (1-50): ");
nums[i] = reader.readInt();
//occurences[nums[i]]++;
}
//for(int x=0;x<=4;x++) {
//System.out.println(occurences[x]);
//}
object.Average(nums);
object.MaxAndRange(nums);
object.findMedian(nums);
object.Mode(nums);
object.Histogram(nums);
}
}
Any suggestions? Thanks
This is the code right here:
public void Histogram(int[] f) {
String[] asterisk = new String[6];
System.out.println("Histogram: ");
System.out.println(" ");
for (int i = 0; i <= f.length - 1; i++) {
if (f[i] >= 1 && f[i] <= 10) {
asterisk[1] += "*";
}
if (f[i] >= 11 && f[i] <= 20) {
asterisk[2] += "*";
}
if (f[i] >= 21 && f[i] <= 30) {
asterisk[3] += "*";
}
if (f[i] >= 31 && f[i] <= 40) {
asterisk[4] += "*";
}
if (f[i] >= 41 && f[i] <= 50) {
asterisk[5] += "*";
}
}
System.out.println(" 1-10 |" + asterisk[1]);
System.out.println("11-20 |" + asterisk[2]);
System.out.println("21-30 |" + asterisk[3]);
System.out.println("31-40 |" + asterisk[4]);
System.out.println("41-50 |" + asterisk[5]);
}
More specifically, this part:
asterisk[i] += "*";
In Java, + operator for strings means concatenation, and both operands are converted to strings beforehand.
At the very beginning, new String[6] is filled with default values for String type, which, for any type inherited from java.lang.Object is a null value. When you concatenate using operators, the very first pass over any slot in the array will always encounter a null value.
And
String.valueOf(null) + "*"
will output "null*"

Unable to nest a perfect number test within a loop

I'm trying to create a perfect number test for a range of numbers, with n being the start number and endNum being the end number. It won't loop properly, but the perfect number test (portion inside the "while" loop) works by itself. What am I doing wrong?
import java.util.Arrays;
import java.util.Scanner;
public class CodingChallenge3 {
public static void main(String[] args) {
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Welcome to the Perfect Number Tester."
+ "\n" + "Enter a number range."
+ "\n" + "From: ");
n = s.nextInt();
System.out.print("To: ");
int endNum = s.nextInt();
while (n <= endNum) {
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n && n != 0) {
System.out.println(n + " is perfect");
}
if (sum > n) {
System.out.println(n + " is imperfect abundant");
}
if (sum < n) {
System.out.println(n + " is imperfect deficient");
}
if (n == 0) {
System.out.println(n + " has no factors");
}
n++;
}
}
}
You forgot to reset the sum for each value of n:
while (n <= endNum) {
sum = 0; // add this
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum = sum + i;
}
}
if (sum == n && n != 0) {
System.out.println(n + " is perfect");
}
if (sum > n) {
System.out.println(n + " is imperfect abundant");
}
if (sum < n) {
System.out.println(n + " is imperfect deficient");
}
if (n == 0) {
System.out.println(n + " has no factors");
}
n++;
}

Big integer multiplication in java

This is my own method and I am also using my own BigInt class I did everything but I cannot seem to find out where I am doing wrong if someone can help me, I will be really thankful.
public BigInt mul(BigInt o) {
int max = n.length > o.n.length ? n.length : o.n.length;
int[] newdigits = new int[n.length + o.n.length];
for (int i = 0; i < max; i++)
{
int carry = 0;
for (int i2 = 0; i2 < o.n.length || carry > 0; i2++)
{
int otherDigit = i2 >= o.n.length ? 0: o.n[i2];
int val = (n[i] * otherDigit) + carry;
newdigits[i + i2] += val % 10;
carry = val / 10;
}
}
return new BigInt(newdigits);
}
This is my code so far it works but in the result i get one extra zero, as an example: when i multiply 100*10 I get 01000 instead of 1000 and other issue is that when i multiply 9999*1999 I get this: 1817262619101 but the correct answer is 19988001.
Can some one help me on this?
Here is my BigInt class:
public class BigInt {
public static void main(String[] args) {
BigInt a = new BigInt(args.length == 2 ? args[0] : "9999");
BigInt b = new BigInt(args.length == 2 ? args[1] : "1999");
System.out.println(a + (a.equals(b) ? " equals " : " does not equal ") + b);
System.out.println(a + (a.compareTo(b) < 0 ? " < " : (a.compareTo(b) > 0 ? " > " : " = ")) + b);
System.out.println(a + " + " + b + " = " + a.add(b));
if (a.compareTo(b) >= 0) {
System.out.println(a + " - " + b + " = " + a.sub(b));
}
System.out.println(a + " * " + b + " = " + a.mul(b));
if (a.compareTo(b) >= 0) {
System.out.println(a + " / " + b + " = " + a.div(b));
}
}
}
final class BigInt implements Comparable<BigInt> {
int[] digits;
int size;
public BigInt() {
n = new int[1];
}
public BigInt(String s) {
n = new int[s.length()];
for (int i = 0; i < n.length; ++i) {
n[n.length - i - 1] = s.charAt(i) - '0';
}
n = trim(n);
}
private BigInt(int[] n) {
this.n = new int[n.length];
for (int i = 0; i < n.length; ++i) {
this.n[i] = n[i];
}
}
public BigInt add(BigInt o) {
return null;
}
public int compareTo(BigInt o) {
if (n.length < o.n.length) {
return -1;
}
else if (n.length > o.n.length) {
return +1;
}
for (int i = n.length-1; i >= 0; --i) {
if (n[i] < o.n[i]) {
return -1;
}
else if (n[i] > o.n[i]) {
return +1;
}
}
return 0;
}
public BigInt div(BigInt o) {
return null;
}
public boolean equals(Object o) {
if (o instanceof BigInt) {
if (n.length == ((BigInt)o).n.length) {
for (int i = 0; i < n.length; ++i) {
if (n[i] != ((BigInt)o).n[i]) {
return false;
}
}
return true;
}
}
return false;
}
public BigInt mul(BigInt o) {
int max = n.length > o.n.length ? n.length : o.n.length;
int[] newdigits = new int[n.length + o.n.length];
for (int i = 0; i < max; i++)
{
int carry = 0;
for (int i2 = 0; i2 < o.n.length || carry > 0; i2++)
{
int otherDigit = i2 >= o.n.length ? 0: o.n[i2];
int val = (n[i] * otherDigit) + carry;
newdigits[i + i2] += val % 10;
carry = val / 10;
}
}
return new BigInt(newdigits);
}
public BigInt sub(BigInt o) {
return null;
}
public String toString() {
String s = "";
for (int i : n) {
s = i + s;
}
return s;
}
private int[] trim(int[] nums) {
int size = nums.length;
for (int i = nums.length - 1; i > 0; --i) {
if (nums[i] != 0) {
break;
}
--size;
}
int[] res = new int[size];
for (int i = 0; i < size; ++i) {
res[i] = nums[i];
}
return res;
}
private int[] n;
}
Didn't feel like debugging your code, but here is how I'd implement that multiplication. It's a little less efficient, but easier to keep track of the carry.
public BigInt mul(BigInt o) {
int max = n.length > o.n.length ? n.length : o.n.length;
int[] newdigits = new int[n.length + o.n.length];
for (int i = 0; i < max; i++) {
for (int i2 = 0; i2 < max; i2++) {
int digit1 = i >= n.length ? 0 : n[i];
int digit2 = i2 >= o.n.length ? 0 : o.n[i2];
if (digit1 > 0 && digit2 > 0) {
int value = digit1 * digit2;
int pos = i + i2;
while (value > 0) {
int newDigit = (newdigits[pos] + value) % 10;
value = (newdigits[pos] + value) / 10;
newdigits[pos] = newDigit;
pos++;
}
}
}
}
return new BigInt(newdigits);
}
First, look the possible lengths:
[1] * [1] = [1] OR length(1) + length(1) -> length(1)
[9] * [9] = [8,1] OR length(1) + length(1) -> length(2)
One solution
Psudocode:
if (newdigits[ (length-1) ] == 0)
int[] newarray = new int[ (length-1) ]
copy newdigits to newarray
return newarray
You have to look at the carry of the largest digit before the earlier digits.
Secondly, you need to add the previous value you found to the val variable.
End of i=0:
[1, 9, 9, 7, 1, 0, 0, 0]
Adding during i=1:
[0, 1, 9, 9, 7, 1, 0, 0]
End of i=1:
[1, 10, 18, 16, 8, 1, 0, 0]
I suggest you try using Arrays.toString(newdigits) or use a debugger to catch these problems in the future.

Array count logic error

Made some edits to the code to try and figure out why my X's [-1] are not being included in finding my average for that row. That is throwing of my averages. Any idea why It is not counting my -1's?
output[expected]:
USER INPUT: 3
O O O
X X X
X X X
TOTAL OPENNESS OF [I][J] = 1
TOTAL OPENNESS OF [I][J+1] = 2
TOTAL OPENNESS OF [I][J+2] = 1
TOTAL SUM AVERAGE FOR THAT ROW = 1.3
HOWEVER..FOR ROW 2 AND ROW 3
TOTAL SUM AVERAGE FOR THOSE ROWS = 0
WHICH IS INCORRECT IT SHOULD = -1
public static void openfactor(char[][] mazeValue, int n){
for(int i = 1; i<=n; i++)
{
double rowAvg=0;
double totalRowAvg=0;
for(int j=1;j<=n;j++)
{
int count=0;
int totalOpeness=0;
int totalRowOpeness = 0;
//double rowAvg=0;
if(mazeValue[i][j]=='X'){
System.out.println("tHIS IS AN X FOR : [" + i + "]" +"[" + j + "] IS -1 ");
count = -1;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=1)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1 && j-1>=1)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=1)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<=n && i+1<=n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<=n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=1 && i+1<=n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=1 && j+1<=n)
{
if(mazeValue[i-1][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " +totalOpeness);
totalRowOpeness = totalRowOpeness + totalOpeness;
//}//eND OF iF CONDITION\
}
rowAvg = (double)totalRowOpeness/(double)n;
System.out.println("ROW AVERAGE: "+rowAvg);
totalRowAvg = totalRowAvg + rowAvg;
System.out.println("SUM ROW AVERAGE: "+totalRowAvg);
}
System.out.println("TOTAL SUM ROW AVERAGE: " +totalRowAvg);
}
}
public static void printMaze(char mazeValue[][]) {
System.out.println("MAZE");
for (int i = 1; i < mazeValue.length; i++) {
for (int j = 1; j < mazeValue[i].length; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n + 1][n + 1];
System.out.println("ENTER A PATH: ");
for (int i = 0; i < mazeValue.length; i++) {
for (int j = 0; j < mazeValue[i].length; j++) {
if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
mazeValue[i][j] = 'X';
else {
mazeValue[i][j] = kbd.next().charAt(0);
}
}
}
printMaze(mazeValue);
horizontalPath(mazeValue, n);
System.out.println(" ");
verticalPath(mazeValue,n);
System.out.println(" ");
openfactor(mazeValue, n);
}
}
I do not completely understand what u want to accomplished but I am going to to assume you want to find repeated values, do this using some search algorithm below is an example of a binary search. Hope it helps.
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Here's the complete code for your request. you need to reorder your if statements a little bit your logic was right:
and here is the output :
MAZE
O O X
O O O
X X O
TOTAL OPENESS FOR : [0][0] IS 3
TOTAL OPENESS FOR : [0][1] IS 4
THERE IS AN X HERE FOR : [0][2]
Average of O's in this row is : 66.66667%
TOTAL OPENESS FOR : [1][0] IS 3
TOTAL OPENESS FOR : [1][1] IS 5
TOTAL OPENESS FOR : [1][2] IS 3
Average of O's in this row is : 100.0%
THERE IS AN X HERE FOR : [2][0]
THERE IS AN X HERE FOR : [2][1]
TOTAL OPENESS FOR : [2][2] IS 2
Average of O's in this row is : 33.333336%
here's the code:
import java.util.Scanner;
public class sof {
public static boolean IsOutOfBound(int i, int j, int n)
{
if (i-1<1 || j-1<1 || i+1>n || j+1>n)
return true;
else
return false;
}
public static void openfactor(char[][] mazeValue, int n)
{
for(int i = 0; i<n; i++)
{
int TotalCounts=0;
for(int j=0;j<n;j++)
{
int count=0;
if(mazeValue[i][j]=='X'){
System.out.println("THERE IS AN X HERE FOR : [" + i + "]" +"[" + j + "] ");
//TotalCounts--;
}
else
{
//YOU NEED TO VERIFY THAT J IS NOT OUT OF BOUND
if( j-1>=0)
{
if(mazeValue[i][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0 && j-1>=0)
{
if(mazeValue[i-1][j-1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(i-1>=0)
{
if(mazeValue[i-1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n)
{
if(mazeValue[i][j+1]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j+1<n && i+1<n)
{
if(mazeValue[i+1][j+1]=='O')
count++;
}
if (i+1<n)
{
if(mazeValue[i+1][j]=='O')
count++;
}
// System.out.println("cout: "+count);
if(j-1>=0 && i+1<n)
{
if(mazeValue[i+1][j-1]=='O')
count++;
}
if(i-1>=0 && j+1<n)
{
if(mazeValue[j+1][i-1]=='O')
count++;
}
// System.out.println("cout: "+count);
//totalOpeness = totalOpeness +count;
System.out.println("TOTAL OPENESS FOR : [" + i + "]" +"[" + j + "] IS " + count);
TotalCounts++;
}//END OF else CONDITION
}//End of J loop
float Average = ((float)TotalCounts/(float)n) * 100;
System.out.println("Average of O's in this row is : " + Average+ "%");
}//End of I loop
}
public static void printMaze(char mazeValue[][],int n) {
System.out.println("MAZE");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%5c", mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void main(String[] args) {
// TODO code application logic here
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for (int i = 0; i <n; i++) {
for (int j = 0; j < n; j++) {
//if (i == 0 || j == 0 || i == n + 1 || j == n + 1)
// mazeValue[i][j] = 'X';
// else {
mazeValue[i][j] = kbd.next().charAt(0);
// }
}
}
printMaze(mazeValue,n);
openfactor(mazeValue, n);
}
}

Can you quickly tell me if this pseudocode makes sense or not?

I believe my code is now foolproof. I will write up the pseudocode now. But I do have one question. Why does DRJava ask that I return something outside of my if statements? As you can see I wrote for ex: "return 1;" just because it asked. It will never return that value however. Can someone explain this to me?
public class assignment1question2test {
public static void main(String[] args) {
int[] a = new int[50];
int l = 0;
int r = a.length;
for(int i=0; i<r; i++) {
a[i] = 1;
}
a[0] = 10;
for (int i=0; i<r; i++) {
System.out.println(a[i]);
}
System.out.print(recursiveSearch(a,l,r));
}
public static int recursiveSearch (int[] a, int l, int r) {
int third1 = (r-l)/3 + l;
int third2 = third1*2 - l + 1;
System.out.println("i will be checking compare from " + l + " to " + third1 + " and " + (third1 + 1) + " to " + third2);
int compareResult = compare(a,l,third1,third1 + 1, third2);
if(r-l == 1) {
if (compareResult == 1) {
return l;
}
else {
return r;
}
}
if (compareResult == 0) {
return recursiveSearch(a,third2 + 1, r);
}
if (compareResult == 1) {
return recursiveSearch(a,l,third1);
}
if (compareResult == -1) {
return recursiveSearch(a,third1 + 1, third2);
}
return 1;
}
public static int compare(int[] a, int i, int j, int k, int l) {
int count1 = 0;
int count2 = 0;
for(int g=i; g<=j; g++) {
count1 = count1 + a[g];
}
for(int g=k; g<=l; g++) {
count2 = count2 + a[g];
}
if (count1 == count2) {
return 0;
}
if (count1 > count2) {
return 1;
}
if (count1 < count2) {
return -1;
}
return 0;
}
}
UPDATED FINAL PSEUDOCODE:
Algorithm: recursiveSearch (a,l,r)
Inputs: An array a, indices l and r which delimit the part of interest.
Output: The index that has the lead coin.
int third1 ← (r - l + 1)/3
int third2 ← third1*2 - l + 1
if (r-l = 0) then
return l
int compareResult ← compare(a,l,third1,third1 + 1,third2)
if (r-l = 1) then
if (compareResult = 1) then
return l
else
return r
if (compareResult = 0) then
return recursiveSearch(a, third2 + 1, r)
if (compareResult = "1") then
return recursiveSearch(a,l,third1)
if (compareResult = "-1") then
return recursiveSearch(a,third1 + 1,third2)
You seem to be including mid in the following search regardless of which side is larger. The recursive calls should both exclude mid from their search space.
Also, for the comparison to be meaningful, the two groups being compared need to be of equal size. That will require some extra odd/even logic.

Categories