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
How do i skip the number 0 (zero) from this for() statement. I want 0 to be skipped after -1.
for(x=min_values; x<= max_values; x++)
{
}
my aim is to select every number between two textboxes called max and min. I am trying to plot a y = 1/x function. However when 0 is selected because there can not be 1/0 the program does not work.
The 'continue' keyword would accomplish what you're asking given the right logical condition. The example code you gave doesn't say what mix_values or max_values is.
for(int x = mix_values; x <= max_values; x++ ) {
if( x == 0 ) { continue; }
// ...the rest of your loop body logic goes here...
}
I'm assuming 0 would always come after -1 (if min_values < -1) given x++.
Try this inside the for :
if (x == 0 && lastMinValue == -1 ){
continue;
}
int lastMinValue = x;
I'm going to assume that min_values may be negative. You've said:
I want 0 to be skipped after -1.
In that case, just increment x at the end of the loop body when it's -1:
for(x=min_values; x<= max_values; x++)
{
// ...loop body here, then:
if (x == -1) {
++x;
}
}
After that increment, the one in the for loop will kick in and the next x will be 1.
I won't have any effect if min_values is 0, because you said you wanted to skip 0 after -1, suggesting some kind of dependent relationship.
Example in C# on IDEone, and here in JavaScript, which in this case (not generally) works the same way as C#:
var min_values = -2;
var max_values = 2;
var x;
for (x = min_values; x <= max_values; x++) {
console.log(x);
if (x == -1) {
++x;
}
}
Of course, if you just wanted to skip 0, you'd do what was suggested in a comment that you said didn't work:
for(x=min_values; x<= max_values; x++)
{
if (x == 0) {
continue;
}
// ...loop body here
}
...because it does work: Example in C# on IDEone or, again, here in JavaScript as it happens to work the same way in this regard:
var min_values = -2;
var max_values = 2;
var x;
for (x = min_values; x <= max_values; x++) {
if (x == 0) {
continue;
}
console.log(x);
}
Related
So I have this homework assignment that requires me to assign output to labels after I compare two arrays. My problem is that after I compare the two arrays, the output I assign is wrong. I'm supposed to out 'Y' if at a specific index of the two arrays are equal and 'N' if they're not equal but every time I run the code, it outputs 'Y' to all the labels no matter what. How can I fix what is being outputted after the comparison?
private void evaluateStudentAnswers()
{
/* Use a "for" loop to cycle through the answerKey[] and studentAnswers[] arrays, and compare the answers
* in the two arrays at each index. If they match, then increment the global variable "correctAnswers"
* and assign the value 'Y' to the corresponding index in the correctOrIncorrect[] array. if they
* don't match, then increment the global variable "incorrectAnswers" and assign the value 'N' to the
* corresponding indes in the correctOrIncorrec[] array. These two variables will be used to calculate
* the grade percentage.
*/
for (int i = 0; i < studentAnswers.Length; i++)
{
for(int j = 0; j < answerKey.Length; j++)
{
// I think the indexes below are being checked if they're the same and I need to make sure not just the
//indexes are the same but the values as well
if (studentAnswers[i] == answerKey[j])
{
correctAnswers++;
for(int k = 0; k < correctOrIncorrect.Length; k++)
{
correctOrIncorrect[k] = 'Y';
}
}
else
{
incorrectAnswers++;
for (int k = 0; k < correctOrIncorrect.Length; k++)
{
correctOrIncorrect[k] = 'N';
}
}
}
}
}
I think your code can be simplified quite a lot. assuming there's a 1-1 mapping between studentAnswers and answerKey.
for (int i = 0; i < studentAnswers.Length; i++)
{
var studentAnswer = studentAnswers[i];
var answer = answerKey[i];
if (studentAnswer == answer)
{
++correctAnswers;
correctOrIncorrect[i] = 'Y';
}
else
{
++incorrectAnswers;
correctOrIncorrect[i] = 'N'
}
}
All of the arrays are the same size. So when we loop over each answer the student provided, we know we can find the corresponding correct answer in answerKey. Also, the tracking of correct answers also follows the same pattern, for each studentAnswer, we want to record the correctness in correctOrIncorrect, which corresponds to the particular answer the student provided. As such, we only need to perform a single loop, since the i refers to the appropriate index in all the arrays as we're processing.
If studentAnswers.Length == answerKey.Length == correctOrIncorrect.Length
Then
for (int i = 0; i < studentAnswers.Length; i++)
{
if(studentAnswers[i] == answerKey[j])
{
correctAnswers++;
correctOrIncorrect[k] = 'Y';
}
else
{
incorrectAnswers++;
correctOrIncorrect[k] = 'N';
}
}
Since it is an assignment I wont give an answer :) but since you are stuck I encourage you use the guidance below.
These two are unnecessary in your code
inner for-loop on correctOrIncorrect[]
variable "k", you can use "i" instead for correctOrIncorrect value assignment
Since the arrays have to have the same size/order, you only need to loop through them once. Also I find ternary assignments more clear than if blocks:
Func<bool, int> toInt = (b) => b ? 1 : 0;
for (int i = 0; i < studentAnswers.Length; i++)
{
var studentAnswer = studentAnswers[i];
var answer = answerKey[i];
var isCorrect = studentAnswer == answer;
correctOrIncorrect[i] = isCorrect ? 'Y' : 'N';
correctAnswers = isCorrect ? 1 : 0; // toInt(isCorrect)
incorrectAnswers = !isCorrect ? 1 : 0; // toInt(!isCorrect)
}
}
Or in LINQ (just because it's worth learning, but probably not appropriate for homework):
correctOrIncorrect = answerKey.Zip(studentAnswer, (a,b) => a == b ? "Y" : "N").ToArray();
incorrectAnswers = correctOrIncorrect.Count(x => x == "Y");
...
I have written the algorithm below to compute the Levenshtein distance, and it seems to return the correct results based on my tests. The time complexity is O(n+m), and the space is O(1).
All the existing algorithms I've seen only for this have space complexity O(n*m), as they create a matrix. Is there something wrong with my algorithm?
public static int ComputeLevenshteinDistance(string word1, string word2)
{
var index1 = 0;
var index2 = 0;
var numDeletions = 0;
var numInsertions = 0;
var numSubs = 0;
while (index1 < word1.Length || index2 < word2.Length)
{
if (index1 == word1.Length)
{
// Insert word2[index2]
numInsertions++;
index2++;
}
else if (index2 == word2.Length)
{
// Delete word1[index1]
numDeletions++;
index1++;
}
else if (word1[index1] == word2[index2])
{
// No change as word1[index1] == word2[index2]
index1++;
index2++;
}
else if (index1 < word1.Length - 1 && word1[index1 + 1] == word2[index2])
{
// Delete word1[index1]
numDeletions++;
index1++;
}
else if (index2 < word2.Length - 1 && word1[index1] == word2[index2 + 1])
{
// Insert word2[index2]
numInsertions++;
index2++;
}
else
{
// Substitute word1[index1] for word2[index2]
numSubs++;
index1++;
index2++;
}
}
return numDeletions + numInsertions + numSubs;
}
Was a comment, but I feel it is probably suitable as an answer:
Short answer is "no", if you want the true shortest distance for any given inputs.
The reason your code appears more efficient (and the reason that other implementations create a matrix instead of doing what you're doing) is that your stepwise implementation ignores a lot of potential solutions.
Examples #BenVoigt gave illustrate this, another perhaps clearer illustration is ("aaaardvark", "aardvark") returns 8, should be 2: it's getting tripped up because it's matching the first a and thinking it can move on, when in fact a more optimal solution would be to consider the first two characters insertions.
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 6 years ago.
Improve this question
I'm creating an algorithm to solve sudoku's using Constraint Propagations and Local Search ( similar to Norvig's ). For this I keep track of lists of possible values for each of the squares in the sudoku. For each attempt to try to assign a new value to a square I clone the array and pass it to the algorithm's search method recursively. However, somehow this the list is still being altered. The method it concerns is:
List<int>[,] search(List<int>[,] vals)
{
if (vals == null)
return null;
if (isSolved(vals))
return vals;
//get square with lowest amt of possible values
int min = Int32.MaxValue;
Point minP = new Point();
for (int y = 0; y < n * n; y++)
{
for (int x = 0; x < n * n; x++)
{
if (vals[y, x].Count < min && vals[y, x].Count > 1)
{
min = vals[y, x].Count;
minP = new Point(x, y);
}
}
}
for(int i=vals[minP.Y, minP.X].Count-1; i >= 0; i--)
{
//<Here> The list vals[minP.Y, minP.X] is altered within this for loop somehow, even though the only thing done with it is it being cloned and passed to the assign method for another (altered) search afterwards
Console.WriteLine(vals[minP.Y, minP.X].Count + "-" + min);
int v = vals[minP.Y, minP.X][i];
List<int>[,] newVals = (List<int>[,])vals.Clone();
List<int>[,] l = search(assign(minP, v, newVals));
if (l != null)
return l;
}
return null;
}
The list vals[minP.Y, minP.X] is somehow altered within the for loop which causes it to eventually try to pass squares to the assign method that have 1 (or eventually even 0) possible values. The Console.Writeline statement shows that the vals[minP.Y, minP.X].Count will eventually differ from the 'min' variable (which is defined as the same above the for loop).
If anyone could help me out on how the list is altered within this for loop and how to fix it it'd be much appreciated!
Best regards.
EDIT: The methods in which these lists are edited (in a cloned version however):
List<int>[,] assign(Point p, int v, List<int>[,] vals)
{
int y = p.Y, x = p.X;
for (int i = vals[y, x].Count - 1; i >= 0; i--)
{
int v_ = vals[y, x][i];
if (v_ != v && !eliminate(p, v_, vals))
return null;
}
return vals;
}
bool eliminate(Point p, int v, List<int>[,] vals)
{
if (!vals[p.Y, p.X].Remove(v))
return true; //al ge-elimineerd
// Update peers when only 1 possible value left
if (vals[p.Y, p.X].Count == 1)
foreach (Point peer in peers[p.Y, p.X])
if(!eliminate(peer, vals[p.Y, p.X][0], vals))
return false;
else if (vals[p.Y, p.X].Count == 0)
return false;
// Update units
List<Point> vplaces = new List<Point>();
foreach (Point unit in units[p.Y, p.X])
{
if (vals[unit.Y, unit.X].Contains(v))
{
vplaces.Add(unit);
if (vplaces.Count > 1)
continue;
}
}
if (vplaces.Count == 0)
return false;
else if (vplaces.Count == 1)
{
Console.WriteLine("test");
if (assign(vplaces[0], v, vals) == null)
return false;
}
return true;
}
Your problem is with
List<int>[,] newVals = (List<int>[,])vals.Clone();
Array.Clone() doesn't do what you think it does here. List<int>[,] represents a two-dimensional Array of List<int> objects - effectively a three-dimensional array. Since List<int> isn't a basic value type, .Clone() creates a shallow copy of the array.
In other words, it creates a brand new two-dimensional Array which has, for each value, a pointer to the same List<int> that the old one does. If C# let you manipulate pointers directly, you could start changing those, but since it doesn't, any time you access the underlying List<int>, you're getting the same one regardless of whether it's before the Clone() or after.
See the documentation on it here, and some solutions are here and here.
Effectively, you need to rewrite that line so that rather than copying the array itself, it copies all the values into new List<int>'s.
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
Here is my code so far
{
int x = 10;
int p = 40;
bool y = true;
if (y == true)
{
int r = p;
}
{
if (x + r >= 100)
{
Console.WriteLine("Variables are greater than 100!");
}
else
{
Console.WriteLine("Variables are less than 100!");
}
}
Now I'm getting an error that says that "r" does not exist in the current context.
Im new to programming so no hate please!
The error is right, this code:
if (y == true)
{
int r = p;
}
is indeed declaring the integer, but as soon as you close the block, the new variable, in this case r, ceases to exist. It is only visible to the if scope. Declare r just like you did with x and p and you'll be fine.
Problem : as you have declared variable r inside if block, it will not be accessible outside the if block. because r becomes local variable to the if-block.
Solution : you need to move variable declaration of r outside the if block.so that variable r will be available everywhere within that function scope.
Suggestion : you do'nt need to create extra code blocks using curly braces ,try to remove them.
Try This:
int x = 10;
int p = 40;
bool y = true;
int r = 0
if (y == true)
{
r = p;
}
if (x + r >= 100)
{
Console.WriteLine("Variables are greater than 100!");
}
else
{
Console.WriteLine("Variables are less than 100!");
}
Suggestion : if you really want to perform the above operation when boolean variable y becomes true you can simplify the above code without creating extra variable r as below:
Try This:
int x = 10;
int p = 40;
bool y = true;
if (y == true && (x+p)>=100)
{
Console.WriteLine("Variables are greater than 100!");
}
else
{
Console.WriteLine("Variables are less than 100!");
}
Here it is..
if (y == true)
{
int r = p;
}
Your "r" variable is declare in if clause, so it's only known in this clause, not for out side bracket. That's why in the next if clause the "r" variable is not defined.
I write a DFS(depth first search) founction in my C# project A, and it runs OK. Then I build a new c# project B, which has more lines of codes than A. When I run the same founction in project B with the same input data,my VS2008 shows that there is a stack-overflow error.
Can I change the size of Stack in C#?
The founction's name is :FindBlocksFounction().
Codes which cause stack-overflow:
int tempx = nowx + dir[i, 0];
int tempy = nowy + dir[i, 1];
if (tempx < 0 || tempy < 0 || tempx >= m_Bitmap.Height || tempy >= m_Bitmap.Width)
continue;
int next;
next = PointList.FindIndex(t =>
{
if (t.x == tempx && t.y == tempy)
return true;
else
return false;
});//It seems like that FindIndex() in List<> costs some stack room.
if (next == -1)
continue;
if (color[next] == 0)
{
FindBlocksFounction(next);
}
I think best way to convert your Depth First Search algorithm from recursion to using Queue/Dequeue collection. It is a not complex task. Just google it or take a look here:
Non recursive Depth first search algorithm
It will prevent your code from stack size issues for any amount of data.