Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given an array of n integers A[0…n−1], such that ∀i,0≤i≤n, we have that |A[i]−A[i+1]|≤1, and if A[0]=x, A[n−1]=y, we have that x<y. Locate the index j such that A[j]=z, for a given value of z, x≤ z ≤y
I dont understand the problem. I've been stuck on it for 4 days. Any idea of how to approach it with binary search, exponential search or interpolation search recursively? We are given an element z find the index j such that a [j] = z (a j) am i right?.
This:
| A[i]−A[i+1] | ≤ 1
means that each element in your array will be at most one different(-ve or +ve). It then follows that the closest index that can contain z from the current is |A[cur] - z| spaces away.
So, what you do is start with j=0, and figure it out for each step. Jump that many spaces, and check again. Eventually you'll find z or reach the end.
public static int findZ(int[] a, int z){
int j = 0;
while(j < a.length){
if(a[j] == z)
return j
j += Math.abs(a[j] - z);
}
return -1;
}
This isn't a binary or exponential search, and it's not recursive, but it's simple and gets the job done. It works as a one-sided interpolation search. See below for the two-way method. You can turn it into a recursive function, but that should be straightforward and I'll leave that to you.
It runs in O(n), where your worst case performance is going to be on something like {0,0,0,0,1}, where it can only jump one step, and turns into a straight linear search.
Best case will be ordered, distinct members like {0,1,2,3,4,5}, where it will only perform one jump.
Edit:
In the interests of making this more "interpolation search-like", let's move both the upper and lower bounds at the same time. The same logic applies for both ends:
public static int findZ(int[] a, int z){
int j = 0;
int k = a.length - 1;
while(j <= k){
if(a[j] == z)
return j
if(a[k] == z)
return k;
j += Math.abs(a[j] - z);
k -= Math.abs(a[k] - z);
}
return -1;
}
It still ends up as O(n) overall worse case, but this is normal for an interpolation search.
Now your worst case is more like {0,0,0,1,0,0,0}, and your best is like {0,1,2,3,2,1,0}.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I came across this algorithm on a coding site (There was no author's information) which counts all prime numbers less than a given limit. It looks very similar to SoE algorithm but it is different in the way it counts the primes:
public int countPrimes(int n) {
if (n < 3) return 0;
boolean[] s = new boolean[n];
int c = n / 2;
for (int i = 3; i < Math.sqrt(n); i += 2) {
if (s[i]) continue;
for (int j = i * i; j < n; j += 2 * i) {
if (!s[j]) {
c--;
s[j] = true;
}
}
}
return c;
}
It sets the initial count to half the limit then decrement it, but I can not seem to understand why does this work. Can anyone please explain?
First of all, the boolean array s represents SoE.
The first loop iterates odd numbers from 3 to sqrt(n) (Because all even except 2 is not prime).
At the 6th line, If i is already in the s, continue to next odd number. If not, add all multiple of i that is less or equal to n to s in the second loop.
In addition, the second loop starts from i*i because all multiple of i smaller than i*i are already checked in prior loops.
The count is initialized to n/2 because all even numbers (except 2) are not primes.
And then the loop below can start checking from multiples of 3.
If a new non-prime is found (!s[j]), the count of primes (c) is decreased.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am in a intro to Java class. I seem to be having trouble figuring out the algorithm for how i want to go about this.
Currently I need to create and application that generates the number to store in an array element by summing its index and the individual digits of the index. For example, the element with index 17 should be stored as 25... (17+1+7=25) and an element with index 2 would store as 4 (2+0+2=4). I need the program to have 101 elements and then display each value.
I seem to be having trouble figuring out the algorithm for how i want to go about this. Any assistance in the matter would be greatly appreciated.
Thanks in advance. I currently am still researching this matter and am still learning to code so please bear with me.
This is the updated code that I have come up with so far
import java.util.Random;
public class Java_Lab_4 {
public static void main(String[] args) {
int size = 101;
int max = 101;
int[] array = new int[size];
int loop = 0;
Random generator = new Random();
//Write a loop that generates 101 integers
//Store them in the array using generator.nestInt(max);
generator.nextInt(max);
for (int i = 0; i<101; i++)
{
generator.nextInt(max);
}
}
There are surely many ways to achieve this, but the easiest would be repeated division by 10 (another way would be modular arithmetic, taking the index modulo 10).
This means that you would arrive at something like the following algorithm:
int n = i; // i is the index of the current item
while (n > 0) {
int x = n;
if (x > 10) { // we need to deal with the case where i is small
x = n / 10;
}
while (x > 10) { // necessary because we may be dealing with an index > 100
x = x / 10;
} // at this point we have the first digit of the index
a[i] += x; // add this digit to a[i]
n = n / 10; // get rid of the above digit in the calculation. Note that if n < 10, integer division means that n / 10 == 0
} // at the end of this loop, we have added all digits of i to a[i]
a[i] += i; / now we only need to add the index value itself
There are many ways to solve this, and this is a very straightforward and basic approach. I've added ample comments, but please try to work through the code to understand why this works rather than just copying it.
Without posting complete code -- because this is an assignment -- here are some things to consider:
array[a] = a + a;
would give you the solution for indices where a < 10. For two/three digit indices, you need to extract the digits with for example
int nthDigit = Integer.parseInt( // Finally, converts the single-char String to an int
String.valueOf( // converts the char matching the digit to a String
String.valueOf(a).charAt(n))); // converts 'a' first to a String and
// then takes its 'n'th character
where n is 0, 1 or 2. The values of these would then need to be added to the value of the index (a).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need to modify the below code to use binary search to return the Index of an Insertion Point in a sorted Array
for Instance if objArray={1,2,4} and searchObj=3
the binarysearch function should return 2 as the Index where 3 should be inserted
public int binarySearch(Comparable[] objArray, Comparable searchObj)
{
int low = 0;
int high = objArray.length - 1;
int mid = 0;
while (low <= high)
{
mid = (low + high) / 2;
if (objArray[mid].compareTo(searchObj) < 0)
{
low = mid + 1;
}
else if (objArray[mid].compareTo(searchObj) > 0)
{
high = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
Thanks
Your code is a Binary Search, which returns the index of the element or -1 if it didn't exists at all.
If you just need to return the index where it should be inserted, then you should change your line return -1; to return mid;.
But keep in mind that this approach will return either the index of that element OR the index where it should be inserted. So you will need another test to identify if the item already exists in your array.
Maybe, a better approach would be to use a Binary Tree.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can someone explain to me how to store the previous two fibbonnaci numbers it would help alot in this problem.
public static void main(String[] args) {
int k = 0;
for (int x = 1; x < 13; x++) {
if (k > 2) {
k = (k - 1) + (k - 2);
}
System.out.print(k+" ");
k++;
}
}
when you got number 5 as the printed out put you will set k++ , that will make k=6.
after that k = (k - 1) + (k - 2); output k = (6-1)+(6-2) = 5+4 = 9 , (note : the next should be 8 so your algorithm is wrong)
You have mistaken the Idea of Fibonacci numbers.
the nth Fibonacci number is equal to the sum of previous two Fibonacci numbers. not to the (Fn-1)+(Fn-2)
Edited :
So as you can see if we know the first 2 Fibonacci numbers we can calculate the third by adding those two. and the fourth one will be the summation of second one and third one and it goes ..... to n.
Okay here is a way that you don't need a recursive approach ( you need to store the found Fibonacci numbers in an Array)
okay assume you want to find first n Fibonacci numbers. then create an array of size n and set first and second elements to one (1) since first two Fibonacci numbers are 1 and 1. now loop through the array from 2 to n. at each iteration add the previous two element to the next element.
go through the code. you will find it very easy to do.
public static void fib(int n){
int Fibonacci [] = new int[n];
Fibonacci [0]=1;
Fibonacci [1]=1;
for (int i = 2; i < n; i++) {
Fibonacci [i]=Fibonacci [i-1]+Fibonacci [i-2];
}
System.out.println(Arrays.toString(Fibonacci ));
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public static int binsrch (int[] a, int key) {
int low = 0;
int high = a.length - 1;
while (true) {
if (low > high) return -(low+1);
int mid = (low + high)/2;
if (a[mid] < key) low = mid + 1;
else if (a[mid] > key) high = mid - 1;
else return mid;
}
Can anybody help?
There are at least two, possibly three, things I can see wrong with it.
It uses (low + high)/2. The addition may overflow to a negative number if the array is very large. If so, division by 2 will lead to a negative index. This can be fixed by using (low + high)>>>1.
It is not documented. I am guessing that it is intended to return the match index if it finds the key in the array, and a negative value on miss. I am not sure exactly what the negative result is supposed to represent, due to the lack of documentation.
Depending on the missing specification, there may be additional problems.