Invalid expression term '&&' [duplicate] - c#

This question already has an answer here:
Invalid expression term
(1 answer)
Closed 4 years ago.
I copy the code straight out of the text book and it doesn't work.
Here's the code:
public void BinarySearch(int[] numlist, int value)
{
int min = 0;
int max = numlist.Length - 1;
int index = -1;
while (min <= && index == -1)
{
int mid = (min + max) / 2;
if (value > numlist[mid])
{
min = mid + 1;
}
else if ( value< numlist[mid])
{
max = mid - 1;
}
else
{
index = mid;
}
}
return index;
}
The error I get is:
"Invalid expression term '&&'"
What have I done wrong? I have battled this before and not found an answer for it on StackOverflow.

You want to compare min with max not && and that condition have two part
then the code would be (from what I am seeing BainarySearch):
public void BinarySearch(int[] numlist, int value)
{
int min = 0;
int max = numlist.Length - 1;
int index = -1;
while (min <=max && index == -1)
{
int mid = (min + max) / 2;
if (value > numlist[mid])
{
min = mid + 1;
}
else if ( value< numlist[mid])
{
max = mid - 1;
}
else
{
index = mid;
}
}
return index;
}

You are missing a value in your while condition:
while (min <= [here goes your value] && index == -1)

problem is min <= ? what
while (min <= && index == -1)

Related

Algorithm for the implementation of merge sort using link array(pointers)

int a[SIZE];
int link[SIZE];
int MergeLists(int i, int j)
{
int head;
int *pprev = &head;
while((i != -1) && (j != -1)){
if(a[i] <= a[j]){
*pprev = i;
pprev = &link[i];
i=*pprev;
} else {
*pprev = j;
pprev = &link[j];
j=*pprev;
}
}
if(i == -1)
*pprev=j;
else
*pprev=i;
printf("%d head",head);
return head;
}
int MergeSort(int low, int end)
{
int mid, i, j;
if((end - low) == 0){
return low;
}
if((end - low) == 1){
link[low] = -1;
return low;
}
if((end - low) == 2){
if(a[low] <= a[end-1]){
link[low] = end-1;
link[end-1] = -1;
return low;
} else {
link[end-1] = low;
link[low] = -1;
return end-1;
}
}
mid = (low+end)/2;
i = MergeSort(low, mid);
j = MergeSort(mid, end);
return MergeLists(i, j);
}
int main()
{
int i;
for(i=0;i<SIZE;++i)
{
printf("\nenter element number %d: ",i+1);
scanf("%d",&a[i]);
}
i = MergeSort(1, SIZE);
do{
printf("%3d", a[i]);
i = link[i];
}while(i != -1);
return 0;
}
to implement merge sort using link array(pinters)
error is given below
input 4 5 2 1
output 1 2 5
MergeLists() uses head for the start of a list (the old code uses link[0]), and -1 for the end of a list (the old code uses 0). This allows sorting of a[0] to a[n-1] (the old code was sorting a[1] to a[n], with a[0] unused).
Well, it seems to be a minor problem, just change the function call in main to
i = MergeSort(0, SIZE);
In C or C++, the index starts with 0, and it is also true when we try to write a function.

Apply indexing in binary search for string

I'm getting the error of not being able to apply indexing, but I'm not sure how establish a 'bounds'(algebraically) for the BinarySearch to find a string. It's apparent that
if (item > N[mid])
can't function because item is a string. How do I find item in this?:
public static int BinarySearch(string[] name, string item)
{
int min = 0;
int N = name.Length;
int max = N - 1;
do
{
int mid = (min + max) / 2;
if (item > N[mid])
min = mid + 1;
else
max = mid - 1;
if (name[mid] == item)
return mid;
//if (min > max)
// break;
} while (min <= max);
return -1;
}
and trying to appease it with something like this
public static int BinarySearch(string[] name, string searchKeyword)
{
int min = 0; //=0
int N = name.Length; //.Length
int max = N - 1;
int S = searchKeyword.Length;
do
{
int mid = (min + max) / 2;
if (S > N[mid])
min = mid + 1;
else
max = mid - 1;
if (name[mid] == S)
return mid;
//if (min > max)
// break;
} while (min <= max);
return -1;
}
You cannot use the > operator in a string because C# does not know what do you mean when saying that a string is bigger than another. Do you compare by length, alphabetical order...?.
If you want to sort them alphabetically, use the String.Compare method instead:
public static int BinarySearch(string[] name, string item)
{
int min = 0;
int N = name.Length;
int max = N - 1;
do
{
int mid = (min + max) / 2;
if (String.Compare(item, name[mid]) > 0)
min = mid + 1;
else
max = mid - 1;
if (String.Compare(item, name[mid]) == 0)
return mid; //if (min > max)
// break;
} while (min <= max);
return -1;
}

How to process an array correctly

