how can i do that someone ?
i had problem about that
Enter the mode: A
Enter the minimal possible integer: 1
Enter the maximal possible integer: 10
I have generated a random integer between 1 and 10.
Try to guess: 5
No. It is smaller!
Try to guess: 3
Done.
Enter the mode: B
Enter the minimal possible integer: 1
Enter the maximal possible integer: 10
Generate a random integer between 1 and 10...
Which method I should use to guess it?
1: Binary search
2: Interpolation search
Enter your choice of the method: 1
Is it 5? (<, >, =)
<
Is it 3?
Done.
Learning different search algorithms is very interesting.
Since you say that you need to learn, I present you the theoretical explanation of both algorithms.
Binary search
This is a computer science search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.
Interpolation search
Instead of calculating the midpoint, interpolation search estimates the position of the target value, taking into account the lowest and highest elements in the array as well as length of the array. This is only possible if the array elements are numbers. It works on the basis that the midpoint is not the best guess in many cases. For example, if the target value is close to the highest element in the array, it is likely to be located near the end of the array.
To find the position to be searched, it uses following formula.
pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]
arr[] -> Array where elements need to be searched
x -> Element to be searched
lo -> Starting index in arr[]
hi -> Ending index in arr[]
Source Wikipedia Binary Search
How you wish to implement them is at your own discretion.
If you are stuck with that and post the code of your attempt, we can help you more.
Related
[Interview Question] I got this question in a recent online interview. I had no clue how to solve it. Can anyone please help me solve this so that I can learn in Java.
Tom is very good in problem-solving. So to test Tom's skills, Jerry asks Tom a graph problem. Jerry gives Tom, an array A of N integers.
A graph is a simple graph, iff it has no self-loop or multi-edges.
Now Jerry asks Tom whether he can design a simple graph of N vertices or not. The condition is that Tom has to use each and every element of A exactly once for the degrees of vertices of the graph.
Now, Tom wants your help to design his graph. Print "YES" if the graph can be designed, otherwise print "NO" (without quotes).
Input
A single integer T, in the first line, denoting the number of test cases.
For each test case, there are 2 lines.
The first line is a single integer N, denoting the number of elements of array A.
The second line has N-space separated integers, representing elements of A.
Output
For each test case, print "YES" or "NO" (without quotes) whether the graph can be designed or not, in a new line.
Constraints
1<= T <= 100
1<= N <= 100
0<= Element of A <= 5000
Sample Test Cases
Input
1
2
1 1
Output
YES
Explanation
For this test case, a simple graph with 2 vertices can be designed, where each vertex has degree 1.
Input
2
3
1 2 1
3
1 1 1
Output
YES
NO
Explanation
For the first test case, we can design a simple graph of 3 vertices, which has degree sequence as [1, 2, 1]. The first vertex has degree 1, second, has 2 and third has 1.
For the second test case, we cannot make a simple graph of 3 vertices, which has degree sequence as [1, 1, 1].
One necessery condition is that sum of elements in A is even. That is due each edge
is counted twice in adjencency list.
Next is to try to construct graph, or at least 'allocate' pairs of nodes.
Sort elements of A in decending order,
Let the largest (first) element be a,
Check are element on positions 2 to a+1 larger than 0,
If there is a element with value 0 than it is not possible to construct a graph,
Decrease these a elements by 1 and set first element to 0,
Repeat process until all elements are 0.
Note that sorting in subsequent steps can be done in O(n) with merge sort step, since list consists
of three sorted parts:
first element (0) which can go to the end,
sorted part with a elements,
rest which is also sorted.
Just thinking about the one algorithm below is the statement for that
Given a matrix, with each node having a value. You start from 0,0 and have to reach n,m. From i,j you can either go to i+1,j or i,j+1. When you step on each block, the value on that block gets added to your current score. What’s the minimum initial score you must carry so that you can always reach n,m(through any possible path) having positive score at the end.
Eg:
Matrix -> 2 3 4
-5 -6 7
8 3 1
Ans -> 6 – for path 2,-5,-6,3,1 we need initial score of 6 so that when we land on 1, we have a positive score of 1
So I can do this using brute force and Dynamic programming, but still thinking for approach which could be better then this, please share ur thoughts, just thoughts/idea I do not need implementation, as I can do this.
There's many search algorithm, i encourage you reading these Wikipedia pages :
https://en.wikipedia.org/wiki/Pathfinding
https://en.wikipedia.org/wiki/Tree_traversal
One possible solution, is to transform the array to graph and apply shortest paths algorithms to it, another solution is to use some IA algorithms such as A*.
Link to Wikipedia for A* (prounced A Star) :
https://en.wikipedia.org/wiki/A*_search_algorithm
ive been trying to the problem and have become stuck. The specification of the problem is a as follows
Median of k numbers is defined as the (k/2)th
smallest number if k is even; and the ((k+1)/2)th
smallest number if k is
odd. For example, median of the 4 numbers: 2 1 8 7 is the 2nd smallest number i.e. 2, and the median of the 5
numbers: 2 1 8 7 6 is the 3rd smallest number i.e. 6.
In this problem, you'll be given N numbers. Let the kth
median or m(k) be defined as the median of the first k
numbers (1<=k<=N). i.e. the 5th
median or m(5) is the median of the first 5 numbers, the 8th
median or m(8) is the
median of the first 8 numbers, etc. In other words, let Ai
denote the ith
number, then the kth
median or m(k) is
defined as the median of the numbers A1, A2, …, Ak.
Your task is to find m(1) + m(2) + m(3) + ...+ m(n), output the sum modulo 100000
so basically you have to read in numbers, first number is stored in the variable N and dictates how many numbers to be read in after that point is. (this is always 5). Then you must iterate through the reading in of the numbers, storing them in array, then sorting them and then finding the median of the median and then store the value in the and repeating until all numbers have been read in, sorted and median found.
I have managed to read the numbers in fine and i am able to sort them to some degree but my sorting algorithm, sorts them highest values first and smallest values last and in order to get the program to run properly to get the desired output i need it to be the other way round and i cant work out how.
The numbers read in will be like so
5
10
5
1
2
15
and the answer would be 27.
This is my code
Any help on this problem would be amazing because im just going round in cirles, btw the System.out.println(myIntArray [4]) etc is just a tracer to see how the sorting is taking place
You seem to be sorting the entire array each time through. You need to sort from 0 to i (exclusive) at each iteration. Also, for odd length, you need parentheses when computing the subscript: myIntArray[(i+1)/2] instead of myIntArray[i+1/2]. Because of operator precedence, Java will evaluate the latter as myIntArray[i+(1/2)], which is just myIntArray[i], since 1/2 is 0 in integer division.
I have a system that generates values in a text file which contains values as below
Line 1 : Total value possible
Line 2 : No of elements in the array
Line 3(extra lines if required) : The numbers themselves
I am now thinking of an approach where I can subtract the total value from the first integer in the array and then searching the array for the remainder and then doing the same until the pair is found.
The other approach is to add the two integers in the array on a permutation and combination basis and finding the pair.
As per my analysis the first solution is better since it cuts down on the number of iterations.Is my analysis correct here and is there any other better approach?
Edit :
I'll give a sample here to make it more clear
Line 1 : 200
Line 2=10
Line 3 : 10 20 80 78 19 25 198 120 12 65
Now the valid pair here is 80,120 since it sums up to 200 (represented in line one as Total Value possible in the input file) and their positions in the array would be 3,8.So find to this pair I listed out my approach where I take the first element and I subtract it with the Total value possible and searching the other element through basic search algorithms.
Using the example here I first take 10 and subtract it with 200 which gives 190,then I search for 190,if it is found then the pair is found otherwise continue the same process.
Your problem is vague, but if you are looking for a pair in the array that is summed to a certain number, it can be done in O(n) on average using hash tables.
Iterate the array, and for each element:
(1) Check if it is in the table. If it is - stop and return there is such a pair.
(2) Else: insert num-element to the hash table.
If your iteration terminated without finding a match - there is no such pair.
pseudo code:
checkIfPairExists(arr,num):
set <- new empty hash set
for each element in arr:
if set.contains(element):
return true
else:
set.add(num-element)
return false
The general problem of "is there a subset that sums to a certain number" is NP-Hard, and is known as the subset-sum problem, so there is no known polynomial solution to it.
If you're trying to find a pair (2) numbers which sum to a third number, in general you'll have something like:
for(i=0;i<N;i++)
for(j=i+1;j<N;j++)
if(numbers[i]+numbers[j]==result)
The answer is <i,j>
end
which is O(n^2). However, it is possible to do better.
If the list of numbers is sorted (which takes O(n log n) time) then you can try:
for(i=0;i<N;i++)
binary_search 'numbers[i+1:N]' for result-numbers[i]
if search succeeds:
The answer is <i, search_result_index>
end
That is you can step through each number and then do a binary search on the remaining list for its companion number. This takes O(n log n) time. You may need to implement the search function above yourself as built-in functions may just walk down the list in O(n) time leading to an O(n^2) result.
For both methods, you'll want to check to for the special case that the current number is equal to your result.
Both algorithms use no more space than is taken by the array itself.
Apologies for the coding style, I'm not terribly familiar with Java and it's the ideas here which are important.
Given a set of integers, how to find a subset that sums to a given value...the subset problem ?
Example : S = {1,2,4,3,2,5} and n= 7
Finding the possible subsets whose sum is n.
I tried to google out found many links,but were not clear.
How can we solve this in java and what is the data structure to be used and its complexity ?
In three steps:
Find the powerset of S (the set of all subsets of S)
Compute the sum of each subset
Filter out subsets that did not sum to 7.
I wont give you any code, but explain how it works.
Run a loop from 0 to (2^k-1)
For each value in 1, a 1 in its binary representation indicates that this value is chosen and 0 otherwise.
Test to see if the sum of chosen numbers is equal to n.
The above method will evaluate each possible subset of the given set.
If the upper limit of the values is small, then Dynamic Programming Approach could be used.