How can I do something like this? I need to create a Fibonacci class with one next () method returning the next Fibonacci string value.
Subsequent calls should return: 0, 1, 1, 2, 3, 5, 8, etc.
The program takes an integer from the user and returns the specified number of string values. Calculations should be made using arrays.
public class Fibonacci {
final long[][] A = {{1, 1}, {1, 0}};
public static void main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
long[][] b = f.next();
System.out.print(b[0][1]);
}
}
public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return n;
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public long[][] next() {
long[][] a =new long[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
a[i][j] += a[i][j] * A[j][i];
}
}
return a ;
}
}
Your matrix is confusing.
Here is a simple alteration of your code with two int instead of matrix.
Test it and let me know.
public class Fibonacci {
long i = -1; // clone of the loop counter i
long fibo1 = 1;
long fibo2 = 1;
public void main(String[] args) {
System.out.print("Enter the n th word of the sequence: ");
long n = initialStatement(readValue());
Fibonacci f = new Fibonacci();
for (int i = 0; i < n; i++) {
System.out.print(f.next());
}
}
public static long readValue() {
Scanner scanner = new Scanner(System.in);
return scanner.nextLong();
}
public static long initialStatement(long n) {
do {
if (n == 0 || n == 1) {
return 1; // fibo(0) == fibo(1) == 1
} else if (n < 0) {
System.out.print("Wrong value, please enter correct value: ");
n = Fibonacci.readValue();
}
} while (n < 0);
return n;
}
public String next() {
i++; // simulation of loop i because it is not a param of next()
if(i >= 2) {
long aux = fibo1 + fibo2;
fibo1 = fibo2;
fibo2 = aux;
}
return ""+ fibo2;
}
}
Fibonacci is a sequence that can be described by:
fibo(0) = 0
fibo(1) = 1
fibo(n) = fibo(n - 1) + fibo(n - 2)
In code, the most simple implementation does not use matrices. You can do something like this in your class:
private int a = 0;
private int b = 0;
public void next() {
// Special case: Return 0 as first number in the sequence.
if(a == 0 && b == 0) {
b = 1;
return 0;
}
// Return the sum of the last two numbers, and store the new last two numbers in a and b.
int result = a + b;
a = b;
b = result;
return result;
}
That will return the Fibonacci sequence starting at 0.
Design an application that has an array of at least 20 integers. It should call a module that uses the sequential search algorithm to locate one of the values. The module should keep a count of the number of comparisons it makes until it finds the value. Then the program should call another module that uses the binary search algorithm to locate the same value. It should also keep a count of the number of comparisons it makes. Display these values on the screen.
I already have the sequential search working properly, and it displays the number of iterations it took to find the desired value. However, I am having trouble with my binary search module. Every time it searches for a value, it always returns the value 1. Here is the code I have excluding the sequential search module.
Appreciate any help.
//Scanner class
import java.util.Scanner;
public class JavaProgramCh9Ex7_test {
//global scanner to read input
static Scanner keyboard = new Scanner(System.in);
//size of array
final static int SIZE = 20;
//main
public static void main(String[] args) {
//populate the array
int [] twentyNumbers = new int [SIZE];
populateTwentyNumbersArray(twentyNumbers);
//sort the numbers using bubble sorting:
bubbleSort(twentyNumbers);
displayTwentyNumbersSorted(twentyNumbers);
//ask the user for a value to search for:
int desiredValue = getValidInteger("Search for a number", 1, 20);
//start the binary search algorithm:
int binSearchComparison = performBinarySearch (twentyNumbers, desiredValue);
System.out.println(binSearchComparison);
}
//Display the 20 integers in the array in ascending-order:
public static void displayTwentyNumbersSorted (int [] numArray){
System.out.println("");
System.out.println("Here are the 20 numbers sorted in ascending-order");
for (int i = 0; i < numArray.length; i++) {
if(i < 19){
System.err.print(numArray[i] + ", ");
}
else{
System.err.print(numArray[i]);
}
}
}
//Perform the binary search for the user's desired value:
public static int performBinarySearch (int [] numArray, int userValue){
int first = 0;
int middle;
int last = (numArray.length - 1);
int iteration = -1;
boolean found = false;
for (int i = 0; i < numArray.length; i++) {
while ((!found) && (first <= last)) {
middle = ((first + last) / 2);
if (numArray [middle] == userValue) {
found = true;
iteration = (i + 1);
}
if(numArray [middle] > userValue) {
last = (middle - 1);
}
if(numArray [middle] < userValue) {
first = (middle + 1);
}
}
}
return iteration;
}
//Populate the array with 20 random integers:
public static void populateTwentyNumbersArray (int [] numArray){
int number = 0;
for (int i = 0; i < numArray.length; i++) {
do{
number = getRandomNumber(1, 20);
}while (checkNum(numArray, number));
numArray[i] = number;
}
}
//Check to make sure the number is unique:
public static boolean checkNum (int [] numArray, int num) {
boolean value = false;
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == num) {
value = true;
}
}
return value;
}
//Sort the array in ascending order
public static void bubbleSort(int [] numArray){
int temp;
int maxElement;
for(maxElement = (SIZE - 1); maxElement > 0; maxElement--){
for(int i = 0; i <= (maxElement - 1); i++){
if(numArray[i] > numArray[i + 1]){
temp = numArray[i];
numArray[i] = numArray[i + 1];
numArray[i + 1] = temp;
}
}
}
}
//Get a valid Integer from the user to determine the number of seats sold per section:
public static int getValidInteger(String msg, int low, int high) {
int newValue = getInteger(msg);
//Check that the user entered a valid number within the range:
while (newValue < low || newValue > high) {
System.err.println("Please enter a number from " + low + " to " + high + ".");
newValue = getInteger(msg);
}
return newValue;
}
//Check for a valid Integer input from the user:
public static int getInteger(String msg) {
System.out.println(msg);
while (!keyboard.hasNextInt()) {
keyboard.nextLine();
System.err.println("Invalid integer. Please try again.");
}
int number = keyboard.nextInt();
keyboard.nextLine(); //flushes the buffer
return number;
}
//Get a random number to represent the computer's choice:
public static int getRandomNumber(int low, int high){
return (int)(Math.random() * ((high + 1) - low)) + low;
}
}
In your performBinarySearch you check for the all values of array, this maximizes the binary search complexity, though the loop hasn't any effect on searching. If the value present in the array, then the searching function checks whether it is present or not when i=0 and make found=true. After that the inner while loop don't executes as found=true all the times.
For that reason, iterator=(i+1) for i=0 all the times if the value is present in the array, otherwise iterator=-1.
Consider the below performBinarySearch function :
public static int performBinarySearch(int[] numArray, int userValue) {
int first = 0;
int middle;
int last = (numArray.length - 1);
int iteration = 0;
boolean found = false;
while ((!found) && (first <= last)) {
iteration++;
middle = ((first + last) / 2);
if (numArray[middle] == userValue) {
found = true;
break;
}
if (numArray[middle] > userValue) {
last = (middle - 1);
}
if (numArray[middle] < userValue) {
first = (middle + 1);
}
}
if (found) return iteration;
else return -1;
}
Here, I have reused your code with a simple modification. I have deleted your redundant outer loop and calculated the number of iteration each time the while loop executes. If found then make found=true and break the loop(as I have already found the expected value) and return the value.
public class Palindrome
{
public static boolean isDoublePalindrome (char[] digits)
{
char[] firstHalf = new char[digits.length/2];
char[] secondHalf = new char[digits.length/2];
for(int a = 0; a < digits.length / 2; a++)
{
firstHalf[a] = digits[a];
System.out.print(firstHalf[a]);
}
for(int b = digits.length / 2; b < digits.length; b++)
{
secondHalf[b] = digits[b];
}
if(digits.length % 2 == 0)
{
for(int i = 0; i < digits.length / 2 - 1; i++)
{
if(digits[i] != digits[digits.length - i - 1])
{
return false;
}
else
{
return true;
}
}
for(int j = 0; j < firstHalf.length / 2 - 1; j++)
{
if(firstHalf[j] != firstHalf[digits.length - j - 1])
{
return false;
}
else
{
return true;
}
}
}
else if(digits.length % 2 != 0)
{
return false;
}
return false;
}
}
Here I take digits[] as parameter and whatever the character array in there I want to divide them into half and store first half into firstHalf and second half into secondHalf array. But when I debug, secondHalf doesn't have any values. Please help!!
method to do so
public int reverse(int num) {
int revNum = 0;
while (num > 0) {
int rem = num % 10;
revNum = (revNum * 10) + rem;
num = num / 10;
}
return revNum;
}
implementation
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num = scanner.nextInt();
System.out.println("Please enter a string: ");
String str = scanner.next();
Palindrome palin = new Palindrome();
int revNum = palin.reverse(num);
if (num == revNum) {
System.out.printf("\n The number %d is a Palindrome ", num);
} else {
System.out.printf("\n The number %d is not a Palindrome ", num);
}
here palindrome is class name of main method hope my works helps you in this regard.
First off, be careful dividing your array length by 2, you may have an odd length (making one half 1 longer than the other).
What happens if "digits" is an odd number length? It can still be a palindrome.
To answer your question, in the second loop your assigning values to secondHalf[b], which is past it's length: "digits.length / 2". You should be assigning values into secondHalf[] starting at zero.
If you're lazy, this could be your way:
public static boolean isPalindrome(String s){
String reverse = new StringBuffer(s).reverse().toString();
if(s.equalsIgnoreCase(reverse))
return true;
else
return false;
}
And if you are not allowed to cheat, this could help you:
public static boolean isPalindrome(String s){
char[] chars = s.toCharArray();
for(int i = 0; i < chars.length / 2; i++){
if(Character.toLowerCase(chars[i]) != Character.toLowerCase(chars[chars.length - 1 - i]))
return false;
}
return true;
}
EDIT: With the second version you also don't encounter the problem of overlooking a character, because if it is a odd number, it would be the middle character that both sides of the string share.
Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and give me right results. It always gives me -1. Any help?
public class BinarySearch {
public static final int NOT_FOUND = -1;
public static int binarySearch(double[] a, double key) {
int low = 0;
int high = a.length -1;
int mid;
while (low<=high) {
mid = (low+high) /2;
if (mid > key)
high = mid -1;
else if (mid < key)
low = mid +1;
else
return mid;
}
return NOT_FOUND;
}
public static void main(String[] args) {
double key = 10.5, index;
double a[] ={10,5,4,10.5,30.5};
int i;
int l = a.length;
int j;
System.out.println("The array currently looks like");
for (i=0; i<a.length; i++)
System.out.println(a[i]);
System.out.println("The array after sorting looks like");
for (j=1; j < l; j++) {
for (i=0; i < l-j; i++) {
if (a[i] > a[i+1]) {
double temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
for (i=0;i < l;i++) {
System.out.println(a[i]);
}
System.out.println("Found " + key + " at " + binarySearch(double a[], key));
}
}
you are not actually comparing with the array values. in
while (low <= high) {
mid = (low + high) / 2;
if (mid > key) {
high = mid - 1;
} else if (mid < key) {
low = mid + 1;
} else {
return mid;
}
}
Instead use this section
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] > key) {
high = mid - 1;
} else if (a[mid] < key) {
low = mid + 1;
} else {
return mid;
}
}
You were correct to find the indexes, but what you were doing is that you were just comparing index number with your key, which is obviously incorrect. When you write a[mid] you will actually compare your key with the number which is at index mid.
Also the last line of code is giving compile error, it should be
System.out.println("Found " + key + " at " + binarySearch(a, key));
Here
if (mid > key)
high = mid -1;
else if (mid < key)
low = mid +1;
else
return mid;
You're comparing index to a value (key) in array. You should instead compare it to a[mid]
And,
System.out.println("Found " + key + " at " + binarySearch(double a[], key));
Should be
System.out.println("Found " + key + " at " + binarySearch(a, key));
public static double binarySearch(double[] a, double key) {
if (a.length == 0) {
return -1;
}
int low = 0;
int high = a.length-1;
while(low <= high) {
int middle = (low+high) /2;
if (b> a[middle]){
low = middle +1;
} else if (b< a[middle]){
high = middle -1;
} else { // The element has been found
return a[middle];
}
}
return -1;
}
int binarySearch(int list[], int lowIndex, int highIndex, int find)
{
if (highIndex>=lowIndex)
{
int mid = lowIndex + (highIndex - lowIndex)/2;
// If the element is present at the
// middle itself
if (list[mid] == find)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (list[mid] > find)
return binarySearch(list, lowIndex, mid-1, find);
// Else the element can only be present
// in right subarray
return binarySearch(list, mid+1, highIndex, find);
}
// We reach here when element is not present
// in array
return -1;
}
I somehow find the iterative version not quite easy to read, recursion makes it nice and easy :-)
public class BinarySearch {
private static int binarySearchMain(int key, int[] arr, int start, int end) {
int middle = (end-start+1)/2 + start; //get index of the middle element of a particular array portion
if (arr[middle] == key) {
return middle;
}
if (key < arr[middle] && middle > 0) {
return binarySearchMain(key, arr, start, middle-1); //recurse lower half
}
if (key > arr[middle] && middle < arr.length-1) {
return binarySearchMain(key, arr, middle+1, end); //recurse higher half
}
return Integer.MAX_VALUE;
}
public static int binarySearch(int key, int[] arr) { //entry point here
return binarySearchMain(key, arr, 0, arr.length-1);
}
}
Here is a solution without heap. The same thing can be done in an array.
If we need to find 'k' largest numbers, we take an array of size 'k' populated with first k items from the main data source. Now, keep on reading an item, and place it in the result array, if it has a place.
public static void largestkNumbers() {
int k = 4; // find 4 largest numbers
int[] arr = {4,90,7,10,-5,34,98,1,2};
int[] result = new int[k];
//initial formation of elems
for (int i = 0; i < k; ++i) {
result[i] = arr[i];
}
Arrays.sort(result);
for ( int i = k; i < arr.length; ++i ) {
int index = binarySearch(result, arr[i]);
if (index > 0) {
// insert arr[i] at result[index] and remove result[0]
insertInBetweenArray(result, index, arr[i]);
}
}
}
public static void insertInBetweenArray(int[] arr, int index, int num) {
// insert num at arr[index] and remove arr[0]
for ( int i = 0 ; i < index; ++i ) {
arr[i] = arr[i+1];
}
arr[index-1] = num;
}
public static int binarySearch(int[] arr, int num) {
int lo = 0;
int hi = arr.length - 1;
int mid = -1;
while( lo <= hi ) {
mid = (lo+hi)/2;
if ( arr[mid] > num ) {
hi = mid-1;
} else if ( arr[mid] < num ) {
lo = mid+1;
} else {
return mid;
}
}
return mid;
}
int BinSearch(int[] array, int size, int value)
{
if(size == 0) return -1;
if(array[size-1] == value) return size-1;
if(array[0] == value) return 0;
if(size % 2 == 0) {
if(array[size-1] == value) return size-1;
BinSearch(array,size-1,value);
}
else
{
if(array[size/2] == value) return (size/2);
else if(array[size/2] > value) return BinSearch(array, (size/2)+1, value);
else if(array[size/2] < value) return (size/2)+BinSearch(array+size/2, size/2, value);
}
}
or
Binary Search in Array
/**
* Find whether 67 is a prime no
* Domain consists 25 of prime numbers
* Binary Search
*/
int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
int min = 0,
mid,
max = primes.length,
key = 67,
count= 0;
boolean isFound = false;
while (!isFound) {
if (count < 6) {
mid = (min + max) / 2;
if (primes[mid] == key) {
isFound = true;
System.out.println("Found prime at: " + mid);
} else if (primes[mid] < key) {
min = mid + 1;
isFound = false;
} else if (primes[mid] > key) {
max = mid - 1;
isFound = false;
}
count++;
} else {
System.out.println("No such number");
isFound = true;
}
}
/**
HOPE YOU LIKE IT
A.K.A Binary Search
Take number array of 10 elements, input a number a check whether the number
is present:
**/
package array;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class BinaryS
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a number: ");
int n=Integer.parseInt(br.readLine());
int a[]={10,20,30,40,50,60,70,80,90,100};
int upper=a.length-1,lower=0,mid;
boolean found=false;
int pos=0;
while(lower<=upper)
{
mid=(upper+lower)/2;
if(n<a[mid])upper=mid-1;
else if(n>a[mid])lower=mid+1;
else
{
found=true;
pos=mid;
break;
}
}
if(found)System.out.println(n+" found at index "+pos);
else System.out.println(n+" not found in array");
}
}
Well I know I am posting this answer much later.
But according to me its always better to check boundary condition at first.
That will make your algorithm more efficient.
public static int binarySearch(int[] array, int element){
if(array == null || array.length == 0){ // validate array
return -1;
}else if(element<array[0] || element > array[array.length-1]){ // validate value our of range that to be search
return -1;
}else if(element == array[0]){ // if element present at very first element of array
return 0;
}else if(element == array[array.length-1]){ // if element present at very last element of array
return array.length-1;
}
int start = 0;
int end = array.length-1;
while (start<=end){
int midIndex = start + ((end-start)/2); // calculate midIndex
if(element < array[midIndex]){ // focus on left side of midIndex
end = midIndex-1;
}else if(element > array[midIndex]){// focus on right side of midIndex
start = midIndex+1;
}else {
return midIndex; // You are in luck :)
}
}
return -1; // better luck next time :(
}
static int binarySearchAlgorithm() {
// Array should be in sorted order. Mandatory requirement
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int lowIndex = 0;
int valueToFind = 8;
int highIndex = a.length - 1;
while (lowIndex <= highIndex) {
//Finding the midIndex;
int midIndex = (highIndex + lowIndex) / 2;
// Checking if midIndex value of array contains the value to be find.
if (a[midIndex] == valueToFind) {
return midIndex;
}
// Checking the mid Index value is less than the value to be find.
else if (a[midIndex] < valueToFind) {
// If Yes, changing the lowIndex value to midIndex value + 1;
lowIndex = midIndex + 1;
} else if (a[midIndex] > valueToFind) {
// If Yes, changing the highIndex value to midIndex value - 1;
highIndex = midIndex - 1;
} else {
return -1;
}
}
return -1;
}
the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for (int i = 1; i < 10; i++) {
if (digits[i] > count) {
count = digits[i];
digit = i;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.