Here's the part 1 of my question, if you wanna check the background of this question :
Detecting brackets in input string
Forgive me if the title doesn't match, since I also confused how to name it appropriately to picture my problem. If anyone knows a more appropriate title, feel free to edit.
So, given below code (my own code) :
private const int PARTICLE_EACH_CHAR = 4;
/*ProcessBarLines : string s only contains numbers, b, [, and ]*/
private int ProcessBarLines(Canvas canvas, string s, int lastLineAboveNotation)
{
List<int> bracket = new List<int>();
List<int> other = new List<int>();
int currentCloseNumber = 0;
int currentOpenNumber = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '[')
{
bracket.Add(i);
currentOpenNumber++;
if (i - 1 > 0 && s[i - 1] != '[')
{
currentOpenNumber = 1;
}
}
else if (s[i] == ']')
{
bracket.Add(i);
currentCloseNumber++;
if (i + 1 >= s.Length || s[i + 1] != ']' || currentOpenNumber == currentCloseNumber)
{
int min = bracket.Count - (currentCloseNumber * 2);
int max = bracket[bracket.Count - 1];
List<int> proc = new List<int>();
int firstIndex = -1;
int lastIndex = -1;
for (int ii = 0; ii < other.Count; ii++)
{
if (other[ii] > min && other[ii] < max)
{
proc.Add(other[ii]);
if (firstIndex == -1)
{
firstIndex = ii;
lastIndex = ii;
}
else
{
lastIndex = ii;
}
}
}
double leftPixel = firstIndex * widthEachChar;
double rightPixel = (lastIndex * widthEachChar) + widthEachChar;
DrawLine(canvas, currentCloseNumber, leftPixel,
rightPixel, lastLineAboveNotation * heightEachChar / PARTICLE_EACH_CHAR);
lastLineAboveNotation += currentCloseNumber - 1;
currentOpenNumber -= currentCloseNumber;
currentCloseNumber = 0;
}
}
else
{
other.Add(i);
}
}
return lastLineAboveNotation + 1;
}
Here's the test cases :
Picture 1 & 2 is the correct answer, and picture 3 is the wrong answer. Picture 3 should have a line, just like inverted from number 2, but, apparently, (if you look closely) the line is drawn on the right, but it should be on the left to be correct (above 0).
I figured, the problem is, I'm quite sure on the "min". Since it doesn't give the correct starting value.
Any idea on this? Feel free to clarify anything. It's used for writing numeric musical scores.
Btw, DrawLine() just meant to draw the line above the numbers, it's not the problem.
Finally! I found it!
private int ProcessBarLines(Canvas canvas, string s, int lastLineAboveNotation)
{
List<int> bracket = new List<int>();
List<int> other = new List<int>();
int currentCloseNumber = 0;
int currentOpenNumber = 0;
int space = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '[')
{
bracket.Add(i);
currentOpenNumber++;
if (i - 1 > 0 && s[i - 1] != '[')
{
currentOpenNumber = 1;
}
}
else if (s[i] == ']')
{
bracket.Add(i);
currentCloseNumber++;
if (i + 1 >= s.Length || s[i + 1] != ']' || currentOpenNumber == currentCloseNumber)
{
int min = bracket[Math.Max(bracket.Count - ((currentCloseNumber * 2) + space), 0)];
int max = bracket[bracket.Count - 1];
space = max - min - 1;
List<int> proc = new List<int>();
int firstIndex = -1;
int lastIndex = -1;
for (int ii = 0; ii < other.Count; ii++)
{
if (other[ii] > min && other[ii] < max)
{
proc.Add(other[ii]);
other[ii] = -1;
if (firstIndex == -1)
{
firstIndex = ii;
lastIndex = ii;
}
else
{
lastIndex = ii;
}
}
}
double leftPixel = firstIndex * widthEachChar;
double rightPixel = (lastIndex * widthEachChar) + widthEachChar;
DrawLine(canvas, currentCloseNumber, leftPixel,
rightPixel, lastLineAboveNotation * heightEachChar / PARTICLE_EACH_CHAR);
lastLineAboveNotation += 1;
currentOpenNumber -= currentCloseNumber;
currentCloseNumber = 0;
}
}
else
{
other.Add(i);
}
}
return lastLineAboveNotation + 1;
}
If someone got a more efficient code, please let us know!

Divisors of triangle numbers (Euler 12)

