Hello every one i'm working on a binary search program. My algorithm is correct but when I run the program with the driver program i get back the value "false" repeated instead of a table that looks like this.
Table output(LINK)
here is my driver program and main program.
public class TestResulter {
public static void main(String[] args) {
//Resulter resulter = new Resulter();
int numberOfItems = 10000;
int item;
int a[ ] = new int[ numberOfItems ];
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem( a );
System.out.println( Resulter.binarySearch( a , item ) );
}
}
}
My main program with binarySearch algorithm.
import java.util.Random;
public class Resulter extends TestResulter {
private static class Result {
public Boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st) {
found = f;
index = ind;
steps = st;
}
#Override
public String toString() {
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static boolean binarySearch(int[] a, int item) {
int start=0, end=a.length-1;
while(end>=start) {
int mid = start + ((end - start) / 2);
if (a[mid] == item)
return true;
if (a[mid] > item)
end = mid-1;
else start = mid+1;
}
return false;
}
public static int randomitem ( int[] a ) {
int i;
Random random = new Random();
int item = random.nextInt( 10999 );
for( i = 0; i < 10000; i++ )
{
a[ i ] = random.nextInt( 10000 );
}
return item;
}
}
I want my program to have a similar output to my image from my linear search program.
Here is your code with some changes and refactoring:
public class TestResulter
{
public static void main(String[] args)
{
int numberOfItems = 10000;
int item;
int[] a = new int[numberOfItems];
fillArray(a);
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem(a);
System.out.println(Resulter.binarySearch(a, item));
}
}
private static void fillArray(int[] a)
{
Random random = new Random();
for(int i = 0; i < a.length; i++)
a[i] = random.nextInt(10000);
Arrays.sort(a);
}
}
public class Resulter
{
private static class Result
{
public boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st)
{
found = f;
index = ind;
steps = st;
}
#Override
public String toString()
{
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static Result binarySearch(int[] a, int item)
{
int start=0, end=a.length-1;
int stepCount = 0;
while(end>=start)
{
stepCount++;
int mid = start + ((end - start) / 2);
if(a[mid] == item)
return new Result(true, mid, stepCount);
else if(a[mid] > item)
end = mid-1;
else
start = mid+1;
}
return new Result(false, -1, stepCount);
}
public static int randomitem(int[] a)
{
return new Random().nextInt(10000);
}
}
As I see it, the main problems in your solution were:
The array was not sorted. Binary search only works on sorted arrays, therefore the Arrays.sort(a) command.
The binarySearch returned a boolean and not a Result object, which is what you wanted to print out.
You have a syntax hiccup in your main function. Change int a[] to int[] a.
Also, the logic actions performed in randomitem are likely a contributing factor. The item it returns which binarysearch uses is not pulled from the search array a, but is generated at random. Try return a[random.nestIng(a.length)];
I'm on the mobile app, so my syntax may not be perfect.
Related
I have been trying to troubleshoot this java program from hours now and has not been able to find what is wrong with the execution. I think that the main class is not defined correctly.
It compiles successfully but the output is blank which should not be the case right? I intially tried to call the main class using the objects but still no luck. Any suggestions will work.
The original program:It compiles successfully on adding the main method but the output is blank.
import java.lang.Math; // headers MUST be above the first class
// one class needs to have a main() method
public class OrdSetSimple
{
// arguments are passed using the text field below this editor
public static void main(String[] args){
OrdSetSimple obj = new OrdSetSimple(10);
System.out.print("Success");
}
private int _set_size;
private int _set[];
private int _last;
public OrdSetSimple(int size) {
int k;
_set_size=size;
_set = new int[_set_size];
for(k=0; k<_set_size; k++)
_set[k]=0;
_last=-1;
}
private int make_a_free_slot(int val) {
int pos, i, j;
pos = binSearch(val);
if (pos >= 0)
return -1;
for (i=0; i<=_last; i++) {
if (_set[i] > val)
break;
}
if ((i<=_last)||(_last==-1)) {
for (j=_last; j>=i; j--)
_set[j+1] = _set[j];
pos = i;
} else {
pos = _last+1;
}
_last++;
return pos;
}
public void addElement(int n) {
int pos;
if (n<0) {
System.out.println("Addition of a negative integer impossible\n");
return;
}
if (_last+1>=_set_size) {
System.out.print("Addition of " + n);
System.out.println(" impossible since the array is already full");
System.out.println("The array is: " + toString());
} else {
pos = make_a_free_slot(n);
if (pos>=0)
_set[pos]=n;
}
return;
}
public int getSize() {
return _last+1;
}
public int getElementAt(int i) {
if ((i<0)||(i>_last))
return -1;
else
return _set[i];
}
private int binSearch(int x) {
int i=0;
int j=_last-1;
int m=0;
if (_last==-1)
return -1;
while(i<j) {
m= (i+j)/2;
if (x>_set[m])
i=m+1;
else
j=m;
}
if (x == _set[i]) return i;
else return -1;
}
public OrdSetSimple difference(OrdSetSimple s2) {
OrdSetSimple s1 = this;
int size1=s1.getSize();
int size2=s2.getSize();
OrdSetSimple set=new OrdSetSimple(size2);
int k;
for(k=0; k<size1; k++)
if (s2.binSearch(s1.getElementAt(k)) < 0)
set.addElement(s1.getElementAt(k));
return set;
}
public String toString() {
int k = 0;
String s="";
for (k=0; k<=_last; k++)
s += _set[k] + " ";
return s;
}
}
Your very first statement is wrong.
OrdSetSimple obj = new OrdSetSimple();//This will call the default constructor which will not initialize anything. This constructor will be added to your program by compiler, hence you don't get any compilation error.
Correct it like
OrdSetSimple obj = new OrdSetSimple(100);
ok I'm a little mind blown from an assignment i have to do. We have to implement a sequence class from wiley.com/go/javaexamples (the chapter 10 example) to make a new class called PrimeSequence and it has to right align the first 100 prime sequence numbers. I don't understand the point of implementing the other class and i did it but i know im not following the assignment rules because i dont understand what im supposed to implement from the other class and i also use nothing from the other class. I'm not sure on what i have to do
Sequence Class
public interface Sequence
{
int next();
}
PrimeSequence Class
public class PrimeSequence implements Sequence
{
public PrimeSequence()
{
}
public boolean isPrime(int x)
{
for (int start = 2; start <= Math.sqrt(x); start++)
{
if (x % start == 0)
{
return false;
}
}
return true;
}
public int next()
{
}
}
PrimeSequenceTester
public class PrimeSequenceTester {
public static void main(String[] args)
{
PrimeSequence prime = new PrimeSequence();
int currentNumber = 2;
int primesFound = 0;
while (primesFound < 100) {
if (prime.isPrime(currentNumber))
{
primesFound++;
System.out.printf("%4s",currentNumber + " ");
if (primesFound % 10 == 0)
{
System.out.println();
}
}
currentNumber++;
}
}
Here is a sample implementation using a Sieve of Eratosthenes (sieving only the odd numbers) and optimised to only sieve numbers once across multiple instances of the sequence. You need to do something a LOT simpler and just keep a track of what the current prime is and override the next() function so that when it is called you keep incrementing the value of the current prime until your isPrime() function returns true and then return that value.
import java.util.BitSet;
public class PrimeSequence implements Sequence {
private static final BitSet OddPrimeSieve = new BitSet( 8000 );
private static int MaxSievedPrime = 2;
static {
OddPrimeSieve.set(0, OddPrimeSieve.size() - 1, true );
}
private static int PrimeToIndex( final int prime ){
return (prime - 3) / 2;
}
private static int IndexToPrime( final int index ){
return 2*index + 3;
}
private static synchronized void setMaxSievedPrime( final int max ){
MaxSievedPrime = max;
for ( int index = PrimeToIndex( MaxSievedPrime ) + MaxSievedPrime;
index < OddPrimeSieve.length();
index += MaxSievedPrime )
OddPrimeSieve.set( index, false );
}
int currentPrime = 2;
#Override
public synchronized int next() {
final int current = currentPrime;
if ( current == 2 )
{
currentPrime++;
}
else
{
if ( currentPrime > MaxSievedPrime )
setMaxSievedPrime( currentPrime );
currentPrime = IndexToPrime( OddPrimeSieve.nextSetBit( PrimeToIndex( currentPrime ) + 1 ) );
}
return current;
}
public static void main( final String[] args ){
PrimeSequence p = new PrimeSequence();
for ( int i = 0; i < 100; i++ )
System.out.println( p.next() );
}
}
I have applied the KNN algorithm for classifying handwritten digits. the digits are in vector format initially 8*8, and stretched to form a vector 1*64..
As it stands my code applies the kNN algorithm but only using k = 1. I'm not entirely sure how to alter the value k after attempting a couple of things I kept getting thrown errors. If anyone could help push me in the right direction it would be really appreciated. The training dataset can be found here and the validation set here.
ImageMatrix.java
import java.util.*;
public class ImageMatrix {
private int[] data;
private int classCode;
private int curData;
public ImageMatrix(int[] data, int classCode) {
assert data.length == 64; //maximum array length of 64
this.data = data;
this.classCode = classCode;
}
public String toString() {
return "Class Code: " + classCode + " Data :" + Arrays.toString(data) + "\n"; //outputs readable
}
public int[] getData() {
return data;
}
public int getClassCode() {
return classCode;
}
public int getCurData() {
return curData;
}
}
ImageMatrixDB.java
import java.util.*;
import java.io.*;
import java.util.ArrayList;
public class ImageMatrixDB implements Iterable<ImageMatrix> {
private List<ImageMatrix> list = new ArrayList<ImageMatrix>();
public ImageMatrixDB load(String f) throws IOException {
try (
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr)) {
String line = null;
while((line = br.readLine()) != null) {
int lastComma = line.lastIndexOf(',');
int classCode = Integer.parseInt(line.substring(1 + lastComma));
int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
.mapToInt(Integer::parseInt)
.toArray();
ImageMatrix matrix = new ImageMatrix(data, classCode); // Classcode->100% when 0 -> 0% when 1 - 9..
list.add(matrix);
}
}
return this;
}
public void printResults(){ //output results
for(ImageMatrix matrix: list){
System.out.println(matrix);
}
}
public Iterator<ImageMatrix> iterator() {
return this.list.iterator();
}
/// kNN implementation ///
public static int distance(int[] a, int[] b) {
int sum = 0;
for(int i = 0; i < a.length; i++) {
sum += (a[i] - b[i]) * (a[i] - b[i]);
}
return (int)Math.sqrt(sum);
}
public static int classify(ImageMatrixDB trainingSet, int[] curData) {
int label = 0, bestDistance = Integer.MAX_VALUE;
for(ImageMatrix matrix: trainingSet) {
int dist = distance(matrix.getData(), curData);
if(dist < bestDistance) {
bestDistance = dist;
label = matrix.getClassCode();
}
}
return label;
}
public int size() {
return list.size(); //returns size of the list
}
public static void main(String[] argv) throws IOException {
ImageMatrixDB trainingSet = new ImageMatrixDB();
ImageMatrixDB validationSet = new ImageMatrixDB();
trainingSet.load("cw2DataSet1.csv");
validationSet.load("cw2DataSet2.csv");
int numCorrect = 0;
for(ImageMatrix matrix:validationSet) {
if(classify(trainingSet, matrix.getData()) == matrix.getClassCode()) numCorrect++;
} //285 correct
System.out.println("Accuracy: " + (double)numCorrect / validationSet.size() * 100 + "%");
System.out.println();
}
In the for loop of classify you are trying to find the training example that is closest to a test point. You need to switch that with a code that finds K of the training points that is the closest to the test data. Then you should call getClassCode for each of those K points and find the majority(i.e. the most frequent) of the class codes among them. classify will then return the major class code you found.
You may break the ties (i.e. having 2+ most frequent class codes assigned to equal number of training data) in any way that suits your need.
I am really inexperienced in Java, but just by looking around the language reference, I came up with the implementation below.
public static int classify(ImageMatrixDB trainingSet, int[] curData, int k) {
int label = 0, bestDistance = Integer.MAX_VALUE;
int[][] distances = new int[trainingSet.size()][2];
int i=0;
// Place distances in an array to be sorted
for(ImageMatrix matrix: trainingSet) {
distances[i][0] = distance(matrix.getData(), curData);
distances[i][1] = matrix.getClassCode();
i++;
}
Arrays.sort(distances, (int[] lhs, int[] rhs) -> lhs[0]-rhs[0]);
// Find frequencies of each class code
i = 0;
Map<Integer,Integer> majorityMap;
majorityMap = new HashMap<Integer,Integer>();
while(i < k) {
if( majorityMap.containsKey( distances[i][1] ) ) {
int currentValue = majorityMap.get(distances[i][1]);
majorityMap.put(distances[i][1], currentValue + 1);
}
else {
majorityMap.put(distances[i][1], 1);
}
++i;
}
// Find the class code with the highest frequency
int maxVal = -1;
for (Entry<Integer, Integer> entry: majorityMap.entrySet()) {
int entryVal = entry.getValue();
if(entryVal > maxVal) {
maxVal = entryVal;
label = entry.getKey();
}
}
return label;
}
All you need to do is adding K as a parameter. Keep in mind, however, that the code above does not handle ties in a particular way.
I don't know what to put for the if statement, I am working on this for class and am still EXTREMELY new to the language. It needs to recursively return true if element x is a member of an array A[] and false if not.
public static Boolean member (int x, int A[])
{
if ( )//base case
return true;
else // general case
{
int[] T= new int [A.length-1];
for (int i=1; I<A.length; i++)
T[i-1]=A[i];
return false;
}
}
Say you have this function/method: search(array a, int x, int index)
(1) check if index == a.length, if yes - return false;
(2) check if x is equal to the element a[index], if yes - return true;
(3) otherwise call and return search(a, x, index + 1)
This the pseude-code, you just need to write it in Java.
The function search is recursive.
Made a project and this works.
package recursiveTest;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] test = new int[10];
for(int i = 0; i < 10; i++){
test[i] = i;
}
System.out.println(member(4, test));
}
public static Boolean member (int x, int A[])
{
Boolean res = false;
if(A.length > 0){
if(A[0] != x){
int [] A_NEW = CreateANew(A);
res = member(x, A_NEW);
}else{
res = true;
}
}
return res;
}
public static int[] CreateANew(int A[]){
int [] A_NEW = new int [A.length-1];
for(int i = 1; i < A.length; i++){
A_NEW[i-1] = A[i];
}
return A_NEW;
}
}
Here is another way of doing it: I tried to respect your initial code flow
public static Boolean member (int x, int A[])
{
if ( x == A[0] )//base case
return true;
else // general case
{
if (A.length == 1) {
return false;
}
int B[] = new int[A.length-1];
System.arraycopy(A, 1, B, 0, B.length);
return member(x, B);
}
}
A test example
public static void main(String[] args) {
int A[] = {5,6,7,8,11,25,135,256,1875,1254};
boolean membershipOf25 = member(25,A);
System.out.println("Is 25 member? " + membershipOf25);
boolean membershipOf256 = member(256,A);
System.out.println("Is 256 member? " + membershipOf256);
boolean membershipOf109 = member(109,A);
System.out.println("Is 109 member? " + membershipOf109);
}
The result:
Is 25 member? true
Is 256 member? true
Is 109 member? false
I'm supposed to write a code which checks if a given number belongs to the Fibonacci sequence. After a few hours of hard work this is what i came up with:
public class TP2 {
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 <= n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 8;
System.out.println(ehFibonacci(n));
}
}
I must be doing something wrong, because it always returns "false". Any tips on how to fix this?
You continue the loop while fib2 <= n, so when you are out of the loop, fib2 is always > n, and so it returns false.
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 5;
System.out.println(ehFibonacci(n));
}
This works. I am not sure about efficiency..but this is a foolproof program,
public class isANumberFibonacci {
public static int fibonacci(int seriesLength) {
if (seriesLength == 1 || seriesLength == 2) {
return 1;
} else {
return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
}
}
public static void main(String args[]) {
int number = 4101;
int i = 1;
while (i > 0) {
int fibnumber = fibonacci(i);
if (fibnumber != number) {
if (fibnumber > number) {
System.out.println("Not fib");
break;
} else {
i++;
}
} else {
System.out.println("The number is fibonacci");
break;
}
}
}
}
you can also use perfect square to check whether your number is Fibonacci or not. you can find the code and some explanation at geeksforgeeks.
you can also see stackexchange for the math behind it.
I'm a beginner but this code runs perfectly fine without any issues. Checked with test cases hopefully it'll solve your query.
public static boolean checkMember(int n) {
int x = 0;
int y = 1;
int sum = 0;
boolean isTrue = true;
for (int i = 1; i <= n; i++) {
x = y;
y = sum;
sum = x + y;
if (sum == n) {
isTrue=true;
break;
} else {
isTrue=false;
}
}
return isTrue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(checkMember(n));
}