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 6 years ago.
Improve this question
I found it in the net and I want to know the explanation of it's algorithm.
I'm having a hard time to understand this. thank you so much :)
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");
}
}
I'll appreciate your response. thanks again.
The binary search algorithm begins by comparing the target value to the value of the middle element of the sorted array. If the target value is equal to the middle element's value, then the position is returned and the search is finished. If the target value is less than the middle element's value, then the search continues on the lower half of the array; or if the target value is greater than the middle element's value, then the search continues on the upper half of the array. This process continues, eliminating half of the elements, and comparing the target value to the value of the middle element of the remaining elements - until the target value is either found (and its associated element position is returned), or until the entire array has been searched (and "not found" is returned).
Here is your answer beautifully explained :
check this out
http://www.csit.parkland.edu/~mbrandyberry/CS1Java/Lessons/Lesson27/BinarySearch.htm
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have the following binary search method and the following driver code. Both of the values I search for show in the output are present in the array.
Search Method
//Method for binary search. This method will also cut our array
public static int binarySearch(int[] nums, int x) {
//Bounds
int l = 0, r = nums.length - 1;
//While the size of the array is not 1
while (l <= r) {
//Middle element
int m = l + (r - 1) / 2;
//If our element is the middle
if (nums[m] == x) return m;
//If x is greater, cut to right half
else if (x > nums[m]) l = m + 1;
//Else, ignore right half
else r = m - 1;
}
//If we didn't find the element
return -1;
}
Driver code and output
public class searcher {
public static void main(String[] args) {
/* Initialize a new scanner for user input, initialize random for the
computer to pick a number */
Scanner s = new Scanner(System.in);
//Variable for user input
int guess;
//Do-while loop
do {
System.out.println("Enter a number to search for (0 to quit): ");
//Get the user's guess
guess = s.nextInt();
//Search for the guess in the array of numbers
int i = binarySearch(nums, guess);
System.out.println(i);
//If the number is not found
if (i == -1) {
System.out.println("Your number does not occur in this list.");
}
//If it is
else {
System.out.println("Your number occurs at position " + i);
}
} while (guess != 0);
}
}
/*
Output
Enter a number to search for (0 to quit):
1
1
Your number occurs at position 1
Enter a number to search for (0 to quit):
90
<------- Program doesn't stop running from here...? */
I'm expecting to get an output for the index of the number entered if its found, and if not, the method should return -1 so I can print not found
You are subtracting 1 twice.
r = nums.length - 1;
and then
int m = l + (r - 1) / 2;
should be
int m = l + (r - l) / 2;
int m = l + (r - 1) / 2; // this is not correct, you are subtracting "1"
you need to subtract "left" (variable names edited for clarity):
int mid = left + (right - left) / 2;
or, a bit better:
int mid = (left+ right) >>> 1;
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 5 years ago.
Improve this question
the string is 1a2a(3a4) then I am able to extract (3a4) & calculate it, let 'x' be the answer then substitute to main 1a2ax & calculate as normal (which is easy, I have done. ( a - add, s - sub, m - mul, d - div)
for above equation, I have done like this (works only if I have one set of brackets)
public class task2 {
private static double parseString(String str) {
// declaring the operators' counters
int a = 1;
int s = 1;
int m = 1;
int d = 1;
// splitting the string up into operands and operators
double[] operands = Arrays.stream(str.split("[asmd]")).mapToDouble(Double::parseDouble).toArray();
String[] operators = str.split("\\d+");
// the rest is pretty much self-explanatory
double total = operands[0];
for (int i = 1 ; i < operators.length ; i++) { // note that i starts at 1 because the first item in operators
switch (operators[i]) { // array is an empty string
case "a":
total = total * a + operands[i];
a++;
break;
case "s":
total = total * s - operands[i];
s++;
break;
case "d":
total = total * d / operands[i];
d++;
break;
case "m":
total = total * m * operands[i];
m++;
break;
}
}
return total;
}
public static void main(String[] args){
String x= "1a(2a6a16)a9s88s77m9d5";
System.out.print("Expression \""+x+"\" on solving gives answer as ");
//To extract String with Bracket
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(x);
String y = null;
while(m.find()) {
y = m.group(1);
}
String z = Double.toString(task2.parseString(y));
int p = (int)Double.parseDouble(z);
String q = Integer.toString(p);
x = x.replaceAll("\\p{P}","");
x = x.replace(y,q);
// To call method to find value
System.out.println(task2.parseString(x));
}
}
But prob comes when an equation is
((1a3a(9s9s(10d200))s(10m100a(192s187))a10)d2d8)
, when I have to apply the recursive extract of innermost parenthesis until no more parenthesis, which I am struggling with.
firstly (10d200) extracted and calculated, let the answer be "P", the equation becomes ((1a3a(9s9sP)s(10m100a(192s187))a10)d2d8)
secondly (9s9sp) extracted and calculated, let answer be "Q", equation becomes ((1a3aQs(10m100a(192s187))a10)d2d8)
thirdly (192s187) extracted and calculated, let answer be "R", equation becomes ((1a3aQs(10m100aR)a10)d2d8)
forthly (10m100aR) extracted and calculated, let answer be "S", equation becomes ((1a3aQsSa10)d2d8)
fifthly (Td2d8) expression calculated.
Plz, Help me out here. Thanks in advance.
Pseudocode:
while (there are parentheses left) {
find first closing parenthesis;
walk left and find nearest opening parenthesis;
evaluate expression inbetween;
replace expression with result and remove parentheses;
}
evaluate expression;
Edit: Just for completeness, this can be written in a compact way using peg.js: https://jsfiddle.net/mxLq9drm/2
The simplest way would be to always parse the content of the first pair of brackets:
stack s
for i = 0; i < len(text); i++ do
if text[i] is openingbracket
s.push(i)
if next character is closing bracket
pos = s.pop()
res = parse(text, pos + 1, i - 1)
text.replace(pos, i, res) //update the string to parse
i = pos + len(res) //set i to the end of the newly inserted string
The basic idea is to store the indices of all opening-brackets in a stack. If a closing-bracket is encountered, take the string between the last opening-bracket (head of the stack) and the current position, evaluate the expression and replace it in the string. Afterwards update the current position in the string and proceed to parse.
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 6 years ago.
Improve this question
So I'm new to programming. I'm using java. Right now I have an assignment I can't solve on a website that teaches java.
This is the assignment
Write a program that returns number of occurrences of a string in another string.
E.g
Input:
First String: the
Second String: The students are working hard in the faculty of Engineering because they love it
Output:
3
Note: You should only use nested loops. Don’t use methods like indexOf or substring.
Ienter image description here reached to the code the calculate the number of occurrences but it failed in case of repeated letters
E.g
input:
First String : ooo
Second String : wooooooooooooooooooooow
Output : 21
It's supposed to be 7 since the ooo have only repeated 7 times
This question can be simply solved by using z-function in linear time.
int NumberOfcopies(String t, String h){
// t = the first string i.e "ooo"
// h = the second string i.e "wooooooooooooooooooooow"
String s = t + "$" + h; // adding a sentinel character in between
int n = s.length(); // length of new string
int[] z = new int[n]; // z array
// Code ref : http://e-maxx-eng.github.io/string/z-function.html
int l = 0, r = 0;
for (int i = 1; i < n; i++){
if (i <= r)
z[i] = Math.min(r - i + 1, z[i - 1]);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r){
l = i;
r = i + z[i] - 1;
}
}
//checking for all the occurance of string t in string h
int res = 0;
for (int i = t.length() + 1; i < n; ){
if (z[i] == t.length()){
//A copy is found so skip next t.length chars
i += t.length();
++res;
}
else ++i;
}
System.out.println("Number of Occurance : " + res);
return res;
}
The Z-function for this string is an array of length n where
the i-th element is equal to the greatest number of characters
starting from the position i that coincide with the first
characters of s.
This can be exploited to find the number of occurrences of a string t in another string h. Suppose we join the string t and h with a sentinel character in between (Sentinel character is a character that does not occur in either of the strings) to form a new string s.
Lets us calculate the z function in array z[].
Now lets start searching from the character after the sentinel character i.e. the characters of string h. For i-th character in string h ( such that i-th character belongs to string s) if z[i] equals to length of string t (the pattern) then it implies that starting from i-th char, the t.length() chars are same as the first t.length() chars of string s which is what the string t equals.
example :
t = ab
h = aaabaab
s = a b $ a a a b a a b
z = 0 0 0 1 1 2 0 1 2 0
i = 0 1 2 3 4 5 6 7 8 9
for i = 5 we can see that z[i] == t.length(), that means we found a copy. Now to prevent Overlapping solutions, we skip the t.length() chars hence now i = 7
continuing this will get you the result.
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
// a program tells the maximum value we can store in (unsigned integer) a given bits .( 256 for 8 bits)
int counter=0;
int last= 0b11111111;
for(int first=0b00000000;first<=last;counter++)
{
first=first + 1;//adding 1(binary addition)
}
System.out.println("for "+ variable "bits u can store "+counter values");
//variable here 8.
//(1.how to get it from user? 2.how to convert it into binary 0b00000000?)
//how to do this without 0b ,actually in previous version of java
//a program in which if you give 8 bit(in case of unsigned) then it give u maximum values u can store in it, not by using ((2*n)-1).
//code is not only for java 8
// sorry i do not have java 8 i hope the above code will compile without error
thank you in advance
Try this:
long result = 1 << numBits;
If numBits is greater than the size of long, use a double instead (and cast the "1" and "numBits" to double).
how about this
int last = 0;
for(int i = 0; i < bitNum; i++){
last = (last << 1) + 1
}
Scanner s = new Scanner(System.in);
int variable = s.nextInt();
int counter = 0;
long last = (1 << variable) - 1;// = 0b'111....111
for(int first = 0; i <= last; counter++){
first = first + 1;
}
System.out.println("for "+ variable +"bits u can store " + counter + "values");
this code is same with your code, but this code dont use 0b.
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
I have one array of n cells with cell 0 having int 0 and cell 1 with in 2 ect... [0,2,3,4,n...]
My goal is to have the the user select a value(not cell #) in the array, the selected value then becomes a zero ONLY IF both of the following condition below are true:
The user cannot chose a cell that is already a 0
The user cannot chose a number that does not a remaining divisor in the array. For example; the user cannot chose 3, 4 or 7 in an array containing [0,0,3,4,0,6,7,8]
Any number that the user selected to be unavailable will have System.out.println ("Invalid number");
EDIT: My current problem right now is when I have [0,0,0,4,5,6] I can select 4,5 and 6 and turn it into a zero even though there is no divisor for any of these number.
My try for the code, not fully working:
int[] NumBox = new int[StartNum];
for (int i = 1; i < NumBox.length+1; i++)
{NumBox[i - 1] = i;}
if (NumBox[pick-1]!= 0)
{
boolean hasDivisor = false;
for (int k = 1; k < NumBox.length+1; k++)
{
if (NumBox[k] == 0)
continue;
if (NumBox[pick-1] % NumBox[k] == 0)
{
hasDivisor = true;
break;
}
}
if (hasDivisor)
{
score1 = pick + score1;
NumBox[pick-1]=0;
}
else
System.out.println ("Invalid number");
}
Thanks for any help.
You don't say what the problem is with your current code, but I'm guessing that you probably want to change this test:
if (NumBox[pick-1] % NumBox[k] == 0)
to this:
if (NumBox[pick-1] > NumBox[k] && NumBox[pick-1] % NumBox[k] == 0)
That way you won't consider a number as its own divisor.
Ok.. here's an approach.
1. Sort the array in ascending order.
2. For a given number/input say "n" at index say "i",
if any number before index "i" has number!=0 && n%number ==0, then it is divisible. Else, it is not divisible
Simple approach is this
1. Sort the array in ascending order.
2. Now when the user selects a number, keep testing
the mod value from start until root(N) of that number.
If none mods to zero, then it doesn't have any divisors.
The first part should be easy, the second part would be something like this pseudocode
boolean flag=false;
if(!(pick==0)){ // testing if it is already is not zero
for (int i = 0; i < args.length; i++) {
if(pick%NumBox[i]==0){
//divisor found
flag=true;
break;
}else if(NumBox[i]>Math.sqrt(pick)){
//No divisors found
break;
}
}
}
if(flag==true){
pick=0;
}