I have found a couple of topics related to this very problem, I just want to know why my code returns incorrect data.
So we have to find the first triangle number having more than 500 divisors. Details can be found here: http://projecteuler.net/problem=12
And here is my code:
Int64 triangularnum = 1;
for (Int64 num = 2; num > 0; num++)
{
if(has501Divisors(triangularnum))
{
MessageBox.Show(triangularnum.ToString());
break;
}
triangularnum += num;
}
private bool has501Divisors(Int64 candidate)
{
bool has501 = false;
int count = 0;
for (int i = 1; i < Math.Sqrt(candidate); i++)
{
if (candidate % i == 0) count += 1;
if (count > 501)
{
return true;
}
}
return has501;
}
This gives me number 842161320 which is apparently incorrect.
You should increment your count number by 2 not 1.
Also your
if (count > 501)
part is incorrect because your boundary should 500 not 501. Change it to count > 500 instead of.
static void Main(string[] args)
{
Console.WriteLine(Find());
}
public static int Find()
{
int number = 0;
for (int i = 1; ; i++)
{
number += i; // number is triangle number i
if (CountDivisorsOfNumber(number) > 500)
return number;
}
}
private static int CountDivisorsOfNumber(int number)
{
int count = 0;
int end = (int)Math.Sqrt(number);
for (int i = 1; i < end; i++)
{
if (number % i == 0)
count += 2;
}
if (end * end == number) // Perfect square
count++;
return count;
}
This prints 76576500 and looks like a right solution.
The problem is you are limiting your loop to the square root, which is smart, however that means you need to increment your count by two, not by 1 to account for both divisors.
Change your incrementation to this:
if (candidate % i == 0) count += 2;
Additionally, your count check checks for greater than 501 divisors, not 500.
Quick look but your check isn't ok:
if (count > 501)
This will stop at count 502, not 501.
for (int i = 1; i < Math.Sqrt(candidate); i++)
9 is divisible by 3, so you should use <= here. Also, you're divising by 1, you should start at i = 2.

Checking for prime number - C# logic

Here is a snippet from my code. Basically once the button is clicked this logic should fire out and determine if the number is prime or not. The problem is that some numbers are returning as "not prime", when in reality they are. Can anyone point out where the flaw is?
Thank you
private void bntTestPrime_Click(object sender, EventArgs e)
{
int num;
double num_sqrt;
int num_fl;
num = Convert.ToInt32(txtInput.Text);
num_sqrt = Math.Sqrt(num);
num_fl = Convert.ToInt32(Math.Floor(num_sqrt));
for (int i = 1; i <= num_fl; i++)
{
if (num % i == 0 && i != num)
lblResult_prime.Text = "Number " + num + " is not Prime.";
else
lblResult_prime.Text = "Number " + num + " is Prime.";
}
}
To add to Blender's answer, I'd like to point out that you're simply setting the output text on every iteration loop. That means your result will only depend upon the last number checked. What you need to do is assume the number is prime and loop through until a divisor is found. If a divisor is found. The number is prime if and only if no divisors are found. In the end the code should look something like this:
private bool IsPrime(int num)
{
double num_sqrt = Math.Sqrt(num);
int num_fl = Convert.ToInt32(Math.Floor(num_sqrt));
for (int i = 2; i <= num_fl; i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
private void bntTestPrime_Click(object sender, EventArgs e)
{
int num = Convert.ToInt32(txtInput.Text);
bool isPrime = IsPrime(num);
if (isPrime)
lblResult_prime.Text = "Number " + num + " is Prime.";
else
lblResult_prime.Text = "Number " + num + " is not Prime.";
}
1 is a factor of every number, so you shouldn't check it. Start at 2. Also, you're already looping from 2 to sqrt(num), so there's no way for i to be equal to num.
You can decrease the performance hit on checking large numbers by using a conditional to check the first 4 primes, then start the loop at 11 and increment by 2. Something like this:
private bool IsPrime(int num)
{
double num_sqrt = Math.Sqrt(num);
int num_fl = Convert.ToInt32(Math.Floor(num_sqrt));
if (num !=1 && num !=2 && num != 3 && num != 5 && num != 7 && num % 2 > 0 _
&& num % 3 > 0 && num % 5 > 0 && num % 7 > 0)
{
for (int i = 11; i <= num_fl; i+=2)
{
if (num % i == 0)
{
return false;
}
}
}
else
return false;
return true;
}
You can shorten your code and increase the performance tremendously by using a List of primes that go big enough to cover the upper limit you want to check. Then use the Contains method to test for prime.
Try the code below.
bool IsPrime(int number) {
if(number%2==0 && number!=2) return false; //no need to check for even numbers
for (int i = 2; i < number; i++) {
if (number % i == 0 && i != number) return false;
}
return true;
}
Try this code below:
bool isPrimeNubmer(int n)
{
if (n >=0 && n < 4) //1, 2, 3 are prime numbers
return true;
else if (n % 2 == 0) //even numbers are not prime numbers
return false;
else
{
int j = 3;
int k = (n + 1) / 2 ;
while (j <= k)
{
if (n % j == 0)
return false;
j = j + 2;
}
return true;
}
}
public class PrimeChecker
{
public static bool Prime(int m)
{
for (int i =2; i< m; i++)
{
if (m % i ==0)
{
return false ;
}
}
return true;
}
public static void Main()
{
Console.WriteLine(Prime(13));
}
}

Categories

Resources