the code below belongs to binary search algorithm,user enter numbers in textbox1 and enter the number that he want to fing with binarysearch in textbox2.i have a problem with it,that is when i enter for example 15,21 in textbox1 and enter 15 in textbox2 and put brakpoint on the line i commented below,and i understood that it doesnt put the number in textbox2 in searchnums(commented),for more explanation i comment in code.thanks in advance
public void button1_Click(object sender, EventArgs e)
{
int searchnums = Convert.ToInt32(textBox2.Text);//the problem is here,the value in textbox2 doesnt exist in searchnums and it has value 0.
int result = binarysearch(searchnums);
MessageBox.Show(result.ToString());
}
public int binarysearch(int searchnum)
{
string[] source = textBox1.Text.Split(',');
int[] nums = new int[source.Length];
for (int i = 0; i < source.Length; i++)
{
nums[i] = Convert.ToInt32(source[i]);
}
int first =0;
int last = nums.Length-1;
while (1<= nums.Length)
{
int mid = (int)Math.Floor(first+last / 2.0);
if (first > last)
{
break;
}
if (searchnum < nums[mid])
{
last = mid - 1;
}
if (searchnum > nums[mid])
{
first = mid + 1;
}
else
{
return nums[mid];
}
}
return -1;
}
First, when you know you can place a breakpoint on a line, you sure know you can step through the whole program and see what values are in each variable or property. So, go ahead, and debug. Among other things you are probably missing data input validation in your program.
Second, your binary search implementation is missing mid recalculation after first or last is updated and a stop condition in case the number being looked for is not found in the array. You have to break the loop in case first == last, regardless if nums[mid] matches or not — nobody said the number from textbox2 must be in the array.
What does it have to do with binary search? The problem seems to be that you can't read the number out of a textbox. Are you sure it's the right textbox? What is it's Text? Also, if you put the breakpoint ON the line that assigns the value to searchnums, it will be 0, because it hasn't been assigned yet, put the breakpoint on the line AFTER.
OK, first of all, I hope you know that binary search won't work if nums isn't sorted.
That said, there are a few problems in the algorithm. First of all, you're not changing any of the key elements in the loop. You're only changing first and last in the loop and they aren't even used there, so the loop's state doesn't change.
So i guess you meant to have this line in the beginning of the loop:
mid = (first +last)/2;
Besides that, you need to check for the very likely event that the number doesn't exist. which means adding this in the beginning of the loop to:
if (last < first) break;
Which of course means that the first point of the array block has passed the last point, which means the block size is negative. first == last may be legal when you get to the last cell in the array.
And the last point is to initiate last as size-1:
int last = nums.Length - 1;
We're talking about array indexes after all.
Related
so my problem is that I don't know how to go forward in the list and print the next same integer if there is one.
Here is what I have at the moment:
while (list.Contains(input1))
{
Console.WriteLine(input1 + " is at index " + list.IndexOf(input1))
}
I am trying to list all of the integers that are in the list and print the index of them. But not remove after finding one of the integers (this was at least my first idea.).
IndexOf has an overload with two parameters, which allows you to start searching at a later position in the list.
Since this is obviously a learning exercise, I won't spoil it by providing the full code, but rather suggest that you try to implement the following algorithm:
Find the index of input starting at position 0.
If not found (i.e., IndexOf returns -1): we're done. Otherwise:
Print and remember that index.
Start again at step 1, but this time, don't start searching at 0 but at the index you remembered + 1.
You can do the following:
go through the list/array using for statement
for(int i=0; i < list.length; i++) // loop though list
then inside the loop check the value of the current item using if statement:
if(list[i] == input1)
//do smothing
The list[0] represent the first item in the array, which means the index is 0.
so in the example above the i will be the current index so long that you in the loop.
I didn't write the full code for learning purpose in reference to #Heinzi answer.
Hope that could be helpful!
This is an implementation possibility. It is longer than it has to be, but it makes it clearer for beginners how one could tackle this problem.
Since you wanted to only show numbers that come up more than once here is an implementation method. If you want to show numbers that come up only once too just erase everything about lastindex
List<int> yourlist = new List<int> { 1,1,1,1,1,11,2,3,3,4,4,5 };
int input = 0;
input = Convert.ToInt32(Console.ReadLine());
var index = yourlist.IndexOf(input);
//this checks if your input is in the list
var lastindex = yourlist.LastIndexOf(input);
//this does the same but it searches for the last implementation of your input
if (index != -1 && lastindex != index)
//this if checks if your number comes up more than once. IndexOf returns -1 if there is no occurence of your input
{
Console.Write($"the index of {input} is {index}");
for (int i = index+1; i <= yourlist.Count; i++)
//this loop takes the position of the first occurence of your number and then counts up from there
{
var tempindex = yourlist.IndexOf(input, i);
if (tempindex != -1)
//this if lets everything except -1 through
{
Console.Write($" and {tempindex}");
}
}
}
else
{
Console.WriteLine("your number cannot be found twice in the list");
}
I have a recursion assignment where I have to input into console the following data:
On the first line a natural number equal with the number of tiles I have to input on the following lines (in my example the first number is 6).
On the following lines the domino tiles in the following order:
1 2
1 3
3 4
2 3
3 5
4 5
On the last line another number representing the number of tiles that needs to be returned on each separate line (in my example the number is equal with 3).
With this data I have to display all possible combinations of pairs. For each separate line the number the second number from the first pair has to be equal with the first number of the following pair and so on. I had a hint for this assignment where I have to declare an intermediary list that is equal with the function (using recursion from the start) but when I'm trying to run the code it gives me a null exception for the intermediaryList.
In the first instance I read the data as a 2d array but settled with a simple string array where.
This is my code so far, could you help me with a suggestion, how to avoid the null exception?
(sorry if I missed something from the explanation, this is my second post here so far and thank you in advance). Also I have to mention that I'm allowed to use just "using System;" Not allowed to use Linq or anything else.
enter code here
static string[] ReadDominoTiles(int n)
{
string[] input = new string[n];
for (int i = 0; i < n; i++)
{
input[i] = Console.ReadLine();
}
return input;
}
static string[] DominoSolution(string[] dominoTiles, int numberOfPairs)
{
string[] finalList = new string[numberOfPairs];
if (numberOfPairs == 1)
{
return finalList;
}
string[] intermediaryList = DominoSolution(dominoTiles, numberOfPairs - 1);
for (int i = 0; i < intermediaryList.Length; i++)
{
for (int j = 0; j < dominoTiles.Length; j++)
{
// This is where I get the nullref exception, every value from intermediaryList is null
if (intermediaryList[i] != dominoTiles[j] && intermediaryList[j][1] == dominoTiles[j][0])
{
finalList[j] += intermediaryList[j] + " " + dominoTiles[j];
}
}
}
return finalList;
}
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] dominoTiles = ReadDominoTiles(n);
int numberOfPairs = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(DominoSolution(dominoTiles, numberOfPairs));
}
This is where I get the nullref exception, every value from intermediaryList is null
That's correct, you call the function recursively after doing exactly zero work, besides adding a recursion termination condition which returns an array of nulls. So the first time you come out of your recursion you have in intermediaryList a number of null elements, so when you pretend they're strings and try to get intermediaryList[j][1] you'll get a null reference exception.
As to the solution, it's not exactly clear what's with all the arrays you're allocating. Use a List<> with an actual type and do your work properly. Though I hate to break it to you but if I understand your assignment correctly the solution will use backtracking and combinatorics, which is much more code and much better structured than what you have here.
I am new here. I'm trying a C# problem on Leetcode about Longest Common Prefix. I know this problem has been solved MANY times. I'm just having a hard time understanding why my code doesn't work under certain conditions. When the input ["flower","flow","flight"] is put in, it works just fine and get the output "fl". However, when I get to the input ["ab", "a"], I suddenly get an IndexOutOfRangeException. Anyone know why? Here's my code:
public class Solution {
public string LongestCommonPrefix(string[] strs) {
StringBuilder sb = new StringBuilder();
int h = 1;
int count = 0;
if (strs.Length == 1){
return strs[0];
}
for (int i = 0; i<strs[0].Length; i++)
{
if ((strs[0])[i].Equals((strs[h])[i])){
count++;
if (h<strs.Length-1){
h++;
}
}
}
for (int j = 0; j < count; j++)
{
sb.Append((strs[0])[j]);
}
return sb.ToString();
}
}
You can debug by making a simple console app in Visual Studio. I added a Console.Writeline(strs[0] + strs[h]) to your code to demonstrate the logic as is. Running your code in debug, you can step through and see where the exception gets thrown:
Notice that the console prints the same thing each time, and that the strs[h] is only one character long. When you increment the i to 1, you're trying to access the second element of a one element array.
When the input ["flower","flow","flight"] is put in, it works just fine and get the output "fl". However, when I get to the input ["ab", "a"], I suddenly get an IndexOutOfRangeException. Anyone know why?
Because the algorithm as written loops until i has reached the length of the first string, not the shortest string. This is fine for flower/flow/flight because all these strings will find the common prefix "fl" before i comes close to running off the end of the shortest string; i is 2 by the time the algorithm determines that the o in flower is different to the i in flight and hence the code doesn't go out of bounds.
In the ab/a case, i is 1 and the algorithm hasn't yet determined the prefixes have diverged, you attempt to access the nonexistent index 1 on string "a" and get a crash
As comments have pointed out you also have a problem on your h logic; h should be cycled starting from 1 in a loop of its own inside the i loop. As it is now h just increments up to the number of strings-1 and stays there so in essence you end up only looking for prefixes in the first and last strings. If your strings were flower/flight/float/flowing/flowers you'd declare a prefix of "flower" because flight/float/flowing would only be considered when i was 0, 1 and 2 respectively
I suggest you write out the algorithm in comments, in the language you think in then have a go at turning it into c#
Okay, lets assume we have a variable with an array like this
int[] digit;
int x = 5;
for(int i=0;i < = 5; i++)
{ digit[i] = 0;}
All value array on var Digit have 0. So what i want to do its i want to increment the value on that digit from right using Button Control that adds increment (that means digit[4] to digit[3] and so on) and when the value hits certain number example 5 in digit[4], it would come back to value 0 and the next var digit incremented (digit[3]). And the incremented start again and so on.
I already try using if and switch to make this happen like this
private btnClick_Click(Object Sender, Event Args)
{
digit[4] +=1;
if(digit[4] > 5) { digit[3] += 1;}
if(digit[3] > 5) { digit[2] += 1;}
//and so on
switch(digit[4])
{
case 5: digit[4]=0;
}
//and so on
}
But its only for logic If We Know The Array Number Location. Say if i retrieve that number for somewhere like 15 digit. If we set array number so little on that command Button, it cannot fill the array right?
Imma already confused thinking this, any suggestion, help, discussion ill appreciate it. Thanks.
If you just want to increment by one, and not any substraction or increment by let's say 5, I'd use a simple solution like this:
private void btnClick_Click(Object Sender, Event Args) {
int maxValue = 5;
int carry = 1; // This is our increment
// iterate through your digits back to front
for(int i = digit.Length - 1; i >= 0; i--) {
digit[i] += carry; // increase the value by the carry. This will at least increment the last digit by one
carry = 0;
// if we reach our max value, we set the carry to one to add it to the next digit, and reset our current digit to 0.
// If you wanted to increase by more than 1 a time, we would have to add some more calculations here as it would
// be incorrect to just reset digit[i] to 0.
if(digit[i] >= maxValue) {
carry = 1; // the next digit will now be told to increase by one - and so forth
digit[i] = 0;
} else {
break; // This will break out of the for - loop and stop processing digits as everything just fit nicely and we don't have to update more previous digits
}
}
}
Not that once you reach 44444 and increment, you will end up with 00000.
I have a multi-line textbox of sequences, which the game will play one after the other. For example, the textbox may contain this:
RGBY
YGBR
RGBB
I understand that to read the first line of a multi-line textbox, I must write this:
First sequence:
textBox1.Lines[0].Length //Reads first line only for sequence 1
But how can I make it read the next line in a general sense? n+1 where n is the previous line.
New sequence:
textBox1.Lines[0 + 1].Length //Go to next line for future sequences
Any help is appreciated. Thank you in advance!
You need to store the current index in a variable, a field or property in your class.
private int CurrentIndex { get; set; }
Now you can iterate all lines, for example in a button-click event handler where you want to advance to the next line until end:
if (CurrentIndex + 1 < textBox1.Lines.Length)
{
string currentLine = textBox1.Lines[++CurrentIndex];
}
for(int i=0; i < textBox1.Lines.Count(); i++)
{
var currentLine = textBox1.Lines[i];
// do what you want with current line